Notice
Recent Posts
Recent Comments
Link
«   2026/09   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

helloworld

데이터 필터링 심화과정 본문

restful

데이터 필터링 심화과정

hellojava 2023. 8. 13. 20:48

전 글에서는 JsonIgnore로 데이터를 안보이게끔 하였다.

이번엔 좀 더 프로그래밍적으로 멋잇게(?) 해본다..

 

우선 JsonIgnore 어노테이션을 전부 주석처리하고

@JsonFilter를 추가한다

@Data
@AllArgsConstructor
//@JsonIgnoreProperties(value={"password"})
@JsonFilter("UserInfo")
public class User {
private Integer id;
@Size(min = 2, message = "Name 2글자 이상 입력해주세요")
private String name;
@Past
private Date joinDate;

// @JsonIgnore
private String password;
// @JsonIgnore
private String ssn;//주민등록번호
}

그리고 좀 더 알아보기 쉽게 하기 위해 AdminUserController를 생성했다.  

엔드포인트에 하나하나 다 /admin을 추가하는 것이 아닌 클래스블럭에 @RequestMapping을 추가하여 전부 admin을 추가해주었다.

 

@RestController
@RequestMapping("/admin")
public class AdminUserController {

이렇게 하면 localhost:8080/admin/users 이런식으로 타고 들어가야한다.

 

@GetMapping("/users")
public List<User> retrieveAllUsers() {
return service.findAll();
}

//GET /users/1 or /users/10 -> String
//선언할때 int라고 선언하면 자동으로 int로 매핑시켜줌
@GetMapping("/users/{id}")
public MappingJacksonValue retrieveUser(@PathVariable int id) {
User user = service.findOne(id);

if (user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found", id));
}

SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter
.filterOutAllExcept("id", "name", "joinDate","password" ,"ssn");

FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfo",filter);

MappingJacksonValue mapping = new MappingJacksonValue(user);
mapping.setFilters(filters);

return mapping;
}

 

기존 UserController를 복사해온 후 조금 수정한 것이다.

 

우선 SimpleBeanPropertyFilter로 노출시키고싶은 데이터를 적는다.

나는 신기해서 5개 다 넣어보고 2개,3개도 다 넣어봤다. ㅋㅋ..

 

그 후 FilterProvider로 도메인클래스에서 지정한 id값을 넣고, filter를 매개변수로 넣는다

 

마지막으로 MappingJacksonValue 로 user를 매핑시켜주면 끝..

 

클래스 이름들이 너무 어렵다 ㅋㅋ 현업에 종사하시는 분들은 전부 다 외우고 하시는 거겠지? 열심히 공부하자..

 

암튼 이렇게 코드를 만든 뒤 postman에서 실행시키면 

{
    "id"1,
    "name""Song",
    "joinDate""2023-08-13T11:37:12.534+00:00",
    "password""pass1",
    "ssn""701017-1111111"
}
 
이렇게 내가 지정한 데이터들이 나오게 된다. 
 
이렇게 코드를 만든 뒤에
 
localhost:9090/users 
localhost:9090/amin/users 
등 filter처리를 하지 않은 메서드를 실행시키면 에러가 난다
 
[
    {}
]{
    "timestamp""2023-08-13T11:48:01.391+00:00",
    "message""Type definition error: [simple type, class com.example.restfulwebservice.user.User]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot resolve PropertyFilter with id 'UserInfo'; no FilterProvider configured (through reference chain: java.util.ArrayList[0])",
    "details""uri=/admin/users"
}

필터 떄문이라고 하니 걱정하지말자 ..

'restful' 카테고리의 다른 글

HATEOAS  (0) 2023.08.17
버전관리  (0) 2023.08.17
데이터 필터링  (0) 2023.08.13
JSON 형태의 데이터를 xml 데이터로 변환하기  (0) 2023.08.13
유효성 검사 (Validatation)  (0) 2023.08.13