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();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。