做java web开发经常会需要和过滤器拦截器打交道,平时在用的时候看到功能实现了就并没有在去做一些理论上的学习理解,springboot在ssm的基础上进一步做了封装,开发人员对于很多的细节问题较ssm来说需要了解的越来越少,但不代表这些知识不重要,需要由自己的理解,然后实践理论知识才能慢慢变成自己的经验。以下从最基础的开始来梳理
拦截器demo
1 定义一个拦截器testInterceptor
代码语言:javascript复制public class testInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("测试拦截器方法是否执行");
return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
二、注册
代码语言:javascript复制@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public testInterceptor requestFilterBean(){
return new testInterceptor();
}
//注册request请求拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new testInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/login");
}
}
过滤器
WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp,Servlet, 静态图片文件或静态html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能,以下是小demo
代码语言:javascript复制@Component
public class testFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("测试");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
httpServletRequest.getSession();
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "*");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Content-type", "application/json");
httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
filterChain.doFilter(request, httpResponse);
}
@Override
public void destroy() {
}
}
监听器
需要拓展
Servlet的生命周期过程是怎么样的 filter中的doFilter()什么情况下会执行