Spring Boot(二):Web 綜合開(kāi)發(fā)

上篇文章介紹了 Spring Boot 初級(jí)教程:Spring Boot(一):入門(mén)篇,方便大家快速入門(mén)、了解實(shí)踐 Spring Boot 特性;本篇文章接著上篇內(nèi)容繼續(xù)為大家介紹 Spring Boot 的其它特性(有些未必是 Spring Boot 體系桟的功能,但是是 Spring 特別推薦的一些開(kāi)源技術(shù)本文也會(huì)介紹),對(duì)了這里只是一個(gè)大概的介紹,特別詳細(xì)的使用我們會(huì)在其它的文章中來(lái)展開(kāi)說(shuō)明。

Web 開(kāi)發(fā)


Spring Boot Web 開(kāi)發(fā)非常的簡(jiǎn)單,其中包括常用的 json 輸出、filters、property、log 等

json 接口開(kāi)發(fā)

在以前使用 Spring 開(kāi)發(fā)項(xiàng)目,需要提供 json 接口時(shí)需要做哪些配置呢

1、添加 jackjson 等相關(guān) jar 包
2、配置 Spring Controller 掃描
3、對(duì)接的方法添加 @ResponseBody

就這樣我們會(huì)經(jīng)常由于配置錯(cuò)誤,導(dǎo)致406錯(cuò)誤等等,Spring Boot 如何做呢,只需要類(lèi)添加 @RestController 即可,默認(rèn)類(lèi)中的方法都會(huì)以 json 的格式返回

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

如果需要使用頁(yè)面開(kāi)發(fā)只要使用@Controller注解即可,下面會(huì)結(jié)合模板來(lái)說(shuō)明

自定義 Filter

我們常常在項(xiàng)目中會(huì)使用 filters 用于錄調(diào)用日志、排除有 XSS 威脅的字符、執(zhí)行權(quán)限驗(yàn)證等等。Spring Boot 自動(dòng)添加了 OrderedCharacterEncodingFilter 和 HiddenHttpMethodFilter,并且我們可以自定義 Filter。

兩個(gè)步驟:

1、實(shí)現(xiàn) Filter 接口,實(shí)現(xiàn) Filter 方法
2、添加@Configuration 注解,將自定義Filter加入過(guò)濾鏈

好吧,直接上代碼

@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }
    
    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }
    
    public class MyFilter implements Filter {
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
        }

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            HttpServletRequest request = (HttpServletRequest) srequest;
            System.out.println("this is MyFilter,url :"+request.getRequestURI());
            filterChain.doFilter(srequest, sresponse);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
            // TODO Auto-generated method stub
        }
    }
}

自定義 Property

在 Web 開(kāi)發(fā)的過(guò)程中,我經(jīng)常需要自定義一些配置文件,如何使用呢

配置在 application.properties 中
com.neo.title=純潔的微笑
com.neo.description=分享生活和技術(shù)
自定義配置類(lèi)
@Component
public class NeoProperties {
    @Value("${com.neo.title}")
    private String title;
    @Value("${com.neo.description}")
    private String description;

    //省略getter settet方法

    }

log配置

配置輸出的地址和輸出級(jí)別

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

path 為本機(jī)的 log 地址,logging.level 后面可以根據(jù)包路徑配置不同資源的 log 級(jí)別

數(shù)據(jù)庫(kù)操作


在這里我重點(diǎn)講述 Mysql、spring data jpa 的使用,其中 Mysql 就不用說(shuō)了大家很熟悉。Jpa 是利用 Hibernate 生成各種自動(dòng)化的 sql,如果只是簡(jiǎn)單的增刪改查,基本上不用手寫(xiě)了,Spring 內(nèi)部已經(jīng)幫大家封裝實(shí)現(xiàn)了。

下面簡(jiǎn)單介紹一下如何在 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

其實(shí)這個(gè) hibernate.hbm2ddl.auto 參數(shù)的作用主要用于:自動(dòng)創(chuàng)建 更新 驗(yàn)證數(shù)據(jù)庫(kù)表結(jié)構(gòu),有四個(gè)值:

1、create: 每次加載 hibernate 時(shí)都會(huì)刪除上一次的生成的表,然后根據(jù)你的 model 類(lèi)再重新來(lái)生成新表,哪怕兩次沒(méi)有任何改變也要這樣執(zhí)行,這就是導(dǎo)致數(shù)據(jù)庫(kù)表數(shù)據(jù)丟失的一個(gè)重要原因。
2、create-drop :每次加載 hibernate 時(shí)根據(jù) model 類(lèi)生成表,但是 sessionFactory 一關(guān)閉,表就自動(dòng)刪除。
3、update:最常用的屬性,第一次加載 hibernate 時(shí)根據(jù) model 類(lèi)會(huì)自動(dòng)建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫(kù)),以后加載 hibernate 時(shí)根據(jù) model 類(lèi)自動(dòng)更新表結(jié)構(gòu),即使表結(jié)構(gòu)改變了但表中的行仍然存在不會(huì)刪除以前的行。要注意的是當(dāng)部署到服務(wù)器后,表結(jié)構(gòu)是不會(huì)被馬上建立起來(lái)的,是要等 應(yīng)用第一次運(yùn)行起來(lái)后才會(huì)。
4、validate :每次加載 hibernate 時(shí),驗(yàn)證創(chuàng)建數(shù)據(jù)庫(kù)表結(jié)構(gòu),只會(huì)和數(shù)據(jù)庫(kù)中的表進(jìn)行比較,不會(huì)創(chuàng)建新表,但是會(huì)插入新值。

dialect 主要是指定生成表名的存儲(chǔ)引擎為 InnoDBD
show-sql是否打印出自動(dòng)生成的 SQL,方便調(diào)試的時(shí)候查看

3、添加實(shí)體類(lèi)和 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方法、構(gòu)造方法

}

dao 只要繼承 JpaRepository類(lèi)就可以,幾乎可以不用寫(xiě)方法,還有一個(gè)特別有尿性的功能非常贊,就是可以根據(jù)方法名來(lái)自動(dòng)的生成 SQL,比如findByUserName 會(huì)自動(dòng)生成一個(gè)以 userName 為參數(shù)的查詢方法,比如 findAlll 自動(dòng)會(huì)查詢表里面的所有數(shù)據(jù),比如自動(dòng)分頁(yè)等等。。

Entity 中不映射成列的字段得加 @Transient 注解,不加注解也會(huì)映射成列

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

4、測(cè)試

@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", "aa@126.com", "aa", "aa123456",formattedDate));
        userRepository.save(new User("bb2", "bb@126.com", "bb", "bb123456",formattedDate));
        userRepository.save(new User("cc3", "cc@126.com", "cc", "cc123456",formattedDate));

        Assert.assertEquals(9, userRepository.findAll().size());
        Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "cc@126.com").getNickName());
        userRepository.delete(userRepository.findByUserName("aa1"));
    }

}

當(dāng)讓 Spring Data Jpa 還有很多功能,比如封裝好的分頁(yè),可以自己定義 SQL,主從分離等等,這里就不詳細(xì)講了

Thymeleaf 模板


Spring Boot 推薦使用 Thymeleaf 來(lái)代替 Jsp,Thymeleaf 模板到底是什么來(lái)頭呢,讓 Spring 大哥來(lái)推薦,下面我們來(lái)聊聊

Thymeleaf 介紹

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 內(nèi)容的模板引擎。類(lèi)似 JSP,Velocity,F(xiàn)reeMaker 等,它也可以輕易的與 Spring MVC 等 Web 框架進(jìn)行集成作為 Web 應(yīng)用的模板引擎。與其它模板引擎相比,Thymeleaf 最大的特點(diǎn)是能夠直接在瀏覽器中打開(kāi)并正確顯示模板頁(yè)面,而不需要啟動(dòng)整個(gè) Web 應(yīng)用。

好了,你們說(shuō)了我們已經(jīng)習(xí)慣使用了什么 Velocity,FreMaker,beetle之類(lèi)的模版,那么到底好在哪里呢?

比一比吧

Thymeleaf 是與眾不同的,因?yàn)樗褂昧俗匀坏哪0寮夹g(shù)。這意味著 Thymeleaf 的模板語(yǔ)法并不會(huì)破壞文檔的結(jié)構(gòu),模板依舊是有效的XML文檔。模板還可以用作工作原型,Thymeleaf 會(huì)在運(yùn)行期替換掉靜態(tài)值。Velocity 與 FreeMarke r則是連續(xù)的文本處理器。 下面的代碼示例分別使用 Velocity、FreeMarker 與 Thymeleaf 打印出一條消息:

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

注意,由于 Thymeleaf 使用了 XML DOM 解析器,因此它并不適合于處理大規(guī)模的 XML 文件。

URL

URL 在 Web 應(yīng)用模板中占據(jù)著十分重要的地位,需要特別注意的是 Thymeleaf 對(duì)于 URL 的處理是通過(guò)語(yǔ)法 @{...} 來(lái)處理的。Thymeleaf 支持絕對(duì)路徑 URL:

<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>
條件求值
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

for循環(huán)

<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>

就列出這幾個(gè)吧

頁(yè)面即原型

在 Web 開(kāi)發(fā)過(guò)程中一個(gè)繞不開(kāi)的話題就是前端工程師與后端工程師的協(xié)作,在傳統(tǒng) Java Web 開(kāi)發(fā)過(guò)程中,前端工程師和后端工程師一樣,也需要安裝一套完整的開(kāi)發(fā)環(huán)境,然后各類(lèi) Java IDE 中修改模板、靜態(tài)資源文件,啟動(dòng)/重啟/重新加載應(yīng)用服務(wù)器,刷新頁(yè)面查看最終效果。

但實(shí)際上前端工程師的職責(zé)更多應(yīng)該關(guān)注于頁(yè)面本身而非后端,使用 JSP,Velocity 等傳統(tǒng)的 Java 模板引擎很難做到這一點(diǎn),因?yàn)樗鼈儽仨氃趹?yīng)用服務(wù)器中渲染完成后才能在瀏覽器中看到結(jié)果,而 Thymeleaf 從根本上顛覆了這一過(guò)程,通過(guò)屬性進(jìn)行模板渲染不會(huì)引入任何新的瀏覽器不能識(shí)別的標(biāo)簽,例如 JSP 中的 ,不會(huì)在 Tag 內(nèi)部寫(xiě)表達(dá)式。整個(gè)頁(yè)面直接作為 HTML 文件用瀏覽器打開(kāi),幾乎就可以看到最終的效果,這大大解放了前端工程師的生產(chǎn)力,它們的最終交付物就是純的 HTML/CSS/JavaScript 文件。

Gradle 構(gòu)建工具


Spring 項(xiàng)目建議使用 Maven/Gradle 進(jìn)行構(gòu)建項(xiàng)目,相比 Maven 來(lái)講 Gradle 更簡(jiǎn)潔,而且 Gradle 更適合大型復(fù)雜項(xiàng)目的構(gòu)建。Gradle 吸收了 Maven 和 Ant 的特點(diǎn)而來(lái),不過(guò)目前 Maven 仍然是 Java 界的主流,大家可以先了解了解。

一個(gè)使用 Gradle 配置的項(xiàng)目

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 插件, 表明這是一個(gè) Java 項(xiàng)目
apply plugin: 'spring-boot' //添加 Spring-boot支持
apply plugin: 'war'  //添加 War 插件, 可以導(dǎo)出 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  //目標(biāo)兼容版本 JDK1.7

repositories {     //  Maven 倉(cāng)庫(kù)
    mavenLocal()        //使用本地倉(cāng)庫(kù)
    mavenCentral()      //使用中央倉(cāng)庫(kù)
    maven { url "http://repo.spring.io/libs-snapshot" } //使用遠(yuǎn)程倉(cāng)庫(kù)
}
 
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 是一個(gè)很神奇的東西,可以讓大家以 Jar 包的形式來(lái)使用前端的各種框架、組件。

什么是 WebJars

WebJars 是將客戶端(瀏覽器)資源(JavaScript,Css等)打成 Jar 包文件,以對(duì)資源進(jìn)行統(tǒng)一依賴管理。WebJars 的 Jar 包部署在 Maven 中央倉(cāng)庫(kù)上。

為什么使用

我們?cè)陂_(kāi)發(fā) Java web 項(xiàng)目的時(shí)候會(huì)使用像 Maven,Gradle 等構(gòu)建工具以實(shí)現(xiàn)對(duì) Jar 包版本依賴管理,以及項(xiàng)目的自動(dòng)化管理,但是對(duì)于 JavaScript,Css 等前端資源包,我們只能采用拷貝到 webapp 下的方式,這樣做就無(wú)法對(duì)這些資源進(jìn)行依賴管理。那么 WebJars 就提供給我們這些前端資源的 Jar 包形勢(shì),我們就可以進(jìn)行依賴管理。

如何使用

1、 WebJars主官網(wǎng) 查找對(duì)于的組件,比如 Vuejs

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

2、頁(yè)面引入

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

就可以正常使用了!

示例代碼-github

示例代碼-碼云

文章內(nèi)容已經(jīng)升級(jí)到 Spring Boot 2.x

參考:

新一代Java模板引擎Thymeleaf

Spring Boot參考指南-中文版

轉(zhuǎn)載自:http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容