Spring Boot 3---Controller使用案例
阿新 • • 發佈:2019-01-30
1、Spring Boot的Controller使用
(1)@Controller ---處理http請求
(2)@RestController---Spring4之後新加的註解,原來返回json需要 @ResponseBody配合@Controller
(3)RequestMapping配置url對映
(4)PathVariable獲取url中的資料
(5)RequestParam獲取請求引數的值
(6)GetMapping 組合註解
2、案例GirlProperties.java(在src/main/java/com.example包中)
package com.example; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="girl") public class GirlProperties { private String cupSize; private Integer age; public String getCupSize() { return cupSize; } public GirlProperties setCupSize(String cupSize) { this.cupSize = cupSize; return this; } }
application.yml(在src/main/resources包下)
server:
port: 8081
girl:
cupSize: B
age: 18
GirlController.java
package com.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @ResponseBody public class GirlController { @Autowired private GirlProperties girlProperties; @RequestMapping(value="/hello") public String say() { return girlProperties.getCupSize(); } }
GirlApplication.java
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication//開啟自動配置 public class GirlApplication { //main方法作用:作為專案啟動的入口 public static void main(String[] args) { SpringApplication.run(GirlApplication.class, args); } }
執行GirlApplication.java結果: