카테고리 없음

RESTful Web Service

고고잉93 2024. 3. 21. 16:33
728x90

▣ RESTful Web Service 구성

□ MappingJacksonValue 

@GetMapping("/v1/users/{id}")

	// MappingJacksonValue를 이용하여 JSON응답을 생성할때 필터링을 적용할 수 있다.
        public MappingJacksonValue retrieveUserAdmin(@PathVariable int id) {
        User user = service.findOne(id);
		
        // AdminUser -> id, name, joinDate, password, ssn
        AdminUser adminUser = new AdminUser();
        if (user == null) {
            throw new UserNotFoundException(String.format("ID[%s not found", id));
        } else{
        
        // user객체를 adminUser에 복사(서로 객체의 이름이 같은것만!)
            BeanUtils.copyProperties(user,adminUser);
        }
        
		// JSON으로 변환될 때 보여줄 필드를 지정(id, name, joinDate, ssn)
        SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("id", "name", "joinDate", "ssn");
        
        // UserInfo -> @JsonFilter("UserInfo")로 설정한것을 입력
        FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfo", filter);

        MappingJacksonValue mapping = new MappingJacksonValue(adminUser);
        mapping.setFilters(filters);
        
        // SimpleBeanPropertyFilter는 필터의 규칙을 정의하고,
        // FilterProvider는 실제 필터를 ObjectMapper에 적용하는 역할을 한다.
        // 필터의 이름은 @JsonFilter 어노테이션을 통해 클래스에 설정된 이름과 일치해야 한다.
        
        return mapping;
    }

 

 

□ HTTP Status 제어

○  @PostMapping 

   : Client가 서버에 어떠한 정보를 전달할때 PostMapping을 사용하여 전달한다.

@PostMapping("/users")
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
        User savedUser = service.save(user);
		
        // 생성한 user정보의 상세정보 URI생성
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(savedUser.getId())
                .toUri();

		// HTTP Status -> 201 created 
        return ResponseEntity.created(location).build();
    }

 

○ 예외 처리하기

User user =service.findOne(id);

        if (user == null) { // 데이터가 null이라면
            throw new UserNotFoundException(String.format("ID[%s not found", id)); //
        }

 

@ResponseStatus

// UserNotFoundException이 발생할때 HTTP상태코드를 HttpStatus.NOT_FOUND(404)로 지정한다.

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
        // 부모 클래스인 RuntimeException의 생성자를 호출하여 예외 메시지를 설정.
    }
}

 

@ControllerAdvice, @ControllerAdvice + @ExceptionHandler

@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    // Exception ex : 발생한 예외 객체를 받는다.
    // WebRequest request : 현재의 HTTP요청 정보를 받는다.

	@ExceptionHandler(Exception.class)
    	public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        ExceptionResponse exceptionResponse =
                new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));

        return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    
    
 public class ExceptionResponse {

    private Date timestamp;
    private String message;
    private String details;
}

 

 

 @Valid : Validate-api(유효성 체크)

 

 - dependency 추가

implementation 'org.springframework.boot:spring-boot-starter-validation'

@Valid 어노테이션 입력
Entity 클래스에 @Size, @Past등 valid를 위한 어노테이션 기입

 

○ Response 데이터 제어하기 ( Client에게 제공되는 정보를 제한하기)

  @JsonIgnore

public class Users{
	@JsonIgnore
  	private int age;
    
   	private String name;
    }

개별적으로 설정하거나

@JsonIgnoreProperties(value = {"age",...})
public class Users{
//	@JsonIgnore
  	private int age;
    
   	private String name;
    }

@JsonIgnoreProperties를 클래스에 두어 원하는 파라미터값들을 나열하여 지정할 수 있다.

 

 

하지만, @JsonIgnore을 적용한 후에

setAge를 한다면 age파라미터는 null로 전달된다.

 

이럴때에는 @JsonProperty(access = JsonProperty.Access.READ_ONLY)를 선언하도록 한다.

더보기

++)

Jackson 직렬화

 : Java객체를 JSON형식으로 변환하는 과정을 말한다.

// 직렬화 및 역직렬화 수행
ObjectMapper objectMapper = new ObjectMapper();

String json = objectMapper.writeValueAsString(object);
                         // Java객체를 JSON문자열로 직렬화

 

역직렬화

 : JSON데이터를 Java객체로 변환하는 과정을 말한다.

ObjectMapper objectMapper = new ObjectMapper();
MyClass obj = objectMapper.readValue(json, MyClass.class);
                          // JSON문자열을 Java객체로 역직렬화

 

728x90