本章主要目標完成Spring Boot基礎項目的構建,並且實現一個簡單的Http請求處理,通過這個例子對Spring Boot有一個初步的了解,並體驗其結構簡單、開發快速的特性。
通過SPRING INITIALIZR
工具產生基礎項目
步驟1 : 使用瀏覽器打開: http://start.spring.io
步驟2 : 填寫項目相關信息,選取依賴,然后生成項目。注:本人選擇的是Maven Project,JAVA(1.8),Spring Boot(2.0.0)
步驟3 : 解壓項目,導入Eclipse,大功告成!!
然后需要引入Spring Boot web包,在pom.xml新增
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在主函數包下新創建一個包,包名隨意,創建一個類HelloWorld,如下:
@RestController
public class HelloWorld {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
啟動主程序,打開瀏覽器訪問http://localhost:8080/hello
,可以看到頁面輸出Hello World
在spring boot中引入html模板代碼index.html,文件位於/resources/static目錄下,包括CSS image等如下圖
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> -----hello jasonLin!------ </body> </html>
資源訪問路徑配置 application.properties:
#MVC spring.mvc.view.prefix=/ spring.mvc.view.suffix=.html
上面說到/resources/static靜態資源的默認請求路徑為/ 。假如我的靜態資源位於/resources/static/dist目錄下,但是我不想將請求改為/dist(這里要注意一下html中引用其它資源的相對路徑如果是./xxx 在本地更改真個文件加的路徑引用的資源文件是能夠正常定位,但是在web容器中./xxx需改為/dist/xxx ,這里涉及到web根路徑和本地文件路徑的問題)可以在application.properties加如下配置:
spring.resources.static-locations=classpath:/static/dist/
這樣當我們訪問/ 時實際定位的資源文件位置是/resources/static/dist 這樣就避免了當更改資源文件的位置時需要更改html中的全部引用。