Define the response content type without using HttpServletResponse

advertisements

How can I get HttpServletResponse object in a method in my spring controller so that my application remains loosely coupled with Http API?

Thanks...

Edit: Actually what i want is to set the ContentType of the HttpServletResponse object in my controller.Does spring provides any way for this without getting HttpServletResponse object as argument in the method of controller?


I can see two options:

If the content-type that you want is static, then you can add it to @RequestMapping, e.g.

@RequestMapping(value="...", produces="text/plain")

This will only work if the HTTP request contains the same content-type in its Accept header, though. See 16.3.2.5 Producible Media Types.

Alternatively, use ResponseEntity, e.g.

@RequestMapping("/something")
public ResponseEntity<String> handle() {
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(new MediaType("text", "plain"));
  return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

MediaType also has a handful of common mime types defined as constants, e.g. MediaType.TEXT_PLAIN.

See 16.3.3.6 Using HttpEntity<?>