Spring boot中注册Servlet

如何在spring boot项目中注册Servlet呢?

由于没有web.xml,无法直接在xml中配置,但是spring boot提供了另外两种更为简洁的方式:

一. java代码实现servlet注册

1.创建servlet类。(一贯作风,直接上code,简单粗暴有效)

public class WeChatServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
                        throws ServletException, IOException {

    String signature = req.getParameter("signature");
    String timestamp = req.getParameter("timestamp");
    String nonce = req.getParameter("nonce");
    String echostr = req.getParameter("echostr");
    PrintWriter out = resp.getWriter();
    if (ValidUtil.checkSignature(signature, timestamp, nonce)) {
      out.print(echostr);
    }
  }
}

2.在主类中注册

@SpringBootApplication
public class MyAppliction extends SpringBootServletInitializer {

    public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
    }
       
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
       return application.sources(MyApplicaitioni.class);
    }

    // 注册servlet
    @Bean
    public ServletRegistrationBean weChatValid(){
      //第一个参数是第1步中创建的WeChatServlet实例,第二个参数是其对应的路径,相当于web.xml中配置时的url-pattern。
      return new ServletRegistrationBean(new WeChatServlet(), "/weChatValid");
    }
}

多个了weChatValid函数(注意要用@Bean注解),其中,返回ServletRegistrationBean的实例,其中两个参数…(自己看代码中注释0)。

完毕。

二、注解实现Servlet注册

1.创建Servlet类,并添加注解。

//注解实现
@WebServlet(urlPatterns = "/weChatValid", description = "微信接口验证")
public class WeChatServlet extends HttpServlet { 
  protected void   doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException { 
      String signature = req.getParameter("signature"); 
      String timestamp = req.getParameter("timestamp"); 
      String nonce = req.getParameter("nonce"); 
      String echostr = req.getParameter("echostr"); 
      PrintWriter out = resp.getWriter();
      if (ValidUtil.checkSignature(signature, timestamp, nonce)) {
          out.print(echostr); 
      } 
    }
}

类前多了个@WebServlet注解,参数urlParttern和descriptiion不言而喻。

2.给主类添加一个注解@ServletComponentScan

@ServletComponentScan //添加的注解
@SpringBootApplication
public class MyAppliction extends SpringBootServletInitializer {

    public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
    }
       
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
       return application.sources(MyApplication.class);
    }
}

多了个@ServletComponentScan注解。

完毕。

此时访问该Servlet的url就可以是:

http://localhost:8080/weChatValid

另外,还有一种方法:

@RestController
public class Servlet2 extends HttpServlet {
    @RequestMapping("/serv2")//urlPatterns

url:

http://localhost:8080/ser2

搞定!

posted @ 2020-03-13 18:12  shimmernight  阅读(515)  评论(0编辑  收藏  举报