SpringBoot通过拦截器获取登录信息
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot通过拦截器获取登录信息相关的知识,希望对你有一定的参考价值。
参考技术A 3.参数解析器4.CurrentUser注解
SpringBootWeb开发-登录和拦截器实现
引言:实现拦截器功能,这里是通过session的方式,在登录请求发起的时候,通过往请求里添加session,request.getSession().setAttribute("loginUser","登录成功");然后再获取session的方式实现拦截器,登录成功,那么session就会放进去,然后获取session,看session是否存在,如果存在就登录成功,否则就登录失败,跳转到登录页。session的详解可以参考前面的博客Java中session的详解。
步骤:
1.首先要在前端html页面的form表单中指定提交的地址和请求类型,也就是表单中的th:action和method
<body class="text-center"> <form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post"> <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72"> <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1> <!--加一个登录错误提示,这里用到了th:if--> <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p> <label class="sr-only" th:text="#{login.username}">Username</label> <input type="text" name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""> <label class="sr-only" th:text="#{login.password}">Password</label> <input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="" autofocus=""> <div class="checkbox mb-3"> <label> <input type="checkbox" value="remember-me"> [[#{login.remember}]] </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button> <p class="mt-5 mb-3 text-muted">© 2017-2018</p> <a class="btn btn-sm" th:href="@{/login.html(l=\'zh_CN\')}">中文</a> <a class="btn btn-sm" th:href="@{/login.html(l=\'en_US\')}">English</a> </form> </body>
2.编写Controller层,代码解析看注释。这里所有的html页面都是通过thymeleaf模板引擎解析的
package com.xiaoma.springbootweb.controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.Map; @Controller public class LoginController { //PostMapping可以直接发post请求 @PostMapping(value = "/user/login") //通过RequestParam获取用户名和密码,map里用来存放错误信息 public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map, HttpServletRequest request){ //如果用户名不为空并且密码为123456则登录成功,否则登录失败并给出错误提示 if(!StringUtils.isEmpty(username)&&"123456".equals(password)){ request.getSession().setAttribute("loginUser","登录成功"); //为了防止表单重复提交,这里用重定向,这里的main.html通过MyMvcConfig中的视图映射,会将页面跳转到templates下的dashboard.html页面 return "redirect:/main.html"; } else{ map.put("msg","用户名或者密码错误"); return "login"; } } }
3.编写拦截器
package com.xiaoma.springbootweb.component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; 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"); System.out.println("获取的session为"+user); if(user==null){ //设置登录失败的提示信息 request.setAttribute("msg","没有权限,请先登录"); //登录失败,返回登陆页面 request.getRequestDispatcher("/index.html").forward(request,response); return false; } else{ //登录成功,进入后台 return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
4.在我们的MyMvcConfig.java页面注册拦截器
package com.xiaoma.springbootweb.config; import com.xiaoma.springbootweb.component.LoginHandlerInterceptor; import com.xiaoma.springbootweb.component.MyLocaleResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("atguigu").setViewName("success"); } //通过bean注解将组件注册到loc容器中,让springmvc知道这个组件的存在 @Bean //通过mvc视图解析器实现controller层的mapping映射功能 public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){ WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); } //注册登录拦截器 @Override 33 public void addInterceptors(InterceptorRegistry registry) { 34 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**"). 35 excludePathPatterns("/","/index.html","/user/login"); 36 } }; return adapter; } @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); } }
以上是关于SpringBoot通过拦截器获取登录信息的主要内容,如果未能解决你的问题,请参考以下文章