IT graph

気になったデバイスやプログラムで楽しくやっていけたら良いなと思っております。

Spring Boot2でログイン画面を作ってみた / How to create login function with Spring Boot2!

Spring BootとThymeleafを利用してログイン画面を作成してみます。

まずはHTMLにてログイン画面を作成します。

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Login</title>
    </head>
    <body>
        <form id="form" action="/login" method="POST">
            <table>
                <tr>
                <td>
                    ID
                </td>
                <td>
                <input type="text" id="loginId" name="loginId" value="">
                </td>
                </tr>
                <tr>
                <td>
                    Password
                </td>
                <td>
                <input type="password" id="password" name="password" value="">
                </td>
                </tr>
                <tr>
                <td colspan="2">
                    <input type="submit" value="login"/>
                </td>
                </tr>
            </table>
        </form>
    </body>
</html>

次に、ログイン結果を表示する画面をHTMLで作成します。 ${message}はコントローラからログイン結果の値を受けとって表示します。 th:textはthymeleafのタグです。

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Login Result</title>
    </head>
    <body>
        <h1 th:text="${message}"></h1>
    </body>
</html>

次はDatabase、環境はMySQLを使っています。 かなり雑ですが、以下のようにテーブルを作っています。 今回必要なのは、idとpasswordだけです。

mysql> desc employee;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| id         | varchar(100) | YES  |     | NULL    |       |
| name       | varchar(50)  | YES  |     | NULL    |       |
| email      | varchar(50)  | YES  |     | NULL    |       |
| updated_at | varchar(50)  | YES  |     | NULL    |       |
| created_at | varchar(50)  | YES  |     | NULL    |       |
| password   | varchar(100) | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

SpringとMySQLの接続は、application.propertiesに以下を追加します。コンパイル環境はGradleです。
[databasename]の箇所にDB名を指定して、DBへの接続ユーザおよびパスワードを指定します。

spring.datasource.url=jdbc:mysql://localhost:3306/[databasename]?autoReconnect=true&useSSL=false
spring.datasource.username=xxxx
spring.datasource.password=xxxx

次に、テーブルと紐付いたEntityを作成します。SetterとGetterは省略しています。

package com.hello.entity;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Employee")
public class EmployeeEntity {
    private static final long serialVersionUID = 1L;
    
    @Id
    @Column
    private String id;
    @Column
    private String name;
    @Column
    private String email;
    @Column
    private Timestamp updatedAt;
    @Column
    private Timestamp createdAt;
    @Column
    private String password;

続けてテーブルからデータを取得するためのRepositoryを作成。 呼び出し元からidとpasswordは渡されます。
findByIdAndPasswordについては、JPAのルールに従って記載すればSQLなしで同等の処理を行ってくれます。

package com.hello.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.hello.entity.EmployeeEntity;

@Repository
public interface EmployeeRepository extends JpaRepository<EmployeeEntity, String> {
    EmployeeEntity findByIdAndPassword(String id, String password );

}

最後はControllerの編集。loginメソッドでは、ルートへアクセスされた場合はログイン画面を表示 するようにします。
loginCheckメソッドでは、ログイン画面のSubmitを押下後にログインチェックを 行い、結果を別の画面に返すようにしています。

package com.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hello.entity.EmployeeEntity;
import com.hello.repository.EmployeeRepository;

@Controller
public class HelloController {
    
    @Autowired
    EmployeeRepository employeeRepository;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    public ModelAndView login(ModelAndView mav) {
        mav.setViewName("login");                            //ModelAndViewクラスにViewのページ名を指定
        return mav;                                          //ModelAndViewを返す
    }
    
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public ModelAndView loginCheck(@RequestParam("loginId") String id, @RequestParam("password") String password,  ModelAndView mav) {
        String idd = id;
        EmployeeEntity employeeEntity = employeeRepository.findByIdAndPassword(id, password);
        if(employeeEntity == null) {
            mav.addObject("message", "FAILURE!!");          
        }else {
            mav.addObject("message", "SUCCESS!!");              
        }
        mav.setViewName("result");                   //ModelAndViewクラスにViewのページ名を指定
        return mav;                                  //ModelAndViewを返す
    }
}

では確認してみます。
まずはログイン画面へアクセス。

f:id:ice_black:20180502113546p:plain

正しいIDとパスワードを入力して、loginボタンを押下すると・・・ でましたーー!
f:id:ice_black:20180502113814p:plain

かなり端折ってしまいましたが・・・(汗)
時間があるときに説明書きを増やせたらいいなと思っています。