1. String Boot的使用
1.1 創建專案



1.2 匯入依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.7.RELEASE</version> </dependency> </dependencies>

1.3 制作簡單的網站
在src/main/java包下,包結構:

創建FirstApp.java檔案:
package com.xhh; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FirstApp { }
查看@SpringBootApplication,可以看到這個注解是多個注解的集合,
然后撰寫main方法:
package com.xhh; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FirstApp { public static void main(String[] args) { SpringApplication.run(FirstApp.class, args); } }
此時,我們可以右鍵直接運行專案了,

啟動的是tomcat的默認埠8080,
再創建一個MyController.java:
package com.xhh; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MyController { //該注解將HTTP Get 映射到 特定的處理方法上, //即可以使用@GetMapping(value = https://www.cnblogs.com/liuhui0308/p/“/hello”)來代替@RequestMapping(value=”/hello”,method= RequestMethod.GET), //組合注解,是@RequestMapping(method = RequestMethod.GET)的縮寫 @GetMapping("/hello") //讓controller回傳資料能夠在頁面上顯示,實作回顯效果 @ResponseBody public String hello() { return "Hello World"; } }
再啟動專案,在網頁中輸入http://localhost:8080/hello:

然后來玩玩回傳物件:
先創建物體類Person:
package com.xhh; public class Person { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
再創建MyRestController.java:
package com.xhh; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class MyRestController { //produces = MediaType.APPLICATION_JSON_VALUE 將回傳的資料轉換成json格式 @RequestMapping(value = "https://www.cnblogs.com/person/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) //@PathVariable 獲取url中的資料 public Person getPerson(@PathVariable Integer id) { Person p = new Person(); p.setId(id); p.setName("angus"); p.setAge(30); return p; } }
運行程式:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/192821.html
標籤:Java
