import javax.validation.constraints.*;
controller
@PostMapping("/")
public ResponseEntity<> create(@Valid @RequestBody User user){
return ResponseEntity.status(HttpStatus.CREATED).body(responseUser);}
@RestController
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
//유효성 검사에 문제가 생겼을 때 화면에 오류 메세지를 출력하기 위한
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status,
WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(),
ex.getMessage(), ex.getBindingResult().toString());
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
}
다국어 처리
@Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.KOREA);
return localeResolver;
}
application.yml
spring:
messages:
basename: messages //다국어 파일의 이름을 "messages" 로 하겠다는 의미
resources에 위에 적은 이름으로
messages.properties
greeting.message=안녕하세요
messages_en.properties
greeting.message=Hello
*messages_fr.properties
greeting.message=Bonjour
//메세지소스를 반환하기 위해서
import org.springframework.context.MessageSource;
private final MessageSource messageSource;
@GetMapping("/hello")
public String hello(@RequestHeader(name="Accept-Language", required=false) Locale locale){
return messageSource.getMessage("greeting.message",null,locale);
}
<dependency>
<groupId>com.faster xml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.10.2</version>
</dependency>
중요한 데이터를 클라이언트가 바로 받아볼 수 있는 것이 아니라 이런 데이터 값을 제어하는 방법
방법 1.
@JsonIgnore
private String password;
@JsonIgnore
private String ssn;
방법 2.
@JsonIgnoreProperties(value={"password", "ssn"})
public class User{
...
private String password;
private String ssn;
}
@JsonFilter("UserInfo")
public class User{
...
}
관리자 유저컨트롤러
*개인 사용자 보기
@GetMapping("/admin/users/{id}")
public MappingJacksonValue retreveUser(@PathVariable int id){
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;
}
*유저 리스트
@GetMapping("/admin/users")
public MappingJacksonValue retrieveAllUsers(){
List<User users = service.findAll();
SimpleBeanPropertyFilter filter = simpleBeanPropertyFilter.filterOutAllExcept("id", "name" "joinDate" "ssn");
FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfo", filter);
MappingJacksonValue mapping = new MappingJacksonValue(users);
mapping.setFilters(filters);
return mapping;
}
UserV1 class
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonFilter("UserInfo")
public class UserV1{
private Integer id;
@Size(min=2, message = "이름은 두글자 이상 입력해주세요.")
private String name;
@Past
private Date joinDate;
private String ssn;
UserV2 class
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonFilter("UserInfoV2")
public class UserV2 extends UserV1 {
private String grade;
}
@GetMapping("/admin/v2/users/{id}")
public MappingJacksonValue retreveUserV2(@PathVariable int id){
//user -> user2
UserV2 userV2 = new UserV2();
BeanUtils.copyProperties(userV1, userV2);
userV2.setGrade("VIP");
SimpleBeanPropertyFilter filter = simpleBeanPropertyFilter.filterOutAllExcept("id", "name" "joinDate" "ssn", "grade");
FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfoV2", filter);
MappingJacksonValue mapping = new MappingJacksonValue(user);
mapping.setFilters(filters);
return mapping;
}
*Request Parameter
@GetMapping(value= "/users/{id}", params = "version=1") public MappingJacksonValue retreveUserV1(@PathVariable int id){...}
@GetMapping(value= "/users/{id}", params = "version=2") public MappingJacksonValue retreveUserV2(@PathVariable int id){...}
*Header
@GetMapping(value = "/users/{id}", headers="X-API-VERSION=1") public MappingJacksonValue retreveUserV1(@PathVariable int id){...}
mine
@GetMapping(value="/users/{id}", produces = "application/vnd.company.appv1+json") public MappingJacsonvalue retreveUserV1(@PathVariable int id){...}