我的PathVariables无效

时间:2018-08-29 07:00:45

标签: java spring rest spring-boot

你好,我想用Spring Rest编写一个Get方法,但是下面的代码不起作用;

@RequestMapping(value = "userRight/hasRightForOperation", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> hasRightForOperation(@PathVariable(value = "loginName") String loginName,
            @PathVariable(value = "vendorId") String vendorId,
            @PathVariable(value = "accessRightCode") String accessRightCode) {
        return new ResponseEntity<>(hasRightForOperation(loginName, vendorId, accessRightCode), HttpStatus.OK);

提前谢谢

2 个答案:

答案 0 :(得分:1)

@RequestMapping(value = "userRight/hasRightForOperation", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> hasRightForOperation(@PathVariable(value = "loginName") String loginName,
        @PathVariable(value = "vendorId") String vendorId,
        @PathVariable(value = "accessRightCode") String accessRightCode) {
    return new ResponseEntity<>(hasRightForOperation(loginName, vendorId, accessRightCode), HttpStatus.OK);

您正在使用@PathVariable,但是您的网址映射没有参数。 您可以像

一样进行修复
@RequestMapping(value = "userRight/hasRightForOperation/{loginName}/{vendorId}/{accessRightCode}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> hasRightForOperation(@PathVariable(value = "loginName") String loginName,
        @PathVariable(value = "vendorId") String vendorId,
        @PathVariable(value = "accessRightCode") String accessRightCode) {
    return new ResponseEntity<>(hasRightForOperation(loginName, vendorId, accessRightCode), HttpStatus.OK);

您可以更改url映射参数的顺序。因此,如果您不想进行网址映射,则可以使用@RequestParam标签获取参数。

@GetMapping(value = "userRight/hasRightForOperation", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> hasRightForOperation(@RequestParam("loginName") String loginName,
                                              @RequestParam("vendorId") String vendorId,
                                              @RequestParam("accessRightCode") String accessRightCode) {
    return new ResponseEntity<>(hasRightForOperation(loginName, vendorId, accessRightCode), HttpStatus.OK);
}

答案 1 :(得分:0)

您必须在URL中接收路径变量,以便添加如下所示的所有参数。

更改

@RequestMapping(value = "userRight/hasRightForOperation", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)

@RequestMapping(value = "userRight/hasRightForOperation/{loginName}/{vendorId}/{accessRightCode}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)

我建议您为此使用@RequestParam

请参见:@RequestParam vs @PathVariable