Light Blue Pointer
본문 바로가기
개발일지

2023-12-21, Today I Learned

by 개발바닥곰발바닥!!! 2023. 12. 21.

오늘 한 일

 

제목(500자 까지 입력 가능), 작성 내용을 입력하기(5000자 까지 입력 가능)

  1. Column에 length를 지정함
  2. Size로 받아오는 request에서 크기 validation함

Entity

@Getter
@Entity
@NoArgsConstructor
public class Post extends Timestamped {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 500)
    private String title;

    @Column(length = 5000)
    private String content;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    public Post(PostRequest request, User user){
        this.title = request.getTitle();
        this.content = request.getContent();
        this.user = user;
    }

}

Request

@Getter
@RequiredArgsConstructor
public class PostRequest {

    @Size(max = 500, message ="title should be shorter than 500") 
    private String title;

    @Size(max = 5000, message ="content should be shorter than 5000")
    private String content;

}

Controller

@PostMapping("")
    public ApiResponse<PostResponse> postPost(
            @Valid @RequestBody PostRequest request,
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            BindingResult bindingResult
            )
    {
        // Validation exception
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (fieldErrors.size() > 0) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                log.error(fieldError.getField() + " field : " + fieldError.getDefaultMessage());
            }
            throw new IllegalArgumentException("the input content has exceeded the limit");
        }
        return new ApiResponse<>(HttpStatus.CREATED.value(),"successfully posted",postService.createPost(request,userDetails.getUser()));
    }

500글자 넘는거 보냈더니 403 forbidden됨 근데 리턴값은 왜 안 돌아오지

{
    "title" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum, odio eu tristique feugiat, dolor ipsum elementum ex, quis euismod nulla nisl nec leo. Aenean vitae erat id odio gravida bibendum. Nullam ullamcorper felis in nisl pellentesque bibendum. Sed rhoncus, augue ac fermentum sagittis, ligula justo fringilla quam, non volutpat eros leo id urna. Curabitur ut arcu eu tortor sagittis hendrerit. Integer nec libero nec augue gravida varius ut a elit. Vivamus laoreet, libero a scelerisque feugiat, libero dolor aliquet libero, a ultricies risus quam vel lectus. Suspendisse potenti...",
    "content" : "this is content2"
}

로그는 찍힘

2023-12-20T21:06:15.815+09:00  WARN 26372 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.minisun.board.global.dto.ApiResponse<com.minisun.board.post.dto.PostResponse> com.minisun.board.post.controller.PostController.postPost(com.minisun.board.post.dto.PostRequest,com.minisun.board.global.security.UserDetailsImpl,org.springframework.validation.BindingResult): [Field error in object 'postRequest' on field 'title': rejected value [Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum, odio eu tristique feugiat, dolor ipsum elementum ex, quis euismod nulla nisl nec leo. Aenean vitae erat id odio gravida bibendum. Nullam ullamcorper felis in nisl pellentesque bi
@PostMapping("")
    public ApiResponse<PostResponse> postPost(
            @Valid @RequestBody PostRequest request,
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            BindingResult bindingResult
            )
    {
        // Validation exception
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (fieldErrors.size() > 0) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                log.error(fieldError.getField() + " field : " + fieldError.getDefaultMessage());
            }
            throw new IllegalArgumentException("the input content has exceeded the limit");
        }
        return new ApiResponse<>(HttpStatus.CREATED.value(),"successfully posted",postService.createPost(request,userDetails.getUser()));
    }

Q. 근데 controller의 throw 부분 왜 안될까?

{
    "title" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum, odio eu tristique feugiat, dolor ipsum elementum ex, quis euismod nulla nisl nec leo. Aenean vitae",
    "content" : "this is content2"
}

500 이하로 주면 되긴 함

{
    "status": 201,
    "message": "successfully posted",
    "data": {
        "id": 6,
        "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum, odio eu tristique feugiat, dolor ipsum elementum ex, quis euismod nulla nisl nec leo. Aenean vitae",
        "content": "this is content2",
        "username": "minisun"
    }
}

Difference Between @Size, @Length, and @Column(length=value)

@Size Java-standard annotation,

@Length specific to Hibernate.

@Column, JPA annotation

@Size

For validations, we’ll use @Size**,** a bean validation annotation. We’ll use the property middleName annotated with @Size to validate its value between the attributes min and max:

public class User {

    // ...

    @Size(min = 3, max = 15)
    private String middleName;

    // ...

}

@Length

As we previously mentioned, @Length is the Hibernate-specific version of @Size. We’ll enforce the range for lastName using @Length:

@Entity
publicclassUser {

    // ...

    @Length(min = 3, max = 15)
private String lastName;

    // ...

}

@Column(length=value)

@Column is quite different from the previous two annotations.

We’ll use @Column to indicate specific characteristics of the physical database column. We’ll use the length attribute of the @Column annotation to specify the string-valued column length:

@Entity
publicclassUser {

    @Column(length = 3)
private String firstName;

    // ...

}Copy

The resulting column will be generated as a VARCHAR(3), and trying to insert a longer string will result in an SQL error.

Note that we’ll use @Column only to specify table column properties, as it doesn’t provide validations.

Of course, we can use @Column together with @Size to specify database column properties with bean validation:

12/19 - 게시글 수정 API

  • [ ] 토큰을 검사하여, 해당 사용자가 작성한 게시글만 수정 가능

12/20 - 게시글 삭제 API

  • [ ] 토큰을 검사하여, 해당 사용자가 작성한 게시글만 삭제 가능

'개발일지' 카테고리의 다른 글

2023-12-27, Today I Learned  (0) 2023.12.27
2023-12-26, Today I Learned  (0) 2023.12.26
2023-12-18, Today I Leanred  (0) 2023.12.18
2023-12-15, Today I Learned  (0) 2023.12.15
2023-12-14, Today I Learned  (0) 2023.12.14