Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。
特點:
1. 創建獨立的Spring應用程序
2. 嵌入的Tomcat,無需部署WAR文件
3. 簡化Maven配置
4. 自動配置Spring
5. 提供生產就緒型功能,如指標,健康檢查和外部配置
6. 絕對沒有代碼生成和對XML沒有要求配置
Thyemleaf一個優秀的前端模版,用來替代JSP,因為它能做到前后端分離,支持靜態化。
前面講到SpringBoot本身不需要配置,但是集成Thyemleaf需要加入配置。下面介紹步驟。
1.導入maven依賴
<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>com.imooc</groupId> <artifactId>miaosha_1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>miaosha_1</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!--springBoot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project>
2.SpringBoot會默認在resources下查找application.properties的配置文件。
application.properties用來配置Thyemleaf的池
#緩存
spring.thymeleaf.cache=false
#文本
spring.thymeleaf.content-type=text/html
#啟用
spring.thymeleaf.enabled=true
#編碼
spring.thymeleaf.encoding=UTF-8
#頁面
spring.thymeleaf.mode=HTML5
#前綴
sprin.thymeleaf.prefix=classpath:/templates/
#后綴
spring.thymeleaf.suffix=.html
3.在配置的前綴文件下 編寫html頁面
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>hello</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'hello:'+${name}" ></p> </body> </html>
4.control控制
@Controlle
@RequestMapping("/demo")
public class DemoController { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } //1.rest api json輸出 2.頁面 @RequestMapping("/hello") @ResponseBody public Result<String> hello() { return Result.success("hello,imooc"); // return new Result(0, "success", "hello,imooc"); } @RequestMapping("/helloError") @ResponseBody public Result<String> helloError() { return Result.error(CodeMsg.SERVER_ERROR); //return new Result(500102, "XXX"); } /** * thymeleaf測試的主要方法 * @param model * @return */ @RequestMapping("/thymeleaf") public String thymeleaf(Model model) { model.addAttribute("name", "Joshua"); return "hello"; } }
5.程序的入口mian方法。
SpringBoot有兩個常用的注解,一個是@controller
另一個是@EnableAutoConfiguration,但是一般不使用這個而是用
@SpringBootApplication
如下整個項目就能正常啟動了