First, the first
1. Code
@WebFilter(filterName="LoginCheckFilter",urlPatterns="*")
public class LoginCheckFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("filter");
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Methods", "*");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
httpResponse.setHeader("Access-Control-Expose-Headers", "*");
chain.doFilter(httpRequest, httpResponse);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
2. loading (startup class above plus a comment @ServletComponentScan)
@SpringBootApplication
@ComponentScan(basePackages = {"com.thread.threadtest.*"})
@ServletComponentScan
@EnableAsync
public class ThreadtestApplication {
public static void main(String[] args) {
SpringApplication.run(ThreadtestApplication.class, args);
}
}
3. After the start, a back-end interface to access any of this filter will go, and then we will write that sentence in the filter output.
Second, the second way
1. Code
public class LoginCheckFilter2 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("filter 22222");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
2. Configuration loaded by a class
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistration() {
FilterRegistrationBean reg = new FilterRegistrationBean();
reg.setFilter(new LoginCheckFilter2());
reg.addUrlPatterns("*");
return reg;
}
}
3. The above can achieve the same effect
Third, the end of the
Always keep the faith!!!