SpringBoot配置拦截器
1.创建一个自定义拦截器,实现HandlerInterceptor
package com.hmdp.utils; import com.hmdp.dto.UserDTO; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 拦截器 */ public class LoginInterceptor implements HandlerInterceptor { /** * 前置拦截器 --- 进入controller之前进行登录校验 * * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //1.获取session HttpSession session = request.getSession(); //2.获取session中的用户 Object user = session.getAttribute("user"); //3.判断用户是否存在 if (user==null){ //4.不存在,拦截 返回401未授权 response.setStatus(401); return false; } //5.存在,保存用户到ThreadLocal UserHolder.saveUser((UserDTO) user); //6.放行 return true; } /** * 增强拦截器--空过 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 后置拦截器 --- 用户业务执行完毕,销毁对应的用户信息 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserHolder.removeUser(); } }
2.调用配置类拦截器
package com.hmdp.config; import com.hmdp.utils.LoginInterceptor; 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 MvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //添加拦截器,、 //配置不拦截的路径 registry.addInterceptor(new LoginInterceptor()).excludePathPatterns( "/user/code", "/user/login", "/blog.hot", "/shop/**", "/shop-type/**", "/voucher/**" ); } }
如有差错,请各位指正