SpringBoot-登录拦截器
简单实现登录拦截器
登录Controller
@Controller public class LoinController { @RequestMapping("/login") public String login( @RequestParam("userEmail") String userEmail, @RequestParam("password") String password, Model model, HttpSession session ){ if ( !StringUtils.isNullOrEmpty(userEmail) && "123456".equals( password ) ){ session.setAttribute("loginUser",userEmail); return "redirect:/index"; }else { model.addAttribute("msg","账号或密码错了"); return "auth-sign-in"; } } }
return "redirect:/index";用于实现浏览器地址栏的变换,使得看起来更合理。
登录信息符合,则给设置一个session,否则返回登录页面。
登录页面
<p class="text-center" style="color: red" th:text="${msg}" th:if="${ not #strings.isEmpty(msg)}"></p>
<form th:action="@{/login}"> <label th:text="#{signIn.email}">邮箱</label> <input class="form-control" type="email" placeholder="admin@example.com" th:name="userEmail"> <label th:text="#{signIn.password}">密码</label> <input class="form-control" type="password" placeholder="********" th:name="password"> <button type="submit" class="btn btn-primary" th:text="#{signIn.signIn}">Sign In</button>
</form>
p标签用来显示后台返回的提示信息
th:text="${msg}" th:if="${ not #strings.isEmpty(msg)}
到目前虽然有登录这道门,但是还可以不从这道门经过,所有需要下面的登录拦截器:
SpringBoot有预留有接口,我们只需要去按照自己的需求实现并注入即可:
实现:
public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object loginUser = request.getSession().getAttribute("loginUser"); if ( loginUser == null ){ request.setAttribute("msg","没有权限,请登录"); request.getRequestDispatcher("/auth-sign-in.html").forward( request,response ); return false; }else{ return true; } } }
拦截的实现主要是通过判断请求是否带有用户session信息,有就放行,没有返回。
@Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 浏览器发送/test , 就会跳转到test页面; registry.addViewController("/auth-sign-in").setViewName("auth-sign-in"); registry.addViewController("/").setViewName("auth-sign-in"); } //注入 生效 @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor( new LoginHandlerInterceptor() ) .addPathPatterns("/**") .excludePathPatterns("/","/login","/auth-sign-in","/css/*","/js/**","/image/**","/font/**","/picture/**");//static } }
通过重载写addInterceptors方法来规定哪些请求放行、哪些请求拦截。
到这,简单的登录拦截就完成了。