Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set respond header values in Spring Boot rest service method?

Tags:

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?

like image 959
user2868835 Avatar asked Jul 17 '17 19:07

user2868835


People also ask

How do you set a value in response header?

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.

How do you set a header in a response entity?

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.

How do I add a header to all responses in Spring boot?

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.


1 Answers

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

like image 138
Matias Elorriaga Avatar answered Sep 20 '22 14:09

Matias Elorriaga