Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting 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?

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?

like image 768
a Learner Avatar asked Jan 19 '12 14:01

a Learner


2 Answers

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

like image 113
skaffman Avatar answered Oct 02 '22 13:10

skaffman


Just pass it as an argument, e.g.

@RequestMapping( value="/test", method = RequestMethod.GET )
public void test( HttpServletResponse response ) { ... }
like image 24
xpapad Avatar answered Oct 02 '22 12:10

xpapad