Newbie question... I'm building my first Spring Boot restful service. My restful service design requires some data to be returned in the response header.
How do I set response header values inside my controller class method?
Setting Response Headers from Servlets The most general way to specify headers is to use the setHeader method of HttpServletResponse. This method takes two strings: the header name and the header value. As with setting status codes, you must specify headers before returning the actual document.
Method SummaryBuild the response entity with no body. Set the caching directives for the resource, as specified by the HTTP 1.1 Cache-Control header. Set the entity tag of the body, as specified by the ETag header. Add the given, single header value under the given name.
To set the custom header to each response, use addHeader() method of the HttpServletResponse interface. That's all about setting a header to all responses in Spring Boot.
From the Spring Documentation:
@RequestMapping("/handle") public ResponseEntity<String> handle() { URI location = ...; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(location); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED); }
Source: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
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