1. 程式人生 > >spring 攔截器的用法

spring 攔截器的用法

1.建立 AuthIntercepter並實現spring的HandlerInterceptor介面

public class AuthIntercepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
Map<String, String[]> map = request.getParameterMap();
map.forEach((k,v) -> {
if (k.equals(“errorMsg”) || k.equals(“successMsg”) || k.equals(“target”)) {
request.setAttribute(k, Joiner.on(",").join(v));
}
});
String requestUri = request.getRequestURI();//獲取請求路徑
if (requestUri.startsWith("/static") || requestUri.startsWith("/error")) {//如果訪問的是靜態資源 不攔截請求
return true;
}
//獲取當前使用者
HttpSession session = request.getSession(true);
User user = (User) session.getAttribute(CommonConstants.USER_ATTRIBUTE);
if (user != null) {
UserContext.setUser(user);
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
UserContext.remove();
}
}該攔截器主要是攔截除了靜態資源的所有請求 把使用者資訊儲存在ThreadLocal裡
2.建立AuthActionIntercepter並實現spring的HandlerInterceptor介面

public class AuthActionIntercepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
User user = UserContext.getUser();
if(user==null){//重定向到登陸頁面 並且記錄當前頁面路徑
String msg= URLEncoder.encode(“請先登入”,“utf-8”);
String target=URLEncoder.encode(request.getRequestURI(),“utf-8”);
if(“GET”.equalsIgnoreCase(request.getMethod())){//get 請求引數以問號的形式存在
response.sendRedirect("/accounts/signin?errorMsg="+msg+"&target="+target);
}else{
response.sendRedirect("/accounts/signin?errorMsg="+msg);
}
}
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
該介面主要是攔截所有需要登入的請求
3.讓攔截器生效起作用
@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter {
@Autowired
private AuthIntercepter authIntercepter;
@Autowired
private AuthActionIntercepter authActionIntercepter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//設定要攔截的路徑 攔截除了/static的所有請求
registry.addInterceptor(authIntercepter).excludePathPatterns("/static").addPathPatterns("/**");
//攔截需要登入的請求
registry.addInterceptor(authActionIntercepter).addPathPatterns("/accounts/profile");
}
}