【问题标题】:Spring POST controller request body as controller variableSpring POST 控制器请求主体作为控制器变量
【发布时间】:2020-06-14 17:06:35
【问题描述】:

通常,我们将请求主体作为控制器方法的参数。 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....
    }

【问题讨论】:

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


    【解决方案1】:

    默认情况下,控制器是单例范围的 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多