ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
拦截器可以拦截请求也可以拦截响应。使用拦截器的步骤如下: <br/> **1. 实现接口HandlerInterceptor** ```java import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginHandlerInterceptor implements HandlerInterceptor { /** * 在执行目标方法之前先执行该方法 * 当return false时将其拦截 * 当return true时将其放行 */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // session.setAttribute("user", user) Object user = request.getSession().getAttribute("user"); if (user == null) { request.setAttribute("msg", "请先登录!"); request.getRequestDispatcher("/login").forward(request, response); return false; } else { return true; } } /** * 在后端响应数据到前端之前该方法被调用 * * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } /** * 响应完成之后该方法被调用,可以在这个方法中做一些释放资源的工作 * * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } } ``` **2. 注册拦截器到IoC容器中** ```java import com.example.webresult.component.LoginHandlerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CustomMvcConfig implements WebMvcConfigurer { @Bean public WebMvcConfigurer webMvcConfigurer() { WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() { @Override public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns 要拦截的请求,/*表示拦截所有请求 //excludePathPatterns 不拦截的请求 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/*") .excludePathPatterns("/login", "/", "/doLogin"); } }; return webMvcConfigurer; } } ```