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<?>
Just pass it as an argument, e.g.
@RequestMapping( value="/test", method = RequestMethod.GET )
public void test( HttpServletResponse response ) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With