如何在Spring中将RequestHeader转换为自定义对象 [英] How to convert RequestHeader to custom object in Spring
问题描述
我的控制器中有方法:
@RequestMapping(method = RequestMethod.POST)
public CustomObject createCustomObject(final @RequestHeader("userId") Long userId) {
...
}
我可以编写一些自定义转换器或类似的东西来将此RequestHeader userId参数转换为User对象,这样我的方法将是:
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) {
...
}
是否可以使用spring-mvc?
Is it possible to do with spring-mvc?
推荐答案
基本上,我已经完成了评论中的建议. 我将仅提供简短示例.假设我们有下一个控制器和用户POJO:
Basically I finished with the suggestion from the comments. I will provide just short example. Let say we have next controller and User POJO:
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 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;
}
}
测试示例:curl --header "userId: 123" localhost:8080/user
结果将是:Hey, User{id='123', firstName='First', lastName='Last'}
按照我使用下一个版本的方式:spring-boot:2.0.3 and spring-web:5.0.7
By the way I've used next versions: spring-boot:2.0.3 and spring-web:5.0.7
这篇关于如何在Spring中将RequestHeader转换为自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!