2016-11-04 2 views
0

반환 할 데이터가 없으면 스프링이 항상 json을 생성하도록하고, 심지어 빈 json 객체도 생성하도록합니다. 서비스는 상태 코드와 상관없이 json이 아닌 응답을 거부하는 다른 서비스를 거칩니다. 그것은 좋지는 않지만 우리는 이것을 통제 할 수 없습니다.스프링 컨트롤러는 항상 json을 생성합니다.

스프링 컨트롤러를 사용하면 json을 생성하도록 지시 할 수 있지만 반환 할 내용이있는 경우에만 작동합니다. 모든 응답을 json으로 만드는 빠르고 우아한 방법이 있습니까?

간단히 말해서 null을 확인하기 위해 if 문을 추가하는 것입니다. 하지만 헤더와 응답 본문을 수동으로 설정해야하므로 추한 것입니다.

나는 누군가가 더 좋은 방법을 알고 있기를 바랍니까?

감사

당신은 내가이 BaseAjaxResponse 사용 예를 들어, "컨테이너"개체 의 응답을 포장 할 수
+0

here을 볼 수있는 방법 경우에 예외를 throw에 대한 서비스가 null/nothing을 반환하고 ExceptionHandler를 사용하여 적절한 응답과 헤더를 설정합니까? – Mubin

답변

1

는, 당신은 HandlerInterceptorAdapter에서 postHandle()를 재정 의하여 하나의 장소에서 설정할 수 있습니다

@Component 
public class ResponseInterceptor extends HandlerInterceptorAdapter { 

    @Override 
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, 
      final ModelAndView modelAndView) throws IOException { 
     if (response.getContentType() == null || response.getContentType().equals("")) { 
      response.setContentType("application/json"); 
     } 
    } 
} 

당신은

+0

대단히 고마워요, 이것이 제가 찾고 있던 것입니다. – wybourn

0

:

@RequestMapping(method = { RequestMethod.POST }, value = { "/find" }) 
    public ResponseEntity<BaseAjaxResponse> createCandidato(@RequestBody CandidatoDto candidato){ 
     BaseAjaxResponse bar = new BaseAjaxResponse(); 
     HttpStatus statusCode = null; 
     List<Object> payload = null; 
     StopWatch sw = new StopWatch("Find"); 
     try 
     { 
      sw.start(); 
      payload = myService.find(); 
      sw.stop(); 
      if(payload == null || payload.isEmpty()) 
      { 
       statusCode = HttpStatus.NO_CONTENT; 
       bar.setCodiceOperazione(statusCode.value()); 
       bar.setDescrizioneEsitoOperazione("No result"); 
      } 
      else 
      { 
       statusCode = HttpStatus.OK; 
       bar.setCodiceOperazione(statusCode.value()); 
       bar.setDescrizioneEsitoOperazione("Got result");  
       //Set the object count and the number of found objects 
      } 
     } 
     catch (Exception e) 
     { 
      String message = "Errore nell'inserimento di un candidato; "+e.getMessage(); 
      statusCode = HttpStatus.INTERNAL_SERVER_ERROR; 
      bar.setCodiceOperazione(statusCode.value()); 
      bar.setDescrizioneEsitoOperazione(message); 
      logger.error(message, e); 

     } 
     finally 
     { 
      if(sw.isRunning()) 
      { 
       sw.stop(); 
       if(logger.isDebugEnabled()) 
       { 
        logger.debug("CHIUSURA STOPWATCH FORZATA. "+sw.toString()); 
       } 
      } 
     } 

     return new ResponseEntity<BaseAjaxResponse>(bar, statusCode); 
    } 
:이 전략을 사용하는 내 컨트롤러에서 다음

public class BaseAjaxResponse implements Serializable 
{ 

    private static final long serialVersionUID = 9087132709920851138L; 
    private int codiceOperazione; 
    private String descrizioneEsitoOperazione; 
    private long numeroTotaleOggetti; 
    private long numeroOggettiRestituiti; 
    private List<? extends Object> payload; 
    //Constructors and getter/setter 

} 

유용 할 수 있기를 바랍니다.

Ang 모든 응답 application/json을 반환하려면 ELO

+0

불행히도 서비스가 문자열을 반환하므로 작동하지 않습니다. 저는 다른 많은 서비스로 작업하고 있으며 불행히도 리팩토링에 대해서는 제한적입니다. – wybourn

+0

정말로 필요한 것은 빈 또는 빈 문자열을 빈 json 객체로 변환하는 것입니다. 래퍼 접근법의 문제점은 필드를 추가하는 반면 빈 json 객체가 필요하다는 것입니다. – wybourn

+0

그러면 사용자 지정 메시지 변환기를 사용할 수 있습니다. 이 메시지 변환기에서 JSON을 원하는대로 처리 할 수 ​​있습니다. –

관련 문제