★ AOP 란( Aspect Oriented Programming)
1. 생성자 변경
private UserRepository userRepository;
private HttpSession session;
// DI
public UserController(UserRepository userRepository, HttpSession session) {
this.userRepository = userRepository;
this.session = session;
}
private final UserRepository userRepository;
private final HttpSession session;
2. Table 생성 시 각 칼럼 조건
package com.cos.lsm.domain.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 20, unique = true)
// nullable = false =>null 사용여부, length = 20 => 길이 20byte , unique = true => unique 제약걸기
private String username;
@Column(nullable = false, length = 20)
private String password;
@Column(nullable = false, length = 50)
private String email;
}
- @Column 어노테이션 사용하여 컬럼 조건을 걸어준다.
- nullable : null 사용여부, length : 길이, unique : unique 여부
3. 유효성 검사 - Validation
- 회원가입 시 입력란이 null / 공백 일 경우를 막기 위해 코드를 작성하였다.
public String join(JoinReqDto dto) {
if(dto.getUsername() == null ||
dto.getPassword() == null ||
dto.getEmail() == null ||
dto.getUsername().equals("")||
dto.getPassword().equals("")||
dto.getEmail().equals("")
) {
return "error/error";
}
→ 코드가 너무 길고, 매번 사용하기에 코드가 길어져서 줄여서 쓸 수 있다.
- Maven 에서 validation 검색하여 Spring Boot Starter Validation 클릭
- pom.xml dependency 추가한 후 Dto 수정
- Table 생성 시 칼럼 조건을 걸어주면 그 조건에 맞게 유효성 검사를 위한 Annotation을 추가한다.
- @Size는 컬럼 조건과 동일하게 최소 길이와 최대 길이의 유효성을 검사한다.
- @NotNull : 입력한 값이 Not Null
- @NotEmpty : 입력한 값에 공백이 없다.
★ @NotBlank = @NotNull + @NotEmpty
@Valid annotation 삽입
@PostMapping("/join")
public String join(@Valid JoinReqDto dto, BindingResult bindingResult, Model model) {
→ @Valid 걸면 JoinReqDto에 있는 annotation을 자동으로 검증
→ 검증을 통해 실패한 것을 bindingResult에 담아준다.
if(bindingResult.hasErrors()) {
Map<String, String> errorMap = new HashMap<>();
for(FieldError error : bindingResult.getFieldErrors()) {
errorMap.put(error.getField(), error.getDefaultMessage());
System.out.println("필드 : " + error.getField());
System.out.println("메시지 : " + error.getDefaultMessage());
}
}
이는 공통 로직으로 사용 가능, 로그인에서도 사용가능
- HashMap 함수를 사용하여 error가 발생한 필드와 error 메시지를 Map에 담고, 이를 Model에 추가하여 error page
정보를 전달한다.
- 또한 공통로직으로 로그인과 회원가입 모두 같은 코드로 사용할 수 있다.
@PostMapping("login")
public String login(@Valid LoginReqDto dto, BindingResult bindingResult, Model model) {
User userEntity = userRepository.mLogin(dto.getUsername(), dto.getPassword());
System.out.println("에러사이즈 : " + bindingResult.getFieldErrors().size());
if(bindingResult.hasErrors()) {
Map<String, String> errorMap = new HashMap<>();
for(FieldError error : bindingResult.getFieldErrors()) {
errorMap.put(error.getField(), error.getDefaultMessage());
System.out.println("필드 : " + error.getField());
System.out.println("메시지 : " + error.getDefaultMessage());
}
model.addAttribute("errors", errorMap);
return "error/error";
}
session.setAttribute("principal", userEntity);
return "redirect:/home";
}
@PostMapping("/join")
public String join(@Valid JoinReqDto dto, BindingResult bindingResult, Model model) {
System.out.println("에러사이즈 : " + bindingResult.getFieldErrors().size());
if(bindingResult.hasErrors()) {
Map<String, String> errorMap = new HashMap<>();
for(FieldError error : bindingResult.getFieldErrors()) {
errorMap.put(error.getField(), error.getDefaultMessage());
System.out.println("필드 : " + error.getField());
System.out.println("메시지 : " + error.getDefaultMessage());
}
model.addAttribute("errors", errorMap);
return "error/error";
}
userRepository.save(dto.toEntity());
return "redirect:/loginForm"; // 리다이렉션 (300)
}
model.addAttribute("errorMap", errorMap);
return "error/error";
→ 에러 발생 시 에러로 이동, model을 통해 error 페이지로 errorMap 내용 넘겨준다.
* 결과
1. 로그인 시 비밀번호 미입력
2. 회원가입 시 이메일 미입력
★ Postman API Platform 설치
'Programming > SpringBoot' 카테고리의 다른 글
Spring Boot 8강 - Refactoring ② (0) | 2021.09.22 |
---|---|
Spring Boot 6강 - 로그인, 회원가입 (0) | 2021.09.19 |
Spring Boot 5강 - Json, Thread, DB연결 (2) | 2021.09.18 |
Spring Boot 4강 - Mustache, JSP 연결 (0) | 2021.09.05 |
Spring Boot 3강 - 어노테이션, IOC, DI (0) | 2021.09.05 |