Define the response content type without using HttpServletResponse


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


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 Producible Media Types.

Alternatively, use ResponseEntity, e.g.

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 Using HttpEntity<?>