프로젝트/파이널 프로젝트

RESTful Service 기능 확장 (4) - 데이터 제어 Filtering (2) 개별 사용자 조회 (@JsonFilter, SimpleBeanPropertyFilter, MappingJacksonValue, FilterProvider)

Kiwisae 2022. 11. 24. 15:39

유저는 제한된 정보에 접근할 수 있는 동시에 관리자는 모든 정보에 접근이 가능해야 한다.

 

 

 

 

@JsonIgnoreProperties 대신 @JsonFilter 라는 새로운 어노테이션을 사용한다.

그리고 "UserInfo" 라는 이름을 지정한다.

이 필터는 컨트롤러 또는 서비스 클래스에서 사용된다.

 

 

 

 

UserController를 복사해서 붙여넣기해서 새로운 파일을 만들고 이름을 변경했다.

 

AdminUserController.java

 

package com.example.restfulwebservice.user;

import java.net.URI;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
public class AdminUserController {
	
	private UserDaoService service;
	
	public AdminUserController(UserDaoService service) {
		this.service = service;
	}
	
	//전체 목록 조회
	@GetMapping ("/users")
	public List<User> retrieveAllUsers() {
		return service.findAll();
	}
	
	//개별 조회
	//Get : /users/1 or /users/10 ... -> String
	@GetMapping("/users/{id}")
	public User retrieveUser(@PathVariable int id) {
		User user = service.findOne(id);
		
		if (user == null) {
			throw new UserNotFoundException(String.format("ID[%s] not found", id));
		}
		
		return user;
	}

}

 

 

 

 

 

	//개별 조회
	//Get : /users/1 or /users/10 ... -> String
	@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));
		}
		
		//어떤 bean을 대상으로 필터를 설정할 것인지
       		//여기에 설정한 프로퍼티가 관리자에게 노출된다.
		SimpleBeanPropertyFilter filter = 
				SimpleBeanPropertyFilter.filterOutAllExcept("id", "name", "joinDate", "ssn");
		
		FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfo", filter);
		
		MappingJacksonValue mapping = new MappingJacksonValue(user);
		mapping.setFilters(filters);
		
		return mapping;
	}