SpringBoot-拦截器
spring.thymeleaf.cache=false
模板引擎修改后,想要实时生效!页面修改完毕后,IDEA小技巧 : Ctrl + F9 重新编译!
- 在LoginController添加session
session.setAttribute("loginUser",username);
- 自定义一个拦截器
package com.kuang.myproject.component;
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 {
Object user = request.getSession().getAttribute("loginUser");
if (user == null){//未登录,返回登录页面
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
//登录,放行
return true;
}
}
}
- 然后将拦截器注册到我们的SpringMVC配置类当中!
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器,及拦截请求和要剔除哪些请求!
//我们还需要过滤静态资源文件,否则样式显示不出来
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/asserts/**");
}
然后我们登录测试!
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果