拦截器作用:在SpringMVC请求处理期间,特定位置做拦截,插入一些额外处理逻辑。拦截点有以下3个位置:
在controller处理前(preHandle)
在controller处理后(postHandle)
在处理完毕,响应输出前(afterCompletion)拦截器组件编写需要实现HandlerInterceptor接口,接口有preHandle、postHandle、afterCompletion方法分别对应前面3个拦截点。在Boot中,拦截器配置需要采用Java配置模式。
@Component
//扫描
public class SomeInterceptor implements HandlerInterceptor{
-
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("-----进入SomeInterceptor拦截器的PreHandle处理------");
HttpSession session = request.getSession();
if(session.getAttribute("user")==null){
//未登录,拦截器后续处理
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("{\"msg\":\"未登录用户,身份不合法\"}");
return false;
}else{
return true;//登录了,放过去
}
} -
@Configuration//配置类,也具有扫描功能 public class InterceptorConfiguration implements WebMvcConfigurer{
@Autowired
private SomeInterceptor some;
public void addInterceptors(InterceptorRegistry registry) {
String[] patterns = {
"/dept/list",
"/dept/get"};
registry.addInterceptor(some).addPathPatterns(patterns);
}