今度には登録ページを作ります。
まず、Contorller にJoinformで登録ページを呼び出しがあるように設定します。
@GetMapping("/joinform")
public String join(Model model){
model.addAttribute("userFormDto",new UserFormDto());
return "/joinform";
}
@PostMapping("/joinform")
public String join(@Valid UserFormDto userFormDto, BindingResult bindingResult, Model model){
if(bindingResult.hasErrors()){
return "/joinform";
}
try{
User user = User.createUser(userFormDto, passwordEncoder);
userService.saveUser(user);
} catch (IllegalStateException e){
model.addAttribute("errorMessage", e.getMessage());
return "/joinform";
}
return "redirect:/";
}
passwordEncodingために@beanを登録します。
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
そして、user entityを作ります。
package com.rbwsn.entity;
import com.rbwsn.constant.Role;
import com.rbwsn.dto.UserFormDto;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@Getter @Setter
public class User {
@Id // 基本のKEY
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String email;
@Enumerated(EnumType.STRING)
private Role role; // USER, ADMIN, MEMBER
@CreationTimestamp
private Timestamp createDate;
public static User createUser(UserFormDto userFormDto, PasswordEncoder passwordEncoder){
User user =new User();
user.setUsername(userFormDto.getUsername());
user.setEmail(userFormDto.getEmail());
String password = passwordEncoder.encode(userFormDto.getPassword());
user.setPassword(password);
user.setRole(Role.USER);
return user;
}
}
これから、userとserviceと通信する UserDto Classを作ります。
package com.rbwsn.dto;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
@Getter @Setter
public class UserFormDto {
@NotBlank(message = "nameは必須入力値です。")
private String username;
@NotBlank(message = "emailは必須入力値です。")
@Email(message = "email 形式で入力をお願いします。")
private String email;
@NotBlank(message = "passwordは必須入力値です。")
@Length(min = 6,max = 16, message = "passwordは 6文字以上 16文字以下で入力をお願いします。")
private String password;
}
このAnnotationするようにMAVENに依存性を追加します。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
そして、UserEntityがDBと通信できるようにJpaRepositoryをextendsするUserRepositoryを作ります。
package com.rbwsn.repository;
import com.rbwsn.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Long> {
User findByEmail(String email); // 重複メールチェック
}
DBの機能をするUSERSERVICEを作ります。
package com.rbwsn.service;
import com.rbwsn.entity.User;
import com.rbwsn.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@RequiredArgsConstructor // private finalをbeenに注入
public class UserService {
private final UserRepository userRepository;
public User saveUser(User user){
check_User_Email(user);
return userRepository.save(user);
}
private void check_User_Email(User user){
User findEmail =userRepository.findByEmail(user.getEmail());
if(findEmail!=null){
throw new IllegalStateException("また、加入になる人です。");
}
}
}
そして、joinform.htmlパイルを追加します。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layouts/content1}">
<th:block layout:fragment="css">
<style>
.fieldError{
color: red;
}
</style>
</th:block>
<th:block layout:fragment="script">
<script th:inline="javascript">
$(document).ready(function () {
var errorMessage = [[${errorMessage}]];
if(errorMessage != null){
alert(errorMessage)
}
});
</script>
</th:block>
<div layout:fragment="content">
<!--userFormDtoの形式でfieldを作ります。-->
<form class="loginformz" action="/joinform" role="form" method="post" th:object="${userFormDto}" >
<h1 class="border-bottom"> 登録ページ</h1>
<div class="form-floating">
<input type="text" th:field="*{username}" class="form-control" placeholder="Name">
<p th:if="${#fields.hasErrors('username')}" th:errors="*{username}" class="fieldError"></p>
</div>
<div class="form-floating">
<input type="email" class="form-control" th:field="*{email}" placeholder="Email address">
<p th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="fieldError"></p>
</div>
<div class="form-floating">
<input type="password" class="form-control" th:field="*{password}" placeholder="password">
<p th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="fieldError"></p>
</div>
<button class="btn btn-primary" type="submit" >登録</button>
</form>
</div>
</html>
Uploaded by Notion2Tistory v1.1.0