最近試用了一下Spring Boot,發現用它建立WEB應用簡直好爽啊,記錄一下。css
首先用Eclipse建一個maven工程,建立時選中「Create a simple proejct (skip archetype selection)」,建個簡單工程就行了。html
而後編輯pom.xml,引入相關的包,完整文件以下:java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.test</groupId> <artifactId>appboot</artifactId> <version>0.0.1</version> <name>appboot</name> <dependencies> <!-- 引入WEB開發支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.4.1.RELEASE</version> </dependency> <!-- 引入FreeMarker支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> <version>1.4.1.RELEASE</version> </dependency> <!-- 引入重編譯自動加載支持,這樣在Eclipse中調試時有變動會自動從新加載 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <version>1.4.1.RELEASE</version> <optional>true</optional> </dependency> <!-- 引入fastjson,用於替換默認的json包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <finalName>appboot</finalName> <plugins> <!-- 引入maven打包支持 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.4.1.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
添加應用程序入口文件Application.java,以下:jquery
package org.me; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.HttpMessageConverter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; @SpringBootApplication public class Application { /** * 用fastjson做爲默認的json編碼器 * @return */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue); fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } /** * 應用程序入口 * @param args */ public static void main(String[] args) { //用SpringApplication啓動 SpringApplication.run(Application.class, args); } }
若是隻用默認的json編碼器,那麼只有main方法就夠了。而後來寫一個控制器,好比叫HomeController:
web
package org.me; import java.util.Date; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * 定義一個控制器 */ @Controller public class HomeController { /** * 定義一個login方法,映射到/login上,返回視圖爲home/login.ftl */ @RequestMapping("/login") public String login(Map<String, Object> model) { model.put("time", new Date()); model.put("message", "Hello, Spring Boot"); return "home/login"; } /** * 定義一個Json的調用 */ @RequestMapping(value = "/checkLogin", method = RequestMethod.POST) @ResponseBody public JsonResult checkLogin(@RequestBody LoginRequest request) { JsonResult result = new JsonResult(); result.error = 2020; result.data = String.format("%s : %s", request.user, request.pass); return result; } }
和用SpringMVC時沒有什麼不一樣。SpringBoot通常不推薦JSP視圖引擎,因此這裏使用了freemarker做爲視圖引擎。login方法裏指定了視圖爲home/login,所以在src/main/resources/templates/home下建立視圖login.ftl:ajax
<!DOCTYPE html> <html> <head> <title>Login</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="css/core.css" /> <script src="js/jquery-3.1.1.min.js"></script> <script> $(function(){ $("#login").click(function(){ $.ajax({ url: "checkLogin", type: "POST", contentType: "application/json", dataType: "json", data: JSON.stringify({user:"admin", pass:"123"}), success: function(data) { $("#out").text(JSON.stringify(data)); } }); }); }); </script> </head> <body> DateTime: ${time?time}<br> Message: ${message}<br/><br/> <button id="login">登陸</button><br/><br/> <div id="out"></div> </body> </html>
這個頁面從控制器接收了time和message兩個參數,用${}的形式顯示在頁面上。此外還包括了一個ajax調用,向後臺請求checkLogin,並傳入參數,顯示返回值。
spring
最後加個SpringBoot的配置文件,application.properties,放到src/main/resources下:
apache
# APPLICATION SETTINGS (SpringApplication) spring.main.web-environment=true spring.main.show-banner=false # EMBEDDED SERVER CONFIGURATION (ServerProperties) server.port=8080 # FREEMARKER (FreeMarkerAutoConfiguration) spring.freemarker.cache=false spring.freemarker.templateEncoding=UTF-8 spring.freemarker.suffix=.ftl
其實主要是server.port參數,咱們的工程內置了tomcat,這個參數指定了tomcat的綁定端口。json
完整的項目結構以下:瀏覽器
默認狀況下,視圖放到resources/templates下,靜態資源放到resources/static下。一切準備就緒,Ctrl+F11把工程跑起來吧,用瀏覽器訪問 http://localhost:8080/login 就能夠打開頁面了。一但在Eclipse裏修改了java文件,SpringBoot會自動從新加載,在開發調試時會很方便。
打包的時候,能夠把整個項目的相關資源打成一個jar,這樣用命令行就能夠運行了。
mvn clean package |
會在target下獲得一個appboot.jar,這個jar裏包含了用戶代碼的class文件、依賴的jar文件、視圖文件、靜態資源,會比較大,直接用命令行運行:
java -jar appboot.jar |
一個完整的web應用就跑起來了,目標環境只要有JRE就夠了,徹底不用安裝tomcat。雖然jar文件比較大,可是部署到遠程環境的話可就方便多了。
至於性能,徹底不用擔憂,本質是基於tomcat的,性能確定不會差,拿ab測試一下:
ab -c 10 -n 100000 http://localhost:8080/login |
結果以下,超過9000rps: