Programing

Spring MVC 컨트롤러 메소드가 값을 반환하지 않으면 무엇을 반환합니까?

lottogame 2020. 7. 15. 07:32
반응형

Spring MVC 컨트롤러 메소드가 값을 반환하지 않으면 무엇을 반환합니까?


jQuery를 사용하여 $.getJSON()간단한 Spring MVC 백엔드를 비동기 호출합니다. 대부분의 스프링 컨트롤러 메소드는 다음과 같습니다.

@RequestMapping(value = "/someURL", method = RequestMethod.POST)
public @ResponseBody SomePOJO getSomeData(@ModelAttribute Widget widget,
    @RequestParam("type") String type) {
    return someDAO.getSomeData(widget, type);
}   

각 컨트롤러가 @ResponseBody클라이언트 측에서 기대하는 JSON을 JSON으로 반환하도록 설정했습니다 .

그러나 요청이 클라이언트 측에 콘텐츠를 반환하지 않아야 할 경우 어떻게됩니까? 를 가질 수 있어요:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public @ResponseBody void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

그렇지 않은 경우 여기에서 사용하기에 적합한 구문은 무엇입니까? 미리 감사드립니다!


void를 반환하면 @ResponseBody가 필요없는 @ResponseStatus (value = HttpStatus.OK)로 메서드를 표시해야합니다.

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

get 메소드 만 200 상태 코드 내 재성을 리턴합니다. 다른 모든 메소드는 세 가지 중 하나를 수행합니다.

  • void를 반환하고 메소드에 @ResponseStatus(value = HttpStatus.OK)
  • 객체를 반환하고 @ResponseBody
  • HttpEntity인스턴스 반환

적절한 헤더를 사용하여 ResponseEntity를 간단히 반환 할 수 있습니다.

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}

"ResponseEntity"개체를 반환 할 수 있습니다. "ResponseEntity"오브젝트를 사용하면 응답 오브젝트 (HTTP 응답 코드 및 HTTP 상태 코드 포함)를 구성 할 때와 응답 오브젝트에서 정보를 가져올 때 매우 편리합니다.

getHeaders (), getBody (), getContentType (), getStatusCode () 등의 메소드는 ResponseEntity 오브젝트 읽기 작업을 매우 쉽게 만듭니다.

http 상태 코드가 204 (No Content) 인 ResponseEntity 오브젝트를 사용해야합니다. 이는 요청이 올바르게 처리되었고 응답 본문이 의도적으로 비어 있음을 지정하기위한 것입니다. 적절한 상태 코드를 사용하여 올바른 정보를 전달하는 것은 특히 여러 클라이언트 응용 프로그램에서 사용할 API를 만드는 경우 매우 중요합니다.


예, @ResponseBody를 void반환 유형 과 함께 사용할 수 있습니다 .

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseBody
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

void를 반환하는 데 아무런 문제가 없으며 요청 @ResponseBody을해야 POST합니다.

다른 사람이 성공 상태를 언급하는 대신 HTTP 상태 코드를 사용하여 예외 핸들러 루틴 내에서 오류를 정의하십시오. 일반적인 메소드 200는 원하는 응답 코드 를 반환하고 예외 처리기는 오류 객체와 다른 코드 (예 :)를 반환 할 수 있습니다 500.


그러나 시스템의 크기와 기능이 커짐에 따라 항상 json을 반환하는 것은 전혀 나쁜 생각이 아니라고 생각합니다. 더 건축 / "대규모 디자인"문제입니다.

코드와 데이터라는 두 가지 알려진 필드를 사용하여 항상 JSON을 복구하는 것에 대해 생각할 수 있습니다. 여기서 code는 수행 할 작업의 성공을 지정하는 숫자 코드이고 data는 요청 된 작업 / 서비스와 관련된 추가 데이터입니다.

백엔드 서비스 제공 업체를 사용할 때 모든 서비스가 제대로 작동하는지 확인할 수 있습니다.

So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.


Here is example code what I did for an asynchronous method

@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void importDataFromFile(@RequestParam("file") MultipartFile file) 
{
    accountingSystemHandler.importData(file, assignChargeCodes);
}

You do not need to return any thing from your method all you need to use this annotation so that your method should return OK in every case

@ResponseStatus(value = HttpStatus.OK)

참고URL : https://stackoverflow.com/questions/12837907/what-to-return-if-spring-mvc-controller-method-doesnt-return-value

반응형