針對controller 中 如何使用注解進行解析
@RestController
- 返回數據類型為 Json 字符串,特別適合我們給其他系統提供接口時使用。
@RequestMapping
(1) 不同前綴訪問同一個方法,此時訪問hello和hi 都可以訪問到say()這個方法
@RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)
public String say(){
return girlProperties.getName();
}
(2)給類一個RequestMapping, 訪問時就是:http://localhost:8099/hello/say
@RestController
@RequestMapping("/hello")
public class HelloController {
@Resource
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(){
return girlProperties.getName();
}
}
@PathVariable:獲取url中的數據
@RestController
@RequestMapping("/hello")
public class HelloController {
@Resource
private GirlProperties girlProperties;
@RequestMapping(value = "/say/{id}",method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id){
return "id :"+id;
}
}
訪問http://localhost:8099/hello/say/100, 結果如下
id :100
@RequestParam :獲取請求參數的值
(1) 正常請求
@RestController
@RequestMapping("/hello")
public class HelloController {
@Resource
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam("id") Integer id){
return "id :"+id;
}
}
訪問 http://localhost:8099/hello/say?id=111 結果如下
id :111
(2)設置參數非必須的,並且設置上默認值
@RestController
@RequestMapping("/hello")
public class HelloController {
@Resource
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id){
return "id :"+id;
}
}
訪問http://localhost:8099/hello/say 結果如下
id :0
@GetMapping ,當然也有對應的Post等請求的簡化寫法
- 這里對應的就是下面這句代碼
@GetMapping("/say")
//等同於下面代碼
@RequestMapping(value = "/say",method = RequestMethod.GET)