接上一节。
开发期间更改模板后使其实时生效,需要进行两步:
- 在主配置文件中禁用模板缓存:spring.thymeleaf.cache=false。
- 修改完模板后按ctrl+f9进行重新编译。
1、首先是login.html:指定我们表单发送的请求
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.1.2/css/bootstrap.css}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet"> </head> <body class="text-center"> <form class="form-signin" action="/" 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> </body> </html>
2、在com.gong.springbootcurd.controller下新建LoginController.java
package com.gong.springbootcurd.controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.Map; @Controller public class LoginController { // @DeleteMapping // @PutMapping // @GetMapping //@RequestMapping(value = "/user/login",method = RequestMethod.POST) @PostMapping(value = "/user/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map, HttpSession session){ if("admin".equals(username) && "123456".equals(password)){ //登陆成功,防止表单重复提交,可以重定向到主页 session.setAttribute("loginUser",username); return "redirect:/main.html"; }else{ //登陆失败 map.put("msg","用户或名密码错误"); return "login"; } } }
说明:这里我们可以使用PostMapping发送Post请求,不必向原来的springmvc那样麻烦。直接模拟账号和密码,如果是admin+123456,则将用户名存放到session中,为了避免重复提交,重定向到/main.html。如果登录失败,则返回错误信息“用户名或密码错误”到登录界面。
3、配置/main.html跳转到/templates/dashboard.html同时,为了避免没有登录而直接发送请求进入该页面,需要配置一个登录拦截器。
在com.gong.springbootcurd.component下新建LoginHandlerInceptor.java
package com.gong.springbootcurd.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"); if(user == null){ //未登陆,返回登陆页面 request.setAttribute("msg","没有权限请先登陆"); request.getRequestDispatcher("/login.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 { } }
从session中获取用户名,如果有,则放行,如果没有,将错误信息传给login.html。
MyMvcConfig.java
package com.gong.springbootcurd.config; import com.gong.springbootcurd.component.LoginHandlerInterceptor; import com.gong.springbootcurd.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.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //@EnableWebMvc 接管springmvc @Configuration public class MyMvcConfig implements WebMvcConfigurer{ @Override public void addViewControllers(ViewControllerRegistry registry) { //浏览器发送gong请求会跳转到/templates/success.html页面 registry.addViewController("gong").setViewName("success"); } //所有的WebMvcConfigurer会一起起作用 //将组件注册到容器中 @Bean public WebMvcConfigurer webMvcConfigurer() { WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer(){ public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/login.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); } //注册拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { //super.addInterceptors(registry); //静态资源; *.css , *.js //SpringBoot已经做好了静态资源映射 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**") .excludePathPatterns("/login.html","/","/user/login","/asserts/**","/webjars/**"); } }; return webMvcConfigurer; } @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); } }
4、启动服务器
首先是直接访问localhost:8080/curd/main.html
跳转到登录界面,并提示没有权限,我们输入admin+123456:
重定向的dashboard.html
dashboard.html就不贴了,太多。
至此,模拟登录功能基本完成。