具有空值

时间:2017-10-25 08:55:10

标签: java spring spring-mvc spring-boot

enter image description here使用spring boot开发应用程序。在Resource am中使用路径变量(**@PathVariable**注释)和请求参数(**@RequestParam("name")**注释)。我的代码获取请求参数值而不是路径变量值,我将路径变量值作为null。请任何人建议我解决这个问题。

@RequestMapping(value = "/api/user/{id}", method = RequestMethod.GET)  
public void get(@RequestParam("name")  String name, @PathVariable Integer id); {

        System.out.println("name="+name);
        System.out.println("id="+id)
}

URL:
http://localhost:8080/api/user/2?name=neeru

输出:
名称= neeru
ID =空

我也试过

**@RequestMapping(value = "/api/user/id={id}", method = RequestMethod.GET)** 

URL:
http://localhost:8080/api/user/id=2?name=neeru  但获得相同的id值= null

我添加了一个方法 - 只有@PathVariable

@RequestMapping(path="/api/user/name/{name}", method = RequestMethod.GET)    
   void get( @PathVariable("value=name") String name){

   System.out.println("name="+name)
}

但结果是相同的路径变量值name = null

2 个答案:

答案 0 :(得分:3)

@PathVariable用于提取MystyxMac建议的路径中的变量。如果要提取查询参数,则必须使用@RequestParam

但是你的例子是路径和查询参数的混合。

您不能在网址中使用=,因为这是保留字符:https://www.w3.org/Addressing/URL/url-spec.txt

所以要么使用

/api/user/{id} with @PathVariable 

/api/user?id={id} with @RequestParam

答案 1 :(得分:3)

  1. @PathVariable 是从uri获取一些占位符
  2. @RequestParam 是获取参数
  3. 像这样更改您的终端

    http://localhost:8080/api/user/2/users?name=neeru

    `

    @RequestMapping(value = "api/user/{id}/users", method = RequestMethod.GET)  
    public void get(@RequestParam("name")  String name, @PathVariable("id") Integer id); {
            System.out.println("name="+name);
            System.out.println("id="+id)
    }
    

    `

    输出:

    name = neeru

    id = 2

    enter image description here

    enter image description here

    enter image description here