@RequestParam vs @PathVariable

use*_*181 324 java spring spring-mvc

是什么区别@RequestParam@PathVariable同时处理的特殊字符?

+@RequestParam空间接受了.

在这种情况下@PathVariable,+被接受为+.

Ral*_*lph 473

如果URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013在2013年12月5日获得用户1234的发票,则控制器方法如下所示:

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

此外,请求参数可以是可选的,从Spring 4.3.3开始,路径变量也是可选的.请注意:这可能会更改URL路径层次结构并引入请求映射冲突.例如,是否会/user/invoices为用户提供发票null或有关ID为"发票"的用户的详细信息?

  • `@PathVariable`可以在任何RequestMethod中使用 (10认同)
  • 这个def需要一个复选标记. (2认同)
  • @Ralph Correct,这适用于Java 8之前的调试.从Java 8开始,它也无需调试,而是使用"-parameters":http://docs.spring.io/spring/docs/current/spring-framework-reference/ html/mvc.html#mvc-ann-requestmapping-uri-templates https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html (2认同)
  • @ user3705478:`@ PathParam`是一个javax.ws.rs注释.https://docs.oracle.com/javaee/7/api/javax/ws/rs/PathParam.html (2认同)

Xel*_*ian 102

@RequestParam注释用于从请求中访问查询参数值.查看以下请求URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20
Run Code Online (Sandbox Code Playgroud)

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

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}
Run Code Online (Sandbox Code Playgroud)

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

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

@PathVariable

@ PathVariable标识在URI中用于传入请求的图案.我们来看看下面的请求网址:

HTTP://本地主机:8080 /用SpringMVC /你好/ 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){
.......
}
Run Code Online (Sandbox Code Playgroud)

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

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

HTTP://本地主机:8080/spring_3_2/matrixvars /股票; BT.A = 276.70,+ 10.40,+ 3.91; AZN = 236.00,103.00 +,+ 3.29; SBRY = 375.50,+ 7.60,+ 2.07

以及它的Controller方法

 @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";
  }
Run Code Online (Sandbox Code Playgroud)

但你必须启用:

<mvc:annotation-driven enableMatrixVariables="true" >
Run Code Online (Sandbox Code Playgroud)


alo*_*lok 24

@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;
}
Run Code Online (Sandbox Code Playgroud)


And*_*riy 22

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);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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";
    }

}
Run Code Online (Sandbox Code Playgroud)