注解
@PathVariable
获取URL中的数据,如:localhost:8080/demo/hello/5 OR localhost:8080/demo/5/hello
注解中的id_等同于RequestMapping_Value中的名称_不需要和参数名称对应
exp:
@RequestMapping(value = "/hello/{id}", method = RequestMethod.GET) public String say(@PathVariable("id") Integer id){ return "id:" + id; }
也可以这样:
@RequestMapping(value = "/{id}/hello", method = RequestMethod.GET) public String say(@PathVariable("id") Integer id){ return "id:" + id; }
@RequestParam
获取请求参数的值
exp:访问_localhost:8080/demo/hello?id=5
这里@RequestParam注解中的id_等同于URL中问好后拼接的参数名称_然后赋值给注解后面的参数myId
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String say(@RequestParam("id") Integer myId){ return myid.toString(); }还有几个设置的方法,举例说明
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String say( @RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){ return myid.toString(); }value等同根据URL中哪个键名取值
required取值true:不可为空_false:可以为空_也就是必要不必要
defaultValue即为空时的默认值
组合注解
@GetMapping("/")等同于
@RequesteMapping(value = "/", method = RequestMethod.GET)