Springboot Servlet注册
1)、代码注册通过ServletRegistrationBean、 FilterRegistrationBean 和ServletListenerRegistrationBean 获得控制
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/xs/*");}
2)、在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
@SpringBootApplication
@ServletComponentScan
public class SpringBootSampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSampleApplication.class, args);
}
}
3)、Servlet需要继承HttpServlet类
public class LiyjServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("this is liyjServlet doposet method");
PrintWriter pw = resp.getWriter();
pw.write("hello springboot servlet register by LiyjServlet");
pw.flush();
pw.close();
}
@Override
public void init() throws ServletException {
super.init();
}
}
/**
* 这里是通过代码的形式注册一个Servlet,这种形式不需要@ServletComponentScan注解
*
* @return
*/
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new LiyjServlet(),"/web/*");
}
手动注册一个servlet
/**
* 带 @WebServlet注解的Servlet注册需要@ServletComponentScan注解的扫描
*
*/
@WebServlet(urlPatterns="/jeff/*")
public class ShanServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("this is ShanServlet doposet method");
PrintWriter pw = resp.getWriter();
pw.write("hello springboot servlet register by ShanServlet");
pw.flush();
pw.close();
}
@Override
public void init() throws ServletException {
super.init();
}
}
filter测试类请看com.vk.liyj.filter.LiyjFilter
Listener测试类请看 com.vk.liyj.listener.LiyjListener
http://localhost:8080/web/hello
http://localhost:8080/web/jeff
源码下载:http://download.csdn.net/download/liyuejin/9986140