필드 값에 보이지 않게 하고 싶은 데이터가 있을것이다.
예를 들면 회원정보 중에 비밀번호같은건 화면에 보이면 보안상 좋지 않을것이다. 그래서 첫번째 방법으로는
@JsonIgnore
private String password;
이렇게 @JsonIgnore를 써서 passowrd필드를 표시되지 않게 가릴수 있다. 저렇게 보여지지 않아야할 필드명 위에 써주면 됨.
두번째 방법은
@Data
@AllArgsConstructor
@JsonIgnoreProperties(value = {"password", "name"})
@NoArgsConstructor
public class User {
private Integer id;
@Size(min = 2, message = "Name은 2글자 이상 입력해주세요")
private String name;
@Past
private Date joinDate;
private String password;
private String ssn;
}
@JsonIgnoreProperties를 이용해서 원하는 필드명을 적어주면 그 필드는 나타나지 않게 된다. 물론 value는 하나 또는 여러개 가능.
마지막으로는
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonFilter("UserInfo")
public class User {
private Integer id;
@Size(min = 2, message = "Name은 2글자 이상 입력해주세요")
private String name;
@Past
private Date joinDate;
private String password;
private String ssn;
}
@JsonFilter를 써주는건데 "UserInfo"는 이 필터를 적용할 수 있게 필터 이름을 정해주는 것이다.
구현한걸 보면
@GetMapping(value = "/users/{id}", produces = "application/vnd.company.appv2+json")
public MappingJacksonValue retrieveUserV2(@PathVariable int id) {
final User user = service.findOne(id);
if (user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found", id));
}
UserV2 userV2 = new UserV2();
BeanUtils.copyProperties(user, userV2);
userV2.setGrade("VIP");
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter
.filterOutAllExcept("id", "name", "joinDate", "grade"); // 필터에서 제외할 필드명
FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfoV2", filter); // UserInfo는 User클래스에서 정해놓은 jsonFilter이름
final MappingJacksonValue mapping = new MappingJacksonValue(userV2); // 조회한 user값을 json으로 매핑하고
mapping.setFilters(filters); // 필터링된걸 세팅해준다.
return mapping; // 필터링된 값을 반환하기 위해서는 그냥 User같은 도메인객체를 반환할수 없어서 매핑된 값을 반환한다.
}
filterOutAllExcept()에 보여질 필드명을 다 적는다. 적지 않은 필드는 필터링이 되어서 표시되지 않는다.
이건 제목과 상관없이 버전관리 할때.
//@GetMapping("/v1/users/{id}") // URI를 이용한 버전관리
//@GetMapping(value = "/users/{id}/", params = "version=1") // 파라미터를 이용한 버전관리
//@GetMapping(value = "/users/{id}", headers = "X-API-VERSION=1") // header값을 이용한 버전 관리
@GetMapping(value = "/users/{id}", produces = "application/vnd.company.appv1+json") // MIME TYPE을 이용한 버전관리
포스트맨에 돌릴때 params 값에 key = value 에 맞게 적어야 한다. produces는 key를 Accept로 해야함.
'RestfulWebService' 카테고리의 다른 글
Spring Security (0) | 2022.09.17 |
---|---|
HAL explorer(hal browser) (0) | 2022.09.17 |
HATEOAS (0) | 2022.09.16 |
스웨거 생성하기 (0) | 2022.09.16 |