【问题标题】:Use @RequestParam or @PathVariable?使用@RequestParam 和@PathVariable?
【发布时间】:2014-08-16 02:50:22
【问题描述】:

我正在使用 spring 框架开发一个 REST WebApp,现在我想知道接收数据的最佳实践。最好使用@RequestParam@PathVariable 检索它们?显然我有兴趣接收useridusername 之类的简单数据。 举个例子:

@RequestMapping(value = "/getdata", method = RequestMethod.GET)
public String GetData(@RequestParam(value = "memberId", required = true) Integer memberId){
  //return data for user with Id = memberid;
}

@RequestMapping(value = "/getdata/{memberid}", method = RequestMethod.GET)
public String GetData(@pathvariable int memberid){
  //return data for user with Id = memberid;
}

我对 REST Web 服务感兴趣

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

创建一个模型映射并将这些参数名称/值对添加到其中:

@RequestMapping(value="/student/{username}/", method=RequestMethod.GET)

public String adminStudent(@PathVariable String username, @RequestParam String studentid, Model model)
{
    model.put("username", username);
    model.put("studentid", studentid);
    return "student";
}

【讨论】:

    【解决方案2】:

    这取决于你想在 Controller 中接收什么样的数据。

    您可以使用@PathVariable 从 uri 中获取信息。

    网址:

    exampleUrl/Application/example/someData
    

    控制器:

    @RequestMapping(value="example/{someData}", method = RequestMethod.GET)
    public String Controller(@PathVariable("someData") String someData){        
      ...
    }
    

    你可以使用@RequestParam从url获取参数。

    网址:

    exampleUrl/Application/example/someData?parameter1=hello
    

    控制器:

    @RequestMapping(value = "example/someData", method = RequestMethod.GET)
    public String Controller(@RequestParam(value = "parameter1", required = false) String parameter1){        
              ...
            }
    

    所以没有“更好”的方式,这取决于你想如何处理你的请求以及你需要什么样的信息。

    【讨论】:

    • 但如果我的信息是相同的,就像在示例中一样......我认为有一个约定或最佳实践可以遵循......
    【解决方案3】:

    @PathVarible 用于 RESTful Web 服务。了解什么是 REST 。并且方法名应该以小写开头。

    【讨论】:

    • 是的,我忘了说它是用于 RESTful Web 服务的
    【解决方案4】:

    Rest 约定是使用 uri 变量:

    get http://stackoverflow.com/users/3630157
    

    【讨论】:

    • 这就是我要找的,我忘了说我在谈论rest web services
    猜你喜欢
    • 2015-08-28
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多