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

时间:2020-06-14 17:06:35

标签: spring spring-boot spring-mvc spring-restcontroller

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

我希望将请求正文作为控制器的属性,以便其他私有方法可以访问它。

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....
    }

1 个答案:

答案 0 :(得分:0)

默认情况下,控制器是单例作用域的Bean(每个容器初始化创建一次)。将请求正文(在每个​​请求中都会更改)分配给一次创建且可以在任何地方使用的事物,可能会导致严重的麻烦。如果您只是想通过使用私有方法在控制器中应用一些逻辑,则可以像这样将主体作为参数传递给该方法。

@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
}