微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

背景

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

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

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

    @RequestMapping(path={ "/{id}"},method=RequestMethod.PUT)
    public ResponseEntityaration...
    }
}

如您所见,所有这三个方法都为头@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 ResponseEntityaration...
    }
    // rest of your class methods,without @RequestHeader parameters

}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐