Reputation: 5042
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?
Upvotes: 7
Views: 15492
Reputation: 403581
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<?>
Upvotes: 12
Reputation: 1028
I think the best way to handle this is to use a specific View-Implementation, since here to response-rendering should take place.
Upvotes: 0
Reputation: 4456
Just pass it as an argument, e.g.
@RequestMapping( value="/test", method = RequestMethod.GET )
public void test( HttpServletResponse response ) { ... }
Upvotes: 2