SpringBoot-实现登录功能(十一)
登录
开发期间模板引擎页面修改以后,要实时生效.
#禁用模板引擎的缓存 spring.thymeleaf.cache=false
前端提交的表单
<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> <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=""> <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>
编写controller
@Controller public class LoginController { @PostMapping(value = "/user/login") //@RequestParam这个注解是必须写入值 public String login(@RequestParam("username") String username, @RequestParam("password") String password , Map<String,Object> map, HttpSession session){ if(!StringUtils.isEmpty(username) && "123456".equals(password)){ // 把登录的信息存入session中 session.setAttribute("loginUser",username); // 登录成功 // 重定向到main.html解析 return "redirect:/main.html"; }else { //登录失败 map.put("msg","用户名密码错误"); return "login"; } } }
防止表单重复提交,进行重定向
@Bean public WebMvcConfigurer webMvcConfigurer() { WebMvcConfigurer configurer = new WebMvcConfigurer() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); // 浏览器发送index.html / 请求来到 login registry.addViewController("/index.html").setViewName("login"); // 浏览器发送main.html 请求来dashboard! registry.addViewController("/main.html").setViewName("dashboard"); }
登陆错误消息的显示
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
但是这样别人可以直接跳过登录访问我们的主页面,我们应该添加一个拦截器.
拦截器进行登陆检查
要注册拦截器必须实现HandlerInterceptor
//注册拦截器 要注册拦截器必须实现HandlerInterceptor public class LoginHandlerInterceptor implements HandlerInterceptor { //在目标方法执行前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 获得session中携带的值,判断 Object user = request.getSession().getAttribute("loginUser"); // 判断如名字为空说明没登录拦截 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 { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
编写好拦截器,还要注册拦截器的组件,和设置对应的拦截条件
@Configuration public class MyMvcConfig implements WebMvcConfigurer { @Bean public WebMvcConfigurer webMvcConfigurer() { WebMvcConfigurer configurer = new WebMvcConfigurer() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); // 浏览器发送index.html / 请求来到 login registry.addViewController("/index.html").setViewName("login"); // 浏览器发送main.html 请求来dashboard! registry.addViewController("/main.html").setViewName("dashboard"); } //注册拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { //静态资源在springboot2.0以前已经做好映射,不用管 // /**指任意范围都通过拦截 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**") .excludePathPatterns("/index.html", "/", "/user/login", "/asserts/**", "/webjars/**"); // .excludePathPatterns代表这些请求不过滤 // asserts为resources下static下的文件夹,webjars则是maven导入的一些前端框架 } }; return configurer; }
这里注意:WebMvcConfigurer是需要注明 不拦截那些静态资源的.否则我们的静态资源也被拦截了.