Spring POST控制器请求体作为控制器变量

问题描述 投票:0回答:1

通常,我们会得到请求体作为控制器方法的参数。Spring将body绑定到变量的类型上。

我希望将请求体作为控制器的一个属性,这样其他私有方法就可以访问它。

public class UserController {

    private String body;    // Request body should automatically bind to this String.  

    private HttpServletRequest request;

    @Autowired
    public UserController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> create(@RequestBody String body) {
        // I know I can do like: this.body = body.
        // But don't want to do that.
    }

    private someMethod() {
        // Give me access of request body please....
    }
spring spring-boot spring-mvc spring-restcontroller
1个回答
0
投票

控制器默认是单人作用域Bean(每次容器初始化时创建一次)。将请求体(在每次请求中都会改变)分配给只创建一次的东西,并且可以在任何地方使用,这可能会给你带来严重的麻烦。如果你只是想通过使用私有方法在控制器中应用一些逻辑,你可以像这样将body作为参数传递给该方法。

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> create(@RequestBody String body) {
    someMethod(body);
}

private void someMethod(String body) {
    // voila! you have the request body here
}
© www.soinside.com 2019 - 2024. All rights reserved.