Spring MVC 또는 Spring-Boot에서 다양한 유형의 ResponseEntity를 반환하는 가장 좋은 방법은 무엇입니까?
Spring MVC 4(스프링 부트)됩니다.ResponseEntity그러나 경우에 따라서는 JSON을 성공시키고 싶고 검증 오류가 있으면 JSON을 성공시키고 싶습니다.현재 성공과 오류 대응이 전혀 달라 오류와 성공을 위한 2개의 클래스를 만들었습니다. 에서 반환하고 ResponseEntity<Success>★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 않으면 ResponseEntity<Error>떻게게 할?? ???
Success ★★★★★★★★★★★★★★★★★」Error성공과 오류 응답을 나타내기 위해 사용하는 두 개의 클래스입니다.
봄을 합니다.@ControllerAdvice에러를 처리합니다."스프링 부트 오류 처리" 섹션부터 시작하여 이 가이드를 읽어 보십시오.자세한 논의를 위해 Spring.io 블로그에 2018년 4월에 업데이트된 기사가 있습니다.
이 기능의 간단한 개요:
- 는 반환만 .
ResponseEntity<Success>에러 또는 예외 응답을 반환할 책임은 없습니다. - 모든 컨트롤러의 예외를 처리하는 클래스를 구현합니다.에는 '하다'가 .
@ControllerAdvice - 에는, 「어드바이저」라고 코멘트가 붙은 메서드가 되어 있습니다.
@ExceptionHandler - 각 예외 핸들러 메서드는 하나 이상의 예외 유형을 처리하도록 구성됩니다.이러한 방법에서는 오류에 대한 응답 유형을 지정할 수 있습니다.
- 예를 들어 (컨트롤러 어드바이스 클래스에서) 검증 오류 예외 핸들러 메서드를 선언합니다.은 '돌아가다' 입니다.
ResponseEntity<Error>
이 방법에서는 API 내의 모든 엔드포인트에 대해 컨트롤러 예외 처리를 한 곳에 구현하기만 하면 됩니다.또한 API가 모든 엔드포인트에서 동일한 예외 응답 구조를 쉽게 가질 수 있습니다.이것에 의해, 클라이언트의 예외 처리가 간소화됩니다.
와일드카드 「」를 할 수 .<?>Success ★★★★★★★★★★★★★★★★★」Error 매핑
public ResponseEntity<?> method() {
boolean b = // some logic
if (b)
return new ResponseEntity<Success>(HttpStatus.OK);
else
return new ResponseEntity<Error>(HttpStatus.CONFLICT); //appropriate error code
}
@Mark Norman의 답변은 올바른 접근법이다.
잘은 모르겠지만, 제 생각엔@ResponseEntity ★★★★★★★★★★★★★★★★★」@ResponseBody 것을 것은 이고, , 성공 성공 등의 입니다.
@RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
Book bookInfo2() {
Book book = new Book();
book.setBookName("Ramcharitmanas");
book.setWriter("TulasiDas");
return book;
}
@RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity<Book> bookInfo3() {
Book book = new Book();
book.setBookName("Ramayan");
book.setWriter("Valmiki");
return ResponseEntity.accepted().body(book);
}
상세한 것에 대하여는, http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity 를 참조해 주세요.
동일한 요청 매핑 메서드에서 성공과 오류를 반환하기 위해 다음과 같이 구현할 수도 있습니다. Object class(java에서는 모든 클래스의 부모 클래스):-
public ResponseEntity< Object> method() {
boolean b = // logic here
if (b)
return new ResponseEntity< Object>(HttpStatus.OK);
else
return new ResponseEntity< Object>(HttpStatus.CONFLICT); //appropriate error code
}
다음과 같이 객체 또는 문자열과 함께 지도를 사용할 수 있습니다.
@RequestMapping(value = "/path",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Map<String,String>> getData(){
Map<String,String> response = new HashMap<String, String>();
boolean isValid = // some logic
if (isValid){
response.put("ok", "success saving data");
return ResponseEntity.accepted().body(response);
}
else{
response.put("error", "an error expected on processing file");
return ResponseEntity.badRequest().body(response);
}
}
스프링 2에서는 이를 사용하여 String, 다른 HTTP 상태 코드, DTO를 동시에 반환할 수 있는 Response Status Exception이 도입되었습니다.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
반품 가능ResponseEntity다음과 같은 제네릭스를 사용하지 않고
public ResponseEntity method() {
boolean isValid = // some logic
if (isValid){
return new ResponseEntity(new Success(), HttpStatus.OK);
}
else{
return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST);
}
}
방법은 다음과 같습니다.
public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint.
try {
Integer.parseInt(player);
return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST);
} catch (Exception e) {
}
Message msg = new Message(player, "Hello " + player);
return new ResponseEntity < Message > (msg, HttpStatus.OK);
}
@RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint.
try {
Integer.parseInt(player);
List < ErrorResponse > errs = new ArrayList < ErrorResponse > ();
errs.add(new ErrorResponse("111", "player is not found"));
return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST);
} catch (Exception e) {
}
Message msg = new Message(player, "Hello " + player);
List < Message > msgList = new ArrayList < Message > ();
msgList.add(msg);
return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK);
}
커스텀 예외 클래스를 사용하면 다른 HTTP 상태 코드와 dto 개체를 반환할 수 있습니다.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new UserNotFoundException("A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
예외 클래스
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
나는 이런 수업을 이용하곤 했다.statusCode 는, 에러 메세지가 메세지로 설정되어 있는 경우에 설정됩니다.데이터는 맵 또는 목록에 적절한 형태로 저장됩니다.
/**
*
*/
package com.test.presentation.response;
import java.util.Collection;
import java.util.Map;
/**
* A simple POJO to send JSON response to ajax requests. This POJO enables us to
* send messages and error codes with the actual objects in the application.
*
*
*/
@SuppressWarnings("rawtypes")
public class GenericResponse {
/**
* An array that contains the actual objects
*/
private Collection rows;
/**
* An Map that contains the actual objects
*/
private Map mapData;
/**
* A String containing error code. Set to 1 if there is an error
*/
private int statusCode = 0;
/**
* A String containing error message.
*/
private String message;
/**
* An array that contains the actual objects
*
* @return the rows
*/
public Collection getRows() {
return rows;
}
/**
* An array that contains the actual objects
*
* @param rows
* the rows to set
*/
public void setRows(Collection rows) {
this.rows = rows;
}
/**
* An Map that contains the actual objects
*
* @return the mapData
*/
public Map getMapData() {
return mapData;
}
/**
* An Map that contains the actual objects
*
* @param mapData
* the mapData to set
*/
public void setMapData(Map mapData) {
this.mapData = mapData;
}
/**
* A String containing error code.
*
* @return the errorCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* A String containing error code.
*
* @param errorCode
* the errorCode to set
*/
public void setStatusCode(int errorCode) {
this.statusCode = errorCode;
}
/**
* A String containing error message.
*
* @return the errorMessage
*/
public String getMessage() {
return message;
}
/**
* A String containing error message.
*
* @param errorMessage
* the errorMessage to set
*/
public void setMessage(String errorMessage) {
this.message = errorMessage;
}
}
이게 도움이 됐으면 좋겠다.
주의: 스프링부트 1에서 스프링부트 2로 업그레이드하면ResponseStatusExceptionHttp 에러 코드와 설명이 포함되어 있습니다.
따라서 제네릭스를 의도한 대로 효과적으로 사용할 수 있습니다.
유일하게 조금 어려운 것은 상태 204(본문 없음 OK)의 응답 타입입니다.나는 그 방법들을 다음과 같이 표시하는 경향이 있다.ResponseEntity<?>,왜냐면ResponseEntity<Void>예측성이 떨어집니다.
예외적인 경우에는 응용 프로그램에서 HTTP API에 대한 RFC-7807 Problem Details 표준을 채택할 것을 권장합니다.
Zalando의 「봄의 문제」는, Spring Boot 와의 뛰어난 통합을 실현.기존의 Spring Boot 베이스의 애플리케이션과 간단하게 통합할 수 있습니다.JHIPster가 했던 것처럼요
어플리케이션에서 RFC-7087을 채택한 후 컨트롤러 메서드에 예외를 적용하기만 하면 다음과 같은 상세하고 표준적인 오류 응답을 얻을 수 있습니다.
{
"type": "https://example.com/probs/validation-error",
"title": "Request parameter is malformed.",
"status": 400
"detail": "Validation error, value of xxx should be a positive number.",
"instance": "/account/12345/msgs/abc",
}
@MarkNorman의 답변을 팔로업하려면 , 다음의 예외에 대해서, 매핑을 정의할 필요가 있습니다.service고객님께controller(HTTP 에러 코드).
- 성공 응답이 매핑된 위치
200상태(OK) - 매핑된 검증 예외
400상태(BAD_REQUEST) - 수 . 레코드는 없습니다.
404 - 기타
500
예를 들어 코드는 다음과 같습니다.
@GetMapping("/persons/{id}")
public ResponseEntity<Success> findPersonById(@PathVariable("id") Long id) {
try {
var person = service.findById(id);
var message = new Message(HttpStatus.OK, getCurrentDateTime(), person);
return message;
} catch(ServiceException exception) {
throw new NotFoundException("An error occurs while finding a person", exception);
}
}
.ControllerAdvice
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<Error> handleNotFoundException(NotFoundException exception) {
var error = new Error(HttpStatus.NOT_FOUND,
getCurrentDateTime(),
exception.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
이해해야 할 가장 중요한 것은 이 모든 것이RestControllersHTTP를 사용합니다.
언급URL : https://stackoverflow.com/questions/38117717/what-is-the-best-way-to-return-different-types-of-responseentity-in-spring-mvc-o
'programing' 카테고리의 다른 글
| 캐스팅을 피해야 하는 이유는 무엇입니까? (0) | 2023.02.05 |
|---|---|
| django 테스트에서는 mariadb와 keepdb를 어떻게 사용합니까? (0) | 2023.02.05 |
| 명령 프롬프트를 사용하여 mysql 데이터베이스를 내보내려면 어떻게 해야 합니까? (0) | 2023.02.05 |
| CREATE TABLE 문에 생성되지 않은 인덱스 및 제약 조건 (0) | 2023.02.05 |
| 스프링 데이터 JPA에서 FetchMode의 작동 방식 (0) | 2023.01.26 |