SpringBoot:学习笔记(4)——添加自定义的过滤器
引入自定义过滤器
为什么添加自定义过滤器
SpringBoot提供的前端控制器无法满足我们产品的需求时,我们需要添加自定义的过滤器。
参考资料:官方文档
SpringBoot添加过滤器的注解方式
1.编写过滤器代码
package com.mrsaber.security; import org.springframework.core.annotation.Order; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @Order(1) @WebFilter(filterName = "MSecurity",urlPatterns = {"*.html"}) public class MSecurityFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response= (HttpServletResponse) servletResponse; System.out.println(request.getRequestURI()); //检查是否是登录页面 if(request.getRequestURI().equals("/web/index.html")) filterChain.doFilter(servletRequest,servletResponse); //检测用户是否登录 HttpSession session =request.getSession(); String status= (String) session.getAttribute("isLogin"); if(status==null || !status.equals("true")) { try{ response.sendRedirect("/web/index.html");}catch (Exception e){} } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
说明:
重点在于两个注解!
When using an embedded container, automatic registration of
@WebServlet
,@WebFilter
, and@WebListener
annotated classes can be enabled using@ServletComponentScan
.使用嵌入式容器时,可以使用@ServletComponentScan启用@WebServlet,@ WebFilter和@WebListener注释类的自动注册。
@ServletComponentScan will have no effect in a standalone container, where the container’s built-in discovery mechanisms will be used instead.
如果使用外置容器的话,容器的内置发现机制将会被使用,而不需要使用这条注解。
2.添加@ServletComponentScan注解
@SpringBootApplication @ServletComponentScan(basePackages = "com.mrsaber.security") public class MsSupplyAndSaleApplication { public static void main(String[] args) { SpringApplication.run(MsSupplyAndSaleApplication.class, args); } }