1. 程式人生 > >SpringBoot + thymeleaf 實現簡單的登陸驗證

SpringBoot + thymeleaf 實現簡單的登陸驗證

本文上一篇的內容的基礎上,加入thymeleaf 模板,實現一個簡單的登陸和頁面錯誤提示的功能,藉此瞭解SpringBoot web專案,同時為大家分享一些編碼小技巧,用於簡化程式碼。

我們回到第一篇的內容,看一下專案的目錄結構,SpringBoot 生成專案時,如果引入了web元件,在resources資料夾下面會生成兩個資料夾static 和 templates 。static資料夾預設存放css、js等靜態資源,templates資料夾用來存放html等模板頁面(有興趣的同學可以通過配置檔案或配置類修改存放路徑,在demo中,我們就 使用Spring推薦的預設路徑 )。

一、在templates 下,編寫一個登陸頁面 login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>登入</title>
    <link rel="stylesheet" type="text/css" href="/css/common.css" />
</head>
<body>
    <form
th:action="@{/login}" method="post">
<div> <!--/*@thymesVar id="error" type=""*/--> <span id="basic-addon0">&nbsp;</span> <span style="font-size: 12px;color: red" th:text="${error}" aria-describedby="basic-addon0"></span>
<br /> </div> <div> <span id="basic-addon1">@</span> <input id="user_name" name="userName" type="text" placeholder="使用者名稱" aria-describedby="basic-addon1" /> </div> <br /> <div> <span id="basic-addon2">@</span> <input id="password" name="password" type="password" placeholder="密碼" aria-describedby="basic-addon2" /> </div> <br /> <button type="submit" style="width:190px;">登 錄</button> </form> </body> </html>

我們只要在標籤中加入 xmlns:th=”http://www.thymeleaf.org” , 啟用thymeleaf模板。
關於thymeleaf 的語法我們後面另起篇幅進行分享。

二、編寫LoginController控制器

package cn.pw.pf.web.controller;

import cn.pw.pf.web.requestParam.UserVo;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

/**
 * 頁面登陸控制器
 * @Description:
 * @Author:libin
 * @Date: Created in 15:28 2017/11/13
 */
@RestController
@RequestMapping("/")
public class LoginController {

    @GetMapping("/login")
    public ModelAndView login(ModelAndView modelAndView){
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @PostMapping("/login")
    public ModelAndView login(ModelAndView modelAndView, @Valid UserVo userVo, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            modelAndView.addObject("error",bindingResult.getFieldError().getDefaultMessage());
            modelAndView.setViewName("login");
            return modelAndView;
        }
        String userName = userVo.getUserName();
        String password = userVo.getPassword();

        if(!"admin".equals(userName)){
            modelAndView.addObject("error","無此使用者!");
            modelAndView.setViewName("login");
            return modelAndView;
        }
        if(!"123456".equals(password)){
            modelAndView.addObject("error","密碼錯誤!");
            modelAndView.setViewName("login");
            return modelAndView;
        }
        modelAndView.addObject("userName",userName);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

login 的get請求用於頁面跳轉,post請求用於處理登陸驗證。
這裡我使用了@Valid 和 BindingResult 實現頁面引數驗證。

三、編寫 UserVo類,用於bind頁面請求引數。同樣,我們建立一個新包,requestParam,存放UserVo。

package cn.pw.pf.web.requestParam;

import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Size;

/**
 * 頁面請求引數對應實體
 * @Description:
 * @Author:libin
 * @Date: Created in 15:34 2017/11/13
 */
public class UserVo {
    private Long id;

    @NotEmpty(message="使用者名稱不能為空!")
    private String userName;

    private String nickName;

    @Size(min=6,max=10,message = "密碼長度必須6到10位")
    private String password;

    private Integer age;

    private Integer sex;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

這裡寫圖片描述

2、在不輸入使用者名稱密碼的情況下,點選登入

這裡寫圖片描述

3、輸入使用者名稱 admin 不輸入密碼,點選登入

這裡寫圖片描述

4、輸入完整的使用者名稱密碼,使用者名稱:adimn 密碼:123456

這裡寫圖片描述

總結:截止目前,很簡單的一個 SpringBoot web專案 ,內容很簡單,程式碼極少,全程沒有一個xml。下一篇我們分享SpringBoot web 配置Filter過濾器。