一 、登錄及跳轉主頁總體步驟
1.登錄HTML添加動作跳轉,用戶名和密碼以及密碼錯誤提示框
在這裏插入代碼片`<!DOCTYPE html>
<!--<!–<html lang="en">–> 這個是默認的,後面加上對應的模板引擎-->
<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" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
<img class="mb-4" 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標籤,標籤的顏色設置爲紅色,標籤的內容由controller中msg獲得-->
<!--使用if方法,同時變量表達式中的內置工具判斷msg是否爲空-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only">Username</label>
<input type="text" name = "username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" 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}">
<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>
<!-- 下面是根據點擊請求帶上對應的zh_CN字符放到連接中,後面就去鏈接中截取這個關鍵字,然後切換視圖-->
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
</html>`
2.配置“WebMvcConfigurerAdapter”函數
package Main.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class mvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/ceshi").setViewName("hello");
registry.addViewController("/ceshisuccess").setViewName("success");
//前面是請求,http://localhost:8080/hello 因爲沒有hello.html 程序會去controller顯示返回值
// http://localhost:8080/ceshisuccess,controller也沒有對應的處理函數,它是直接去html,顯示信息
}
//上下兩種方法都可以直接不用再controller裏面寫getMapping了,這種方法直接去到templates下的html頁面
@Bean //將定義的東西放到容器中,這樣能被掃描到
public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override //這個可以用右鍵generate、Override 然後就找到對應的函數了
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
//這個是去主頁的重定向,只是登錄頁面不需要
registry.addViewController("/main.html").setViewName("dashboard");
}
};
return adapter;
}
}
3.對應的controller(處理登錄過程中密碼校驗)
package Main.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.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
//去前端頁面獲取對應參數值
@PostMapping(value = "/user/login")
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.setAttribute("loginUser",username);
// return "dashboard";
//登陸成功,防止表單重複提交,可以重定向到主頁
return "redirect:/main.html";//我這裏直接dashboard.html會出現40錯,這樣就不會出錯
}else{
//登陸失敗
//這個msg被傳回到前端,前端寫了個標籤,如果用戶密碼錯誤,提示相應信息
map.put("msg","用戶名密碼錯誤");
return "login";
}
}
}
二、下面是基於原始restful-crud爲什麼要添加這些修改值的詳解(針對登錄及跳轉主頁)
1.登錄
1.配置“WebMvcConfigurerAdapter”函數
該函數讓用戶輸入“http://localhost:8080”直接跳轉到“login.html”
package Main.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class mvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/ceshi").setViewName("hello");
registry.addViewController("/ceshisuccess").setViewName("success");
//前面是請求,http://localhost:8080/hello 因爲沒有hello.html 程序會去controller顯示返回值
// http://localhost:8080/ceshisuccess,controller也沒有對應的處理函數,它是直接去html,顯示信息
}
//上下兩種方法都可以直接不用再controller裏面寫getMapping了,這種方法直接去到templates下的html頁面
@Bean //將定義的東西放到容器中,這樣能被掃描到
public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override //這個可以用右鍵generate、Override 然後就找到對應的函數了
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
//這個是去主頁的重定向,只是登錄頁面不需要
registry.addViewController("/main.html").setViewName("dashboard");
}
};
return adapter;
}
}
2.登錄後跳轉到主頁
2.1.在“login.html”添加跳轉到主頁的動作
原始login.html
<!DOCTYPE html>
<html lang="en">
<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" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<!-- action 這裏有跳轉到主頁的動作-->
<form class="form-signin" action="dashboard.html">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label class="sr-only">Username</label>
<input type="text" class="form-control" placeholder="Username" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" placeholder="Password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
因爲我們要通過登錄跳轉到主頁需要登錄密碼和賬號驗證,所以要寫個controller對登錄跳轉主頁進行設置
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
2.2.對應的controller
package Main.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.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
//去前端頁面獲取對應參數值
@PostMapping(value = "/user/login")
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.setAttribute("loginUser",username);
return "dashboard";
}else{
//登陸失敗
//這個msg被傳回到前端,前端寫了個標籤,如果用戶密碼錯誤,提示相應信息
map.put("msg","用戶名密碼錯誤");
return "login";
}
}
}
2.3錯誤及排查
不幸的是頁面出現錯誤
40開頭的錯誤一般是客戶端的原因導致的,所以回去排查一下
原來是密碼和賬號名沒有設置參數名稱,這樣在controller中無對應參數,所以會報錯
添加對應的參數:
添加參數,還添加了一個報錯後提示密碼錯誤的框及動作跳轉到對應的controller
<!DOCTYPE html>
<!--<!–<html lang="en">–> 這個是默認的,後面加上對應的模板引擎-->
<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" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
<img class="mb-4" 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標籤,標籤的顏色設置爲紅色,標籤的內容由controller中msg獲得-->
<!--使用if方法,同時變量表達式中的內置工具判斷msg是否爲空-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only">Username</label>
<input type="text" name = "username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" 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}">
<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>
<!-- 下面是根據點擊請求帶上對應的zh_CN字符放到連接中,後面就去鏈接中截取這個關鍵字,然後切換視圖-->
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
</html>
重新運行程序
頁面不正常,且刷新會詢問是否重新提交表單
要頁面重定向解決
package Main.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.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
//去前端頁面獲取對應參數值
@PostMapping(value = "/user/login")
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.setAttribute("loginUser",username);
// return "dashboard";
//登陸成功,防止表單重複提交,可以重定向到主頁
return "redirect:/main.html";//我這裏直接dashboard.html會出現40錯,這樣就不會出錯
}else{
//登陸失敗
//這個msg被傳回到前端,前端寫了個標籤,如果用戶密碼錯誤,提示相應信息
map.put("msg","用戶名密碼錯誤");
return "login";
}
}
}
三、攔截器
攔截器即對用戶的請求進行攔截,防止直接跳過登錄進入對應內容頁。如直接輸入 http://localhost:8080/main.html
直接進入主頁,所以要加攔截器
1.新建一個攔截器實現類
package Main.config;
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("/index.html").forward(request,response);
return false;
}else {
//已登陸,放行請求
return true;
}
}
//下面三個方法是實現接口HandlerInterceptor必須要的方法
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2.配置MVC
package Main.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class mvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/ceshi").setViewName("hello");
registry.addViewController("/ceshisuccess").setViewName("success");
//前面是請求,http://localhost:8080/hello 因爲沒有hello.html 程序會去controller顯示返回值
// http://localhost:8080/ceshisuccess,controller也沒有對應的處理函數,它是直接去html,顯示信息
}
//上下兩種方法都可以直接不用再controller裏面寫getMapping了,這種方法直接去到templates下的html頁面
@Bean //將定義的東西放到容器中,這樣能被掃描到
public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override //這個可以用右鍵generate、Override 然後就找到對應的函數了
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
//這個是去主頁的重定向,只是登錄頁面不需要
registry.addViewController("/main.html").setViewName("dashboard");
}
//註冊攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
//靜態資源; *.css , *.js
//SpringBoot已經做好了靜態資源映射
//下面的意思是攔截網頁下/*全部攔截,但除了"/index.html","/","/user/login"
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login");
}
};
return adapter;
}
}
直接登錄主頁就會被攔截,讓先登錄