springboot自定义拦截器
操作说明
1、编写一个拦截器实现HandlerInterceptor接口
2、拦截器注册到容器中(实现WebMvcConfigures的addInterceptors)
3、指定拦截规则 (如果是拦截所有,静态资源也会被拦截)
LoginInterceptor.java
package com.example.springtxiangmu.interceptor;
import lombok.extern.slf4j.Slf4j;
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;
//登陆检查
@Slf4j //能直接使用日志
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURL=request.getRequestURI();
log.info("拦截的请求路径是{}",requestURL);
//显示当前的请求路径
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
//获得上面登陆的cookie
if(loginUser!=null){
return true;
}
//拦截器拦截住了,说明没有登陆,直接跳转到登陆界面
request.setAttribute("msg","请先登陆");
//response.sendRedirect("/");
request.getRequestDispatcher("/").forward(request,response);
//跳转到根目录,并且转发 request、response
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("PostHandler执行",modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion执行",ex);
}
}
执行顺序(先后)
postHandle > 界面运行 >postHandle >afterCompletion
AdminWebConfig.java
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
//这里继承了WebMvcConfigurer
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加上自定义的拦截器
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**/")//拦截的请求
.excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");// 放行的请求
}
}
总结
流程就是,自定义拦截器实现HandlerInterceptor接口重写那三个方法,然后自定义一个配置类需要加(@Configuration)继承WebMvc接口,在里面添加自定义拦截器。
注意的是导入@Slf4j的时候,log.info l是小写,这里写
出了Log.info 搞了好久。细心,细心,细心!
String requestURL=request.getRequestURI();
//获取当前访问页面的路径,比如访问index就会显示 index {}相当于c中的%d占位符
log.info("拦截的请求路径是{}",requestURL);
标签:拦截器,springboot,自定义,request,response,import,public
From: https://www.cnblogs.com/JYcxk/p/17357550.html