1. 程式人生 > 實用技巧 >Spring Book Web(1)

Spring Book Web(1)

使用 Spring Boot 有什麼好處

其實就是簡單、快速、方便!

平時如果我們需要搭建一個 Spring Web 專案的時候需要怎麼做呢?

1)配置 web.xml,載入 Spring 和 Spring mvc
2)配置資料庫連線、配置 Spring 事務
3)配置載入配置檔案的讀取,開啟註解
4)配置日誌檔案
…
配置完成之後部署 Tomcat 除錯
…

  

但是如果使用 Spring Boot 呢?
很簡單,我僅僅只需要非常少的幾個配置就可以迅速方便的搭建起來一套 Web 專案或者是構建一個微服務!

使用 Spring Boot 到底有多爽,用下面這幅圖來表達

Spring Boot 的基礎結構共三個檔案:

src/main/java 程式開發以及主程式入口
src/main/resources 配置檔案
src/test/java 測試程式

  

Web 開發

Spring Boot Web 開發非常的簡單,其中包括常用的 json 輸出、filters、property、log 等

json 介面開發

在以前使用 Spring 開發專案,需要提供 json 介面時需要做哪些配置呢

新增 jackjson 等相關 jar 包
配置 Spring Controller 掃描
對接的方法新增 @ResponseBody

  就這樣我們會經常由於配置錯誤,導致406錯誤等等,Spring Boot 如何做呢,只需要類新增@RestController

即可,預設類中的方法都會以 json 的格式返回

@RestController
public class HelloController {
    @RequestMapping("/getUser")
    public User getUser() {
    	User user=new User();
    	user.setUserName("小明");
    	user.setPassWord("xxxx");
        return user;
    }
}

  如果需要使用頁面開發只要使用@Controller註解即可,下面會結合模板來說明

自定義 Filter

我們常常在專案中會使用 filters 用於錄呼叫日誌、排除有 XSS 威脅的字元、執行許可權驗證等等。Spring Boot 自動添加了 OrderedCharacterEncodingFilter 和 HiddenHttpMethodFilter,並且我們可以自定義 Filter。

兩個步驟:

實現 Filter 介面,實現 Filter 方法
新增@Configuration 註解,將自定義Filter加入過濾鏈

  

自定義 Property

在 Web 開發的過程中,我經常需要自定義一些配置檔案,如何使用呢

配置在 application.properties 中

com.neo.title=純潔的微笑
com.neo.description=分享生活和技術

log配置

配置輸出的地址和輸出級別

logging.path=/user/local/log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR

  path 為本機的 log 地址,logging.level後面可以根據包路徑配置不同資源的 log 級別

資料庫操作

在這裡我重點講述 Mysql、spring data jpa 的使用,其中 Mysql 就不用說了大家很熟悉。Jpa 是利用 Hibernate 生成各種自動化的 sql,如果只是簡單的增刪改查,基本上不用手寫了,Spring 內部已經幫大家封裝實現了。

下面簡單介紹一下如何在 Spring Boot 中使用

1、新增相 jar 包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

  

2、新增配置檔案

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

  

其實這個 hibernate.hbm2ddl.auto 引數的作用主要用於:自動建立 更新 驗證資料庫表結構,有四個值:
create: 每次載入 hibernate 時都會刪除上一次的生成的表,然後根據你的 model 類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致資料庫表資料丟失的一個重要原因。
create-drop :每次載入 hibernate 時根據 model 類生成表,但是 sessionFactory 一關閉,表就自動刪除。
update:最常用的屬性,第一次載入 hibernate 時根據 model 類會自動建立起表的結構(前提是先建立好資料庫),以後載入 hibernate 時根據 model 類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到伺服器後,表結構是不會被馬上建立起來的,是要等 應用第一次執行起來後才會。
validate :每次載入 hibernate 時,驗證建立資料庫表結構,只會和資料庫中的表進行比較,不會建立新表,但是會插入新值。

dialect主要是指定生成表名的儲存引擎為 InnoDBD
show-sql是否打印出自動生成的 SQL,方便除錯的時候檢視

3、新增實體類和 Dao

@Entity
public class User implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue
	private Long id;
	@Column(nullable = false, unique = true)
	private String userName;
	@Column(nullable = false)
	private String passWord;
	@Column(nullable = false, unique = true)
	private String email;
	@Column(nullable = true, unique = true)
	private String nickName;
	@Column(nullable = false)
	private String regTime;

	//省略getter settet方法、構造方法

}

  dao 只要繼承 JpaRepository 類就可以,幾乎可以不用寫方法,還有一個特別有尿性的功能非常贊,就是可以根據方法名來自動的生成 SQL,比如findByUserName會自動生成一個以userName為引數的查詢方法,比如findAlll自動會查詢表裡面的所有資料,比如自動分頁等等。。

Entity 中不對映成列的欄位得加 @Transient 註解,不加註解也會對映成列

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
}

  

4、測試

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class UserRepositoryTests {

	@Autowired
	private UserRepository userRepository;

	@Test
	public void test() throws Exception {
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);        
		String formattedDate = dateFormat.format(date);
		
		userRepository.save(new User("aa1", "[email protected]", "aa", "aa123456",formattedDate));
		userRepository.save(new User("bb2", "[email protected]", "bb", "bb123456",formattedDate));
		userRepository.save(new User("cc3", "[email protected]", "cc", "cc123456",formattedDate));

		Assert.assertEquals(9, userRepository.findAll().size());
		Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "[email protected]").getNickName());
		userRepository.delete(userRepository.findByUserName("aa1"));
	}

}

  當讓 Spring Data Jpa 還有很多功能,比如封裝好的分頁,可以自己定義 SQL,主從分離等等,這裡就不詳細講了

Thymeleaf 模板

Spring Boot 推薦使用 Thymeleaf 來代替 Jsp,Thymeleaf 模板到底是什麼來頭呢,讓 Spring 大哥來推薦,下面我們來聊聊,.

Thymeleaf 介紹

Thymeleaf 是一款用於渲染 XML/XHTML/HTML5 內容的模板引擎。類似 JSP,Velocity,FreeMaker 等,它也可以輕易的與 Spring MVC 等 Web 框架進行整合作為 Web 應用的模板引擎。與其它模板引擎相比,Thymeleaf 最大的特點是能夠直接在瀏覽器中開啟並正確顯示模板頁面,而不需要啟動整個 Web 應用。

好了,你們說了我們已經習慣使用了什麼 Velocity,FreMaker,beetle之類的模版,那麼到底好在哪裡呢?

比一比吧

Thymeleaf 是與眾不同的,因為它使用了自然的模板技術。這意味著 Thymeleaf 的模板語法並不會破壞文件的結構,模板依舊是有效的XML文件。模板還可以用作工作原型,Thymeleaf 會在執行期替換掉靜態值。Velocity 與 FreeMarke r則是連續的文字處理器。 下面的程式碼示例分別使用 Velocity、FreeMarker 與 Thymeleaf 打印出一條訊息:

Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>

  

注意,由於 Thymeleaf 使用了 XML DOM 解析器,因此它並不適合於處理大規模的 XML 檔案。

URL

URL 在 Web 應用模板中佔據著十分重要的地位,需要特別注意的是 Thymeleaf 對於 URL 的處理是通過語法@{...}來處理的。Thymeleaf 支援絕對路徑 URL:

<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

  

條件求值

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

  

for迴圈

<tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

  就列出這幾個吧

頁面即原型

在 Web 開發過程中一個繞不開的話題就是前端工程師與後端工程師的協作,在傳統 Java Web 開發過程中,前端工程師和後端工程師一樣,也需要安裝一套完整的開發環境,然後各類 Java IDE 中修改模板、靜態資原始檔,啟動/重啟/重新載入應用伺服器,重新整理頁面檢視最終效果。

但實際上前端工程師的職責更多應該關注於頁面本身而非後端,使用 JSP,Velocity 等傳統的 Java 模板引擎很難做到這一點,因為它們必須在應用伺服器中渲染完成後才能在瀏覽器中看到結果,而 Thymeleaf 從根本上顛覆了這一過程,通過屬性進行模板渲染不會引入任何新的瀏覽器不能識別的標籤,例如 JSP 中的,不會在 Tag 內部寫表示式。整個頁面直接作為 HTML 檔案用瀏覽器開啟,幾乎就可以看到最終的效果,這大大解放了前端工程師的生產力,它們的最終交付物就是純的 HTML/CSS/JavaScript 檔案。

Gradle 構建工具

Spring 專案建議使用 Maven/Gradle 進行構建專案,相比 Maven 來講 Gradle 更簡潔,而且 Gradle 更適合大型複雜專案的構建。Gradle 吸收了 Maven 和 Ant 的特點而來,不過目前 Maven 仍然是 Java 界的主流,大家可以先了解了解。

一個使用 Gradle 配置的專案

buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-snapshot" }
        mavenLocal()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
    }
}

apply plugin: 'java'  //新增 Java 外掛, 表明這是一個 Java 專案
apply plugin: 'spring-boot' //新增 Spring-boot支援
apply plugin: 'war'  //新增 War 外掛, 可以匯出 War 包
apply plugin: 'eclipse' //新增 Eclipse 外掛, 新增 Eclipse IDE 支援, Intellij Idea 為 "idea"

war {
    baseName = 'favorites'
    version =  '0.1.0'
}

sourceCompatibility = 1.7  //最低相容版本 JDK1.7
targetCompatibility = 1.7  //目標相容版本 JDK1.7

repositories {     //  Maven 倉庫
    mavenLocal()        //使用本地倉庫
    mavenCentral()      //使用中央倉庫
    maven { url "http://repo.spring.io/libs-snapshot" } //使用遠端倉庫
}
 
dependencies {   // 各種 依賴的jar包
    compile("org.springframework.boot:spring-boot-starter-web:1.3.6.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-thymeleaf:1.3.6.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-data-jpa:1.3.6.RELEASE")
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
    compile("org.springframework.boot:spring-boot-devtools:1.3.6.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-test:1.3.6.RELEASE")
    compile 'org.webjars.bower:bootstrap:3.3.6'
	compile 'org.webjars.bower:jquery:2.2.4'
    compile("org.webjars:vue:1.0.24")
	compile 'org.webjars.bower:vue-resource:0.7.0'

}

bootRun {
    addResources = true
}

  

WebJars

WebJars 是一個很神奇的東西,可以讓大家以 Jar 包的形式來使用前端的各種框架、元件。

什麼是 WebJars

WebJars 是將客戶端(瀏覽器)資源(JavaScript,Css等)打成 Jar 包檔案,以對資源進行統一依賴管理。WebJars 的 Jar 包部署在 Maven 中央倉庫上。

  

為什麼使用

我們在開發 Java web 專案的時候會使用像 Maven,Gradle 等構建工具以實現對 Jar 包版本依賴管理,以及專案的自動化管理,但是對於 JavaScript,Css 等前端資源包,我們只能採用拷貝到 webapp 下的方式,這樣做就無法對這些資源進行依賴管理。那麼 WebJars 就提供給我們這些前端資源的 Jar 包形勢,我們就可以進行依賴管理。

  

如何使用

1、WebJars主官網查詢對於的元件,比如 Vuejs

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>vue</artifactId>
    <version>2.5.16</version>
</dependency>

2、頁面引入

<link th:href="@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}" rel="stylesheet"></link>

  就可以正常使用了!