I have method in my controller:
@RequestMapping(method = RequestMethod.POST)
public CustomObject createCustomObject(final @RequestHeader("userId") Long userId) {
...
}
Can I write some custom converter or something like that to convert this RequestHeader userId param to User object so my method will be:
@RequestMapping(method = RequestMethod.POST)
public CustomObject createCustomObject(final User user) {
...
}
Is it possible to do with spring-mvc?
A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.
Spring MVC provides one more annotation, @ModelAttributes , for binding data to the Command object. It is another way to bind the data and to customize the data binding. This annotation allows you to control the creation of the Command object.
Data binding is useful for allowing user input to be dynamically bound to the domain model of an application (or whatever objects you use to process user input). Spring provides the so-called DataBinder to do exactly that.
To help you with that task, Spring provides a convenient template class called RestTemplate . RestTemplate makes interacting with most RESTful services a one-line incantation. And it can even bind that data to custom domain types.
Basically I implemented it with the suggestion from the comments. Below is an example:
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
@RestController
public class SimpleController {
@GetMapping("/user")
public String greeting(@RequestHeader(name = "userId") User user) {
return "Hey, " + user.toString();
}
}
public class User {
private String id;
private String firstName;
private String lastName;
...
}
And then we'll create a converter:
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class UserFromHeaderConverter implements Converter<String, User> {
@Override
public User convert(final String userId) {
// fetch user from the database etc.
final User user = new User();
user.setId(userId);
user.setFirstName("First");
user.setLastName("Last");
return user;
}
}
To test it, please execute: curl --header "userId: 123" localhost:8080/user
Result would be: Hey, User{id='123', firstName='First', lastName='Last'}
Versions:
spring-boot:2.0.3
spring-web:5.0.7
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