spring boot 簡單功能的測試使用
阿新 • • 發佈:2018-11-15
接下來繼續進行功能實現,建立一個 Controller ,加上註解 @RestController 如果新增後沒有出現的話,需要在 pom 檔案中引入如下依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@RestController @RequestMapping(value = "hello") public class SpringTestController { @RequestMapping(value = "hcg") public String helloHcg(){ return "hello hcg"; } }
其中 RequestMapping 對應的路徑前也可以加上 “ / ” 如
@RequestMapping(value = "/hcg")
本專案我沒有對其進行配置埠號,但在啟動日誌中可以發現 Tomcat 給出了預設的埠
瀏覽器訪問,正確響應
我在application.properties 設定埠後,重新啟動測試
構建 User 類,並寫出對應的 Controller ,注意 在此版中使用的是 @RestController = @Controller + @ResponseBody
@Controller @RequestMapping(value = "/user") public class UserController { @RequestMapping(value = "/get") @ResponseBody private User getUser(){ User u = new User(); u.setName("spring boot"); u.setAge(12); u.setBirthday(new Date()); u.setContent("we are familys"); return u; } }
或者
@RestController
@RequestMapping(value = "/user")
public class UserController {
@RequestMapping(value = "/get")
private User getUser(){
User u = new User();
u.setName("spring boot");
u.setAge(12);
u.setBirthday(new Date());
u.setContent("we are familys");
return u;
}
}
返回結果
{"name":"spring boot","age":12,"birthday":"2018-09-14T09:12:07.830+0000","content":"we are familys"}