下面将给出详细例子: 请求路径 : http://www.test.com/user/031267/view?username=zhangsan&age=20 请求URL : http://www.test.com/user/031267/view
@RequestMapping(value = "/user/{userid}/view") //占位符 userid
public String view ( @PathVariable("userid") String userid){ //@PathVariable 中指定 userid
System.out.println("userid= "+userid); //此处可以获取:userid= 031267
return SUCCESS;
}
@RequestMapping(value = "/user/query")
public String query(@RequestParam(value="username") String username) {
System.out.println("username = " + username); //此处打印:username = zhangsan
return SUCCESS;
}
通过@RequestParam 获取 不同请求对应的值:
…/query?username=zhangsan 获取 username 等于 zhangsan …/query?username= 获取 username=="" …/query 获取 username==null @RequestParam 默认必传的,不能为null
如上面例子,请求路径是 http://www.test.com/user/query?age=20 ,程序一定会报错的, 如果username不传时, 就是null ,而 @RequestParam 默认是必传的。
解决方法:
请求路径 : http://www.test.com/user/031267/view?username=zhangsan&age=20
@RequestMapping(value = "/user/{userid}/view")
public String query(@PathVariable("userid") String userid,@RequestParam(value="username") String username ) {
System.out.println("userid= "+userid); //此处可以获取:userid= 031267
System.out.println("username = " + username); //此处打印:username = zhangsan
return SUCCESS;
}