- 处理URL中的参数的注解@ PathVaribale / @ RequestParam
其中,各注解的作用为:
@PathVaribale获取url中的数据
url只有一个参数时:localhost/hello/11
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}",method= RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id){
return "id:"+id;
}
url有多个参数时:hocalhost/hello/12/lee
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id, @PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}
@RequestParam获取请求参数的值
url只有一个参数时:localhost/hello?id=11
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer id){
return "id:"+id;
}
}
id使用默认值
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
//required=false 表示url中可以不穿入id参数,此时就使用默认参数
public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
return "id:"+id;
}
}
url有多个参数时:hocalhost/hello?id=11&name=lee
/**
* Created by wuranghao on 2017/4/7.
*/
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){
return "id:"+id+ " name:"+name;
}
}