394

@RequestParam处理特殊字符和处理特殊字符有什么区别@PathVariable

+@RequestParam作为空间接受。

在 的情况下@PathVariable+被接受为+

4

8 回答 8

542

If the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:

@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
            @PathVariable("userId") int user,
            @RequestParam(value = "date", required = false) Date dateOrNull) {
  ...
}

Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID "invoices"?

于 2012-12-05T07:47:16.083 回答
124

@RequestParam注解用于访问请求中的查询参数值。查看以下请求 URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

在上述 URL 请求中,可以访问 param1 和 param2 的值,如下所示:

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}

以下是@RequestParam 注解支持的参数列表:

  • defaultValue – 如果请求没有该值或为空,这是作为回退机制的默认值。
  • name - 要绑定的参数的名称
  • required - 参数是否是必需的。如果为真,则未能发送该参数将失败。
  • value – 这是 name 属性的别名

@PathVariable

@PathVariable标识用于传入请求的 URI 中的模式让我们看看下面的请求 URL:

http://localhost:8080/springmvc/hello/101?param1=10¶m2=20

上面的 URL 请求可以写在你的 Spring MVC 中,如下所示:

@RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

@PathVariable注解只有一个属性值,用于绑定请求 URI 模板。允许在单个方法中使用多个@PathVariable注解。但是,请确保不超过一种方法具有相同的模式。

还有一个更有趣的注释: @MatrixVariable

http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,+10.40,+3.91;AZN=236.00,+103.00,+3.29;SBRY=375.50,+7.60,+2.07

以及它的控制器方法

 @RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
  public String showPortfolioValues(@MatrixVariable Map<String, List<String>> matrixVars, Model model) {

    logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });

    List<List<String>> outlist = map2List(matrixVars);
    model.addAttribute("stocks", outlist);

    return "stocks";
  }

但您必须启用:

<mvc:annotation-driven enableMatrixVariables="true" >
于 2016-10-14T10:00:59.147 回答
32

@RequestParam 用于查询参数(静态值),例如:http://localhost:8080/calculation/pow?base=2&ext=4

@PathVariable 用于动态值,例如:http://localhost:8080/calculation/sqrt/8

@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
    int pow = (int) Math.pow(base1, ext1);
    return pow;
}

@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
    double sqrtnum=Math.sqrt(num1);
    return sqrtnum;
}
于 2018-09-06T02:18:00.323 回答
26

1)@RequestParam用于提取查询参数

http://localhost:3000/api/group/test?id=4

@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

while@PathVariable用于直接从 URI 中提取数据:

http://localhost:3000/api/group/test/4

@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

2)@RequestParam在数据主要在查询参数中传递的传统 Web 应用程序中更有用,而@PathVariable更适合 URL 包含值的 RESTful Web 服务。

3)如果查询参数不存在或为空,则@RequestParam注释可以通过使用属性指定默认值defaultValue,前提是所需的属性是false

@RestController
@RequestMapping("/home")
public class IndexController {

    @RequestMapping(value = "/name")
    String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
        return "Required element of request param";
    }

}
于 2019-11-28T11:59:07.070 回答
1

可能是 application/x-www-form-urlencoded midia 类型将空格转换为+ ,并且接收者将通过将+转换为空格来解码数据。检查 url 以获取更多信息。http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1

于 2014-09-26T02:13:00.997 回答
1

两个注释的行为方式完全相同。

只有 2 个特殊字符 '!' 和 '@' 被 @PathVariable 和 @RequestParam 注释所接受。

为了检查并确认行为,我创建了一个仅包含 1 个控制器的 spring boot 应用程序。

 @RestController 
public class Controller 
{
    @GetMapping("/pvar/{pdata}")
    public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
    {
        return pathdata;
    }

    @GetMapping("/rpvar")
    public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
    {
        return paramdata;
    }
}

点击以下请求我得到了相同的响应:

  1. localhost:7000/pvar/!@#$%^&*()_+-=[]{}|;':",./<>?
  2. localhost:7000/rpvar?param=!@#$%^&*()_+-=[]{}|;':",./<>?

!@ 在两个请求中都作为响应收到

于 2019-12-27T15:18:24.533 回答
1
@PathVariable - must be placed in the endpoint uri and access the query parameter value from the request
@RequestParam - must be passed as method parameter (optional based on the required property)
 http://localhost:8080/employee/call/7865467

 @RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
 public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = false) String callStatus) {

    }

http://localhost:8080/app/call/7865467?status=Cancelled

@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = true) String callStatus) {

}
于 2016-12-20T17:14:24.083 回答
0

@RequestParam:我们可以说它是像键值对一样的查询参数@PathVariable:-它来自URI

于 2021-11-27T12:04:17.970 回答