Springboot+Thymeleaf+Jpa實現登錄功能(附源碼)

前言

最近有學習到關於Springboot+Thymeleaf+Jpa的綜合運用知識,因此想寫一個簡單的登錄界面來嘗試一下,以下將展示具體流程

具體實現

首先要創建一個springboot項目

在這裡插入圖片描述

添加以下依賴項

在這裡插入圖片描述

pom.xml代碼

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo1</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件application.yml的代碼

在mysql://localhost:3306/後更改為自己的數據庫名字,另外username和password同樣更改為自己數據庫的用戶名和密碼

spring:
  thymeleaf:
    mode: HTML

  datasource:
    url: jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true


Po(實體)層代碼(User.java)

建立一個簡單的用戶類,裡面包含id主鍵(用jpa寫po層必須要有主鍵用@id註解)

@Entity
public class User {
    @Id
    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

Dao(數據庫操作)層代碼(UserDao.java)

創建一個接口繼承jpa的數據庫操作<>裡第一個參數,代表要操作的具體哪一個Po層,第二個參數代表這個Po層的主鍵類型
寫瞭一個方法(也就是JPA最香的地方,可以通過簡單的名字對應關系進行sql的查找)通過name和password查找一個用戶

public interface UserDao extends JpaRepository<User,Integer> {

    User findByNameAndPassword(String name,String password);
}

Service(服務)層代碼

Service層接口(Userservice.java)

public interface UserService {

    User finduser(String name,String password);
}

Service層具體實現(UserServiceimpl.java)

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public User finduser(String name, String password) {
        return userDao.findByNameAndPassword(name,password);
    }
}

驗證碼功能

因為要用到瞭驗證碼的實現功能,所以采取瞭一位大佬的驗證碼生成的操作進行集成
它的工具類 VerifyCode.java以及CaptchaController.java本博客就不貼瞭,移步大佬博客進行使用即可
參考文章(關於驗證碼)

Controller(控制)層代碼(LoginController.java)

@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping("/")
    public String login()
    {
        return "login";
    }
    @RequestMapping("/dologin")
    public String dologin(User user, HttpSession session, String verifycode, Model model)
    {
        User user1=userService.finduser(user.getName(), user.getPassword());

        String code= (String) session.getAttribute("verifyCode");

        if(user1!=null&&code.equalsIgnoreCase(verifycode))
        {
            model.addAttribute("message","成功");
            return "enter";
        }
        else
        {
            model.addAttribute("message","失敗");
            return "enter";
        }
    }
}

Html頁面代碼

註意三個input裡面的name屬性,很多初學者(包括我)會好奇Controller是怎麼獲取網頁上輸入的具體的值?
實際上就是通過name屬性比如說第一個參數user,因為它裡面有user.name和user.password屬性,因此可以通過在html裡進行對name屬性的更改來實現數據的尋找,第二個參數verifycode也是一樣的道理註意驗證碼後的input框的name屬性是verifycode,第三個屬性model也是常用屬性,此處是為瞭在頁面上進行具體的消息顯示

 public String dologin(User user, HttpSession session, String verifycode, Model model)

登錄頁面(login.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
      <form action="/dologin">
          <div>
              <span>
                  名字:
              </span>
              <input type="text" name="name" >
          </div>
            <div>
                <span>
                    密碼:
                </span>
                <input type="password" name="password" >
            </div>
            <div>
                <span>
                    驗證碼
                </span>
                <input type="text" name="verifycode">

            </div>
            <div>
                <a href="javascript:void(0);" rel="external nofollow"  title="點擊更換驗證碼">
                    <img th:src="@{getVerifyCode}" onclick="changeCode()" class="verifyCode"/>
                </a>
            </div>
          <div>
          <button type="submit">登錄</button>
          </div>
      </form>
      <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  <script>
      function changeCode() {
          const src = "/getVerifyCode?" + new Date().getTime(); //加時間戳,防止瀏覽器利用緩存
          $('.verifyCode').attr("src", src);
      }
  </script>
</body>
</html>

判斷登錄是否成功的頁面(enter.html)

通過Thymeleaf的表達式,對message進行取值,來反應登錄是否成功

model.addAttribute("message","成功");
model.addAttribute("message","失敗");
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h2 th:text="${message}">
    登錄成功
  </h2>
</body>
</html>

最後的項目目錄結構

在這裡插入圖片描述

到此這篇關於Springboot+Thymeleaf+Jpa實現登錄功能(附源碼)的文章就介紹到這瞭,更多相關Springboot Thymeleaf Jpa登錄內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: