自定义拦截器
package com.mcs.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
/**
* 访问控制器方法前执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("--preHandle--");
String userId = request.getHeader("userId");
if (StringUtils.isEmpty(userId)) {
response.setStatus(401);
response.getWriter().print("please login");
response.getWriter().flush();
return false;
}
return true;
}
/**
* 访问控制器方法后执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("--postHandle--");
}
/**
* 渲染视图结束后执行,一般用于释放资源
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("--afterCompletion--");
}
}
配置拦截器
package com.mcs.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.mcs.interceptor.LoginInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加Web项目的拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login").order(10);
// 多个拦截器在下边追加
// registry.addInterceptor(new LoginInterceptor2()).addPathPatterns("/**").excludePathPatterns("/login").order(5);
}
}
addPathPatterns:用于指定拦截路径,/**表示拦截全部
excludePathPatterns:用于排除拦截路径
order:拦截器优先级,数值越低,优先级越高