caffeine-library / pro-spring-5

🌱 전문가를 위한 스프링5를 읽는 스터디
5 stars 0 forks source link

[question] 스프링 유효성 검사 및 타입 변환의 또 다른 실례 #76

Closed JasonYoo1995 closed 2 years ago

JasonYoo1995 commented 2 years ago

질문

스프링 유효성 검사 및 타입 변환의 또 다른 실례

상세 내용

책에서 나온 유효성 검사 및 타입 변환의 예시 코드 말고, 또 다른 예시 코드가 함께 있으면 좀 더 이해가 좋을 것 같습니다.

연관 챕터

73

JasonYoo1995 commented 2 years ago

코드 출처 : https://github.com/joneconsulting/msa_with_spring_cloud/blob/main/user-service/src/main/java/com/example/userservice/controller/UserController.java

Layer

UserController.java

@RestController
public class UserController {
    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
    ...
    @PostMapping("/users")
    public ResponseEntity<ResponseUser> createUser(@RequestBody RequestUser user) {
        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        UserDto userDto = mapper.map(user, UserDto.class);
        userService.createUser(userDto);

        ResponseUser responseUser = mapper.map(userDto, ResponseUser.class);

        return ResponseEntity.status(HttpStatus.CREATED).body(responseUser);
    }
    ...
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {
    UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    ...
    @Override
    public UserDto createUser(UserDto userDto) {
        userDto.setUserId(UUID.randomUUID().toString());

        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        UserEntity userEntity = mapper.map(userDto, UserEntity.class);
        userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd()));

        userRepository.save(userEntity);

        UserDto returnUserDto = mapper.map(userEntity, UserDto.class);

        return returnUserDto;
    }
    ...
}

UserRepository.java

public interface UserRepository extends CrudRepository<UserEntity, Long> {
    UserEntity findByUserId(String userId);
    UserEntity findByEmail(String username);
}

image

데이터 객체(VO / DTO)

RequestUser.java

@Data
public class RequestUser {
    @NotNull(message = "Email cannot be null")
    @Size(min = 2, message = "Email not be less than two characters")
    @Email
    private String email;

    @NotNull(message = "Name cannot be null")
    @Size(min = 2, message = "Name not be less than two characters")
    private String name;

    @NotNull(message = "Password cannot be null")
    @Size(min = 8, message = "Password must be equal or grater than 8 characters")
    private String pwd;
}

UserDto.java

@Data
public class UserDto {
    private String email;
    private String name;
    private String pwd;
    private String userId;
    private String encryptedPwd;
}

UserEntity.java

@Data
@Entity
@Table(name = "users")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 50, unique = true)
    private String email;

    @Column(nullable = false, length = 50)
    private String name;

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

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

image

image

wooyounggggg commented 2 years ago

원래 유효성 검사를 실패하면 400 bad request를 뱉는 것으로 알고 있었는데 방금 테스트 해봤을 땐 401 unauthorized를 돌려주네요.

관련 정책이 변경된 것인지 제가 설정을 잘못한 것인지 알 수가 없어서 테스트 한번 돌려봐주시면 감사하겠습니다 🙏