且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Spring中将RequestHeader转换为自定义对象

更新时间:2022-06-16 21:58:59

基本上,我已经完成了评论中的建议. 我将仅提供简短示例.假设我们有下一个控制器和用户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