声明

  本文转载自https://www.cnblogs.com/mkl34367803/p/10836959.html

正文

  最近学习springMVC,学到@PathVariable时,发现@PathVariable有个required属性,尝试将其设置为false,但请求/helloWorld/user时报404。

  刚开始我的代码是这样的:

@RequestMapping(value={"/helloWorld/user/{id}/{name}"})
public User getUser(@PathVariable(value="id",required=false) Integer id,@PathVariable(value="name",required=false) String name ){
    System.out.println("--------------:"+id+","+name);
    User user=new User(id,name);
    return user;
}

  改成下面的样子,请求/helloWorld/user的时候,就不会报404了。

/**
 * http://localhost:8080/helloWorld/user/1/zhangsan
 * http://localhost:8080/helloWorld/user/1
 * http://localhost:8080/helloWorld/user
 * @param id
 * @param name
 * @return
 */
@RequestMapping(value={"/helloWorld//user/{id}/{name}","/helloWorld/user/{id}","/helloWorld//user"})
public User getUser(@PathVariable(value="id",required=false) Integer id,@PathVariable(value="name",required=false) String name ){
    System.out.println("--------------:"+id+","+name);
    User user=new User(id,name);
    return user;
}

  原因就是地址是不一样的,需要配置多个地址映射。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐