【问题标题】:Can Spring be directed to take a parameter from either the body or the URL?是否可以指示 Spring 从正文或 URL 中获取参数?
【发布时间】:2018-03-04 10:39:51
【问题描述】:

Spring MVC 方法的参数可以声明为 RequestBody 或 RequestParam。有没有办法说“从正文(如果提供)或 URL 参数(如果不提供)中获取此值”?也就是说,让用户可以灵活地以任何方便的方式传递它。

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    您可以在代码中创建这两个变量并检查它们是否为 null 像这样:

    @RequestMapping(value = GET_SOMETHING, params = {"page"}, method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject getPromoByBusinessId(
            @PathVariable("businessId") String businessId, @RequestParam("page") int page,
            @RequestParam("valid") Boolean valid,
            @RequestParam("q") String promoName) throws Exception {}
    

    然后使用一系列 if-else 来响应请求。 我写它是为了处理三个参数中的任何一个为空或空,对所有不同的场景做出反应。

    要使它们成为可选,请参阅: Spring Web MVC: Use same request mapping for request parameter and path variable

    【讨论】:

      【解决方案2】:

      HttpServletRequest 接口应该有助于解决这个问题

      @RequestMapping(value="/getInfo",method=RequestMethod.POST)
      @ResponseBody
      public String getInfo(HttpServletRequest request) {
          String name=request.getParameter("name");
          return name;
      
      }
      

      现在,根据来自正文或参数的请求数据,将获取值

      C:\Users\sushil
      λ curl http://localhost:8080/getInfo?name=sushil-testing-parameter
      sushil-testing-parameter
      C:\Users\sushil
      λ curl -d "name=sushil-testing-requestbody" http://localhost:8080/getInfo
      sushil-testing-requestbody
      C:\Users\sushil
      λ
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        • 1970-01-01
        • 1970-01-01
        • 2012-04-19
        • 2021-09-03
        相关资源
        最近更新 更多