java – 如何装饰所有请求从头部获取值并将其添加到body参数?

前端之家收集整理的这篇文章主要介绍了java – 如何装饰所有请求从头部获取值并将其添加到body参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

背景

我正在使用Spring MVC创建RESTful服务.目前,我有一个控制器的结构如下:

@RestController
@RequestMapping(path = "myEntity",produces="application/json; charset=UTF-8")
public class MyEntityController {

    @RequestMapping(path={ "","/"},method=RequestMethod.POST)
    public ResponseEntity

如您所见,所有这三个方法都为头@RequestHeader(“X-Client-Name”)字符串clientName接收相同的参数,并在每个方法上以相同的方式应用它:myEntity.setClientName(clientName).我将创建类似的控制器,对于POST,PUT和PATCH操作将包含几乎相同的代码,但对于其他实体.目前,大多数实体都是为了支持这个领域而设计的超级类:

public class Entity {
    protected String clientName;
    //getters and setters ...
}
public class MyEntity extends Entity {
    //...
}

此外,我使用拦截器来验证是否为请求设置了标头.

如何通过控制器类和方法避免重复相同的代码?有没有一个干净的方法来实现它?或者我应该声明变量并在任何地方重复这些行?

西班牙社区也提出了这个问题.这是the link.

最佳答案
我的建议是将标头值存储在Spring拦截器或过滤器内的请求范围bean中.然后你可以在任何你想要的地方自动装配这个bean – 服务或控制器并使用存储的客户端名称值.

代码示例:

public class ClientRequestInterceptor extends HandlerInterceptorAdapter {

    private Entity clientEntity;

    public ClientRequestInterceptor(Entity clientEntity) {
        this.clientEntity = clientEntity;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {
        String clientName = request.getHeader("X-Client-Name");
        clientEntity.setClientName(clientName);
        return true;
    }
}

在您的配置文件中:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(clientRequestInterceptor());
    }

    @Bean(name="clientEntity")
    @Scope(value = "request",proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Entity clientEntity() {
        return new Entity();
    }

    @Bean
    public ClientRequestInterceptor clientRequestInterceptor() {
        return new ClientRequestInterceptor(clientEntity());
    }

}

然后,假设我们必须在我们的控制器中使用这个bean:

@RestController
@RequestMapping(path = "myEntity",produces="application/json; charset=UTF-8")
public class MyEntityController {

    @Autowired
    private Entity clientEntity; // here you have the filled bean

    @RequestMapping(path={ "",method=RequestMethod.POST)
    public ResponseEntity

我没有编译这段代码,所以如果我犯了一些错误,请纠正我.

原文链接:https://www.f2er.com/spring/432458.html

猜你在找的Spring相关文章