What is the difference between ResponseEntity and @ResponseBody?

后端 未结 2 1071
一生所求
一生所求 2020-12-12 16:17

I have a simple handler in my controller which returns a message

@RequestMapping(value = \"/message\")
@ResponseBody
public Message get() {
    return new Me         


        
2条回答
  •  情歌与酒
    2020-12-12 16:54

    HttpEntity represents an HTTP request or response consists of headers and body.

    // Only talks about body & headers, but doesn't talk about status code
    public HttpEntity(T body, MultiValueMap headers)
    

    ResponseEntity extends HttpEntity but also adds a Http status code.

    // i.e ResponseEntity = HttpEntity + StatusCode
    public ResponseEntity(T body, MultiValueMap headers, HttpStatus statusCode)
    

    Hence used to fully configure the HTTP response.

    For Ex:

    @ControllerAdvice 
    public class JavaWebExeptionHandler {
    
        @Autowired
        ExceptionErrorCodeMap exceptionErrorCodeMap;
    
        @ExceptionHandler(RuntimeException.class)
        public final ResponseEntity handleAllExceptions(Exception ex) {
            Integer expCode = exceptionErrorCodeMap.getExpCode(ex.getClass());
            // We have not added headers to response here, If you want you can add by using respective constructor
            return new ResponseEntity(new ExceptionResponseBody(expCode, ex.getMessage()),
                    HttpStatus.valueOf(expCode));
        }
    
    }
    

    @ResponseBody indicates that return value of method on which it is used is bound to the response body (Mean the return value of method is treated as Http response body)

提交回复
热议问题