spring boot控制器的使用
一:
1.注解
2.control注解
@Controller public class HelloController { @Value("${cupSize}") private String cupSize; @Value("${age}") private Integer age; @Value("${content}") private String content; @Autowired private GirlProperties girlProperties; @RequestMapping(value = "/hello",method = RequestMethod.GET) public String say(){ // return girlProperties.getCupSize()+" "+girlProperties; return "index"; } }
<!--模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <optional>true</optional> </dependency>
@Controller 与@ResponseBody等价于@RestController
3.hello与hi都可以访问多个浏览器地址映射到一个方法()
@RequestMapping(value = {"/hello","/hi"}
@RestController public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET) public String say(){ return girlProperties.getCupSize()+" "+girlProperties; } }
4.RequestMapping的类上使用的方式
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(){ return girlProperties.getCupSize()+" "+girlProperties; } }
http://127.0.0.1:8081/hello/say
二:
1.注解
2.PathVariable的使用
http://127.0.0.1:8081/hello/say?id=10这个针对的是?=这种url
3.RequestParam的使用
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(@RequestParam("id") Integer id){ return Integer.toString(id); } }
4.设置默认值
@RequestParam(value = "id",required = false,defaultValue = "0")Integer id
@RestController @RequestMapping("/hello") public class HelloController { @Autowired private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(@RequestParam(value = "id",required = false,defaultValue = "0")Integer id){ return Integer.toString(id); } }
http://127.0.0.1:8081/hello/say?id=10
http://127.0.0.1:8081/hello/say?id
http://127.0.0.1:8081/hello/say
这三种路径映射的url都不会报错
5.GetMapping的使用
@RequestMapping(value={"/say"},method = RequestMethod.GET)
等价于@GetMapping(value = "/say")