一般情况下,使用Spring、SpringMvc这些框架后,基本告别了Servlet、Filter、Listener。
但是在整合第三方框架时,可能还是会使用到Servlet,比如整合某报表插件时需要使用Servlet。
SpringBoot对整合这些基本的Web组件也提供了很好的支持。
1.整合Servlet
@WebServlet("/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("name: "+req.getParameter("name"));
}
}
2.整合Filter
@WebFilter("/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("myfilter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("myfilter dofilter");
filterChain.doFilter(servletRequest, servletResponse); //放行
}
@Override
public void destroy() {
System.out.println("myfilter destory");
}
}
3.整合Listener
//这里使用的是ServletRequestListener。
//对于HttpSessionListener和ServletContextListener等也是支持的。
@WebListener
public class MyListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("servletRequestListener requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("servletRequestListener requestInitialized");
}
}
4.启动类开启Servlet组件扫描,让Web组件生效
@SpringBootApplication
@ServletComponentScan
public class RunnerApplication {
public static void main(String[] args) {
SpringApplication.run(RunnerApplication.class, args);
}
}
5.测试
请求:http://localhost:8080/my?name=zhangsan