您好,登錄后才能下訂單哦!
Controller的使用
一、
1.對(duì)于控制器層,如果只使用@Controller注解,會(huì)報(bào)500,即controller必須配合一個(gè)模板來(lái)使用:
使用spring官方的一個(gè)模板:
<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相當(dāng)于@Controller和@ResponseBody組合使用
如果程序需要通過(guò)hello和hi都能訪問(wèn)到,只需在@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(); } }
結(jié)果:
方式二:也可以把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(); } }
結(jié)果:
方式三:使用傳統(tǒng)方式訪問(wèn):
@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這個(gè)id不需要與前面對(duì)應(yīng) // return girlProperties.getCupSize(); } }
結(jié)果:
注解簡(jiǎn)寫:@RequestMapping(value = "/say",method = RequestMethod.GET)等價(jià)于:@GetMapping(value = "/say")
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; // @RequestMapping(value = "/say",method = RequestMethod.GET) //@GetMapping(value = "/say")//等價(jià)于上面的 @PostMapping(value = "/say") public String say(@RequestParam("id") Integer myId){ return "id:"+myId; //方法參數(shù)中的Integer id這個(gè)id不需要與前面對(duì)應(yīng) // return girlProperties.getCupSize(); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。