springboot项目中拦截器实现,只能通过登录进入,直接进入会被拦截
将登录的session保存!!!
1.实现一个拦截器类
package com.demo1.springboot.config; /** * @author panglili * @create 2022-07-09-10:33 */ import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 拦截器实现 */ public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //登陆成功之后拿到session;证明登录成功! Object loginUser = request.getSession().getAttribute("loginUser"); if(loginUser==null){ //没有登录 request.setAttribute("msg","没有权限,请先登录!"); request.getRequestDispatcher("/index.html").forward(request,response); return false; }else{ return true; } } }
2.注册拦截器类到mvc
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHandlerInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/index.html","/","/user/login","/css/*","/js/**","/img/**"); }
ok了就
测试: