标签:客户 intercept text new login err spring getattr handler
SpringBoot 拦截器 | 过滤器 | 监听器
1.拦截器:拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。一般用于拦截用户登录,用户验证等。
2.过滤器:它可以对客户的请求进行处理。处理完成后,它会交给下一个过滤器处理,这样,客户的请求在过滤链里逐个处理,直到请求发送到目标为止。一般用于对数据的处理。
3.监听器:
配置拦截器:
实现的 HandlerInterceptor 接口
package com.intercept; import org.springframework.lang.Nullable; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserInterceptor implements HandlerInterceptor { //方法执行前 @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception { System.out.println("方法执行前"); if(req.getSession().getAttribute("user")==null){ System.out.println("用户未登录或session失效"); resp.sendRedirect("/login/to_login"); return false; } return true; } //方法执行后 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("方法执行后"); } //页面渲染前 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("页面渲染前"); } }
在WebMvcConfigurer中添加拦截器:
package com.intercept; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorConfig implements WebMvcConfigurer { //添加拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new UserInterceptor()) .addPathPatterns("/**") //拦截请求 .excludePathPatterns("/login/to_login","/login/do_login"); //不拦截请求 } }
拦截器配置完成。
标签:客户 intercept text new login err spring getattr handler
原文地址:https://www.cnblogs.com/yanghe123/p/10945674.html