接上一節。
開發期間更改模板后使其實時生效,需要進行兩步:
- 在主配置文件中禁用模板緩存: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就不貼了,太多。
至此,模擬登錄功能基本完成。