springboot-controller的使用詳解
Controller的使用
一、
- @Controller:處理http請求
- @RestController:Spring4之后新加的注解,原來返回json需要@ResponseBody配合@Controller
- @RequestMapping:配置url映射
1.對于控制器層,如果只使用@Controller注解,會報500,即controller必須配合一個模板來使用:
使用spring官方的一個模板:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
在resources下面的templates文件夾下建立index.html:
<h1>hello Spring Boot!</h1>
HelloController:
@Controller @ResponseBody public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = "/hello",method = RequestMethod.GET) public String say(){ // return girlProperties.getCupSize(); return "index"; } }
@RestController相當于@Controller和@ResponseBody組合使用
如果程序需要通過hello和hi都能訪問到,只需在@RequestMapping的value中添加如下:
@RestController public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = {"/hello", "/hi"},method = RequestMethod.GET) public String say(){ return girlProperties.getCupSize(); } }
二、
- @PathVariable:獲取url中的數(shù)據(jù)
- @RequestParam:獲取請求參數(shù)的值
- @GetMapping:組合注解
@PathVariable:
方式一:
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = {"/say/{id}"},method = RequestMethod.GET) public String say(@PathVariable("id") Integer id){ return "id:"+id; // return girlProperties.getCupSize(); } }
結果:
方式二:也可以把id寫在前面:
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = {"/{id}/say"},method = RequestMethod.GET) public String say(@PathVariable("id") Integer id){ return "id:"+id; // return girlProperties.getCupSize(); } }
結果:
方式三:使用傳統(tǒng)方式訪問:
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(@RequestParam("id") Integer myId){ return "id:"+myId; //方法參數(shù)中的Integer id這個id不需要與前面對應 // return girlProperties.getCupSize(); } }
結果:
注解簡寫:@RequestMapping(value = "/say",method = RequestMethod.GET)等價于:@GetMapping(value = "/say")
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; // @RequestMapping(value = "/say",method = RequestMethod.GET) //@GetMapping(value = "/say")//等價于上面的 @PostMapping(value = "/say") public String say(@RequestParam("id") Integer myId){ return "id:"+myId; //方法參數(shù)中的Integer id這個id不需要與前面對應 // return girlProperties.getCupSize(); } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
spring boot RestTemplate 發(fā)送get請求的踩坑及解決
這篇文章主要介紹了spring boot RestTemplate 發(fā)送get請求的踩坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Flutter 通過Clipper實現(xiàn)各種自定義形狀的示例代碼
這篇文章主要介紹了Flutter 通過Clipper實現(xiàn)各種自定義形狀的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12