您好,登錄后才能下訂單哦!
Controller的使用
一、
1.對于控制器層,如果只使用@Controller注解,會報500,即controller必須配合一個模板來使用:
使用spring官方的一個模板:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
在resources下面的templates文件夾下建立index.html:
<h2>hello Spring Boot!</h2>
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:
方式一:
@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(); } }
結果:
方式三:使用傳統方式訪問:
@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; //方法參數中的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; //方法參數中的Integer id這個id不需要與前面對應 // return girlProperties.getCupSize(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。