TIL (Today I Learned)

TIL) Lv2 피드백 복습하며 배운 정보들

Won's log 2023. 7. 12. 22:49

passwordEncoder

클라이언트가 입력한 비밀번호를 암호화해 주는 인터페이스 

 //비밀번호 확인 (password 가 다른 경우)
        if(!passwordEncoder.matches(password, user.getPassword())) {
            throw new IllegalArgumentException("비밀번호가 일치하지 않습니다.");
        }
        // 사용자가 입력한 Password와 인코딩한 상태에서의 비밀번호를 비교해주는 메서드

인터페이스이기 때문에 사용하려면 Configuaration에서 @Bean으로 등록해줘야 한다.

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

객체를 생성하면 빈으로 등록되어  생성자로 주입받아서 사용할 수 있게 된다.  

 

Optional

단건을 조회할 때 Optional 사용

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
    // 단건을 조회할 때 Optional 사용
}

isPresent는 Optional이 가지고 있는 매소드이다.

값이 없으면 Null, 있으면 value를 제공한다.

 

unique = true

하나만 존재하도록, 중복되어 존재하지 않도록 지정한다.

[User Entity]

@Column(nullable = false, unique = true)
    private String username;

 

orElseThrow

Null이 아니면 값을 주고, null이면 IllegalExcetpion 발행

public void login(AuthRequestDto requestDto) {
        String username = requestDto.getUsername();
        String password = requestDto.getPassword();

        //사용자 확인 (username 이 없는 경우)
        User user = userRepository.findByUsername(username).orElseThrow(
                () -> new IllegalArgumentException("등록된 사용자가 없습니다.")
        );

        //비밀번호 확인 (password 가 다른 경우)
        if(!passwordEncoder.matches(password, user.getPassword())) {
            throw new IllegalArgumentException("비밀번호가 일치하지 않습니다.");
        }
    }

 

 

 

@RequestBody

public @interface RequestBody

Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

클라이언트에서 서버로 필요한 데이터를 요청하기 위해 JSON 데이터를 요청 본문에 담아서 서버로 보내면, 서버에서는 @RequestBody 어노테이션을 사용하여 HTTP 요청 본문에 담긴 값들을 자바객체로 변환시켜, 객체에 저장한다.

 

+ @Valid 를 이용해 @RequestBody 객체 검증하기

파라미터로 @RequestBody 어노테이션 옆에 @Valid를 작성하면, RequestBody로 들어오는 객체에 대한 검증을 수행한다. 이를 통해 들어오는 객체를 제한시킬 수 있다. 

 

+@Valid와 @Pattern 은 짝으로 잘 사용한다. 

[Controller]

 @PostMapping("/signup")
    public ResponseEntity<ApiResponseDto> signUp(@Valid @RequestBody AuthRequestDto requestDto) {

        try {
            userService.signup(requestDto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(new ApiResponseDto("중복된 username 입니다.", HttpStatus.BAD_REQUEST.value()));
        }

        return ResponseEntity.status(201).body(new ApiResponseDto("회원가입 성공", HttpStatus.CREATED.value()));
    }

[AuthRequestDto]

@Getter
@Setter
public class AuthRequestDto {
    @Pattern(regexp = "^[a-z0-9]{4,10}$",
             message = "최소 4자 이상, 10자 이하이며 알파벳 소문자(a~z), 숫자(0~9) 로 구성되어야 합니다.")
    private String username;

    @Pattern(regexp = "^[a-zA-Z0-9!@#$%^&*()_+{}:\"<>?,.\\\\/]{8,15}$",
             message = "최소 8자 이상, 15자 이하이며 알파벳 대소문자(a~z, A~Z), 숫자(0~9), 특수문자 로 구성되어야 합니다.")
    private String password;

    private UserRoleEnum role; // 회원 권한 (ADMIN, USER)
}

 

@ResponseBody 

서버에서 클라이언트로 응답 데이터를 전송하기 위해 @ResponseBody 어노테이션을 사용하여 자바 객체를 HTTP 응답 본문의 객체로 변환하여 클라이언트로 전송한다. 

 

@RestController

@Controller와는 다르게 @RestController는 리턴값에 자동으로 @ResponseBody가 붙게 되어 별도 어노테이션을 명시해주지 않아도 HTTP 응답데이터(body)에 자바 객체가 매핑되어 전달된다.

 

@Controller인 경우에 바디를 자바객체로 받기 위해서는 @ResponseBody 어노테이션을 반드시 명시해주어야 한다.

 

출처 :

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html

 

RequestBody (Spring Framework 6.0.10 API)

Whether body content is required. Default is true, leading to an exception thrown in case there is no body content. Switch this to false if you prefer null to be passed when the body content is null.

docs.spring.io

 

https://cheershennah.tistory.com/179

 

[Spring] @RequestBody / @ResponseBody 어노테이션 이란?

스프링에서 비동기 처리를 하는 경우 @RequestBody , @ResponseBody를 사용한다. 비동기 처리를 위해 이 어노테이션들은 어떻게 작동할까? 클라이언트와 서버의 비동기 통신 클라이언트에서 서버로 통

cheershennah.tistory.com

 

https://jyami.tistory.com/55

 

@Valid 를 이용해 @RequestBody 객체 검증하기

Springboot를 이용해서 어노테이션을 이용한 validation을 하는 방법을 적으려 한다. RestController를 이용하여 @RequestBody 객체를 사용자로부터 가져올 때, 들어오는 값들을 검증할 수 있는 방법을 소개한

jyami.tistory.com

 

추가 공부할 것

csrf