验证了下这三个注解在spring boot中的作用方式。
1、@WebServlet
注解的使用方式:
示例:三种方式指定URL路径,当get/post/delete/等请求指定URL时,会优先进入被@WebServlet注解的类,做相应的请求。可用于根据不同条件,重定向请求至不同URL。
//@WebServlet("/webServlet")
//@WebServlet(name="TestWebServlet",urlPatterns="/webServlet")
@WebServlet(name="TestWebServlet",urlPatterns={"/webServlet","/hello"})
public class TestWebServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet " + req.getAttribute("filter"));
resp.sendRedirect("/hello"); //重定向
// doPost(req,resp);
// super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost " + req.getAttribute("filter"));
// super.doPost(req, resp);
}
}
2、@WebFilter
注解的使用方式:
示例:被注解中标注的servletName或URL,业务请求时将被拦截,可用于拦截/过滤请求,提前对请求的request进行判断处理,在doFilter后过滤器放行,调用实际请求URL路径。
//@WebFilter("/*") //拦截所有请求
//@WebFilter("/path/*") //拦截路径包含path的所有请求
@WebFilter("/webServlet") //拦截指定URL的请求
//@WebFilter(urlPatterns = {"/webServlet","/hello"})
public class TestWebFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("webFilter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println("webFilter doFilter 1 "+ request.getAttribute("filter"));
request.setAttribute("filter","a filter");
chain.doFilter(request,response);//过滤器放行
System.out.println("webFilter doFilter 2 "+ request.getAttribute("filter"));
}
@Override
public void destroy() {
System.out.println("webFilter destroy");
}
3、@WebListener
注解的使用方式:
@WebListener
public class TestWebListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("test WebListener contextInitialized");//spring启动之前初始化操作
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("test WebListener contextDestroyed");//spring注销时执行
}
}
在spring启动之前监听执行初始化操作,可用于提前加载缓存等。
spring boot中,这三个注解使用时需要在Application启动类添加@ServletComponentScan注解,这样服务启动时才能去扫描到这三个注解。
@ServletComponentScan
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(DesignPatternApplication.class,args);
}
}