1. 程式人生 > >SpringBoot從入門到熟悉(二)web開發

SpringBoot從入門到熟悉(二)web開發

web開發

spring boot web開發非常的簡單,其中包括常用的json輸出、filters、property、log等

json 介面開發

在以前的spring 開發的時候需要我們提供json介面的時候需要做那些配置呢

  1. 新增 jackjson 等相關jar包
  2. 配置spring controller掃描
  3. 對接的方法新增@ResponseBody

就這樣我們會經常由於配置錯誤,導致406錯誤等等,spring boot如何做呢,只需要類新增 @RestController或者@Controller [email protected]  即可,預設類中的方法都會以json的格式返回

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

上面,通過@[email protected]註解與@RestController會有同樣結果

啟動專案通過:localhost:8080/getUser來直接訪問了,返回Json結構資料,結果如下

如果使用Controller註解,忘記加ResponseBody註解,會有如下報錯資訊,下次你應該知道問題在哪了,錯誤資訊描述的也很清楚,即未指定檢視:

如果我們需要使用頁面開發只要使用 @Controller配合要跳轉的頁面,下面會結合模板來說明

自定義Filter

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

兩個步驟:

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

好吧,直接上程式碼,關於配置過濾器的一些說明,在後面註釋中

@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteAddrFilter(){
        return new RemoteIpFilter();
    }
    @Bean
    public FilterRegistrationBean testFilterRegistration(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());     //自定義的過濾器
        registration.addUrlPatterns("/*");        //配置哪些請求地址走過濾器  ,也可以單個設定比如/getUser
        registration.addInitParameter("paramName","paramValue");    //新增預設引數
        registration.setName("過濾器名稱");        //配置過濾器名稱
        registration.setOrder(1);               //過濾器順序,當有多個過濾器時配置
        return registration;
    }
    public class MyFilter implements Filter{

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest hRequest = (HttpServletRequest) servletRequest;
            System.out.println("this is MyFilter,url:"+hRequest.getRequestURI()+" user:"+hRequest.getRemoteUser()+" authType:"+hRequest.getAuthType());
            filterChain.doFilter(servletRequest,servletResponse);
        }

        @Override
        public void destroy() {

        }
    }
}

在controller層獲取filter配置:

  @Autowired
    FilterRegistrationBean filterRegistrationBean;

    @RequestMapping("/getFilterConfig")
    public Map getInitMap(){
        Map initParameters = filterRegistrationBean.getInitParameters();
        System.out.println(filterRegistrationBean.getOrder());
        System.out.println(filterRegistrationBean.getServletNames());
        System.out.println(filterRegistrationBean.getUrlPatterns());
        return initParameters;
    }

 下圖中,左側時filter中的配置,右邊時controller層中獲取到的結果

自定義Property

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

配置在application.properties中

com.zerah.title=zerah
com.zerah.description=web Demo

自定義配置類

    @Value("${com.zerah.title}")
    private String title;
    @Value("com.zerah.description")
    private String description;

    @RequestMapping("/getProp")
    public String getProp(){
        System.out.println(title);                //會直接注入配置檔案中的值
        System.out.println(description);        //如果忘記加${} 變數會直接注入@Value中的值
        return title;
    }

log配置

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

logging.path=/user/local/log
logging.level.com.zerah.boot=info
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包

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

2、新增配置檔案

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

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

其實這個hibernate.hbm2ddl.auto引數的作用主要用於:自動建立|更新|驗證資料庫表結構,有四個值:

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

dialect 主要是指定生成表名的儲存引擎為InneoDB

show-sql 是否打印出自動生產的SQL,方便除錯的時候檢視

3、新增實體類和Dao,切記不要忘了實體類上面的@Entity註解

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

    //get/set省略
}

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

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

/**
 * User repo  泛型第一個引數代表要對映的實體類,第二個代表主鍵型別
 */
public interface UserRepository extends JpaRepository<User,Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String userName,String email);
}

4、測試

@RunWith(SpringJUnit4ClassRunner.class)
//@SpringApplicationConfiguration       1.5之後已移除,使用@SpringBootTest就可以了
@SpringBootTest
public class UserRepositoryTests {
    @Autowired
    private UserRepository userRepository;
    @Test
    public void test(){
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        String format = dateFormat.format(date);
        System.out.println(format);

        userRepository.save(new User("aa1", "[email protected]", "aa", "aa123456",format));
        userRepository.save(new User("bb2", "[email protected]", "bb", "bb123456",format));
        userRepository.save(new User("cc3", "[email protected]", "cc", "cc123456",format));

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

儲存資料結果如下,如果多次測試,記得將application.properties中spring.jpa.properties.hibernate.hbm2ddl.auto的值修改為create,否則忘記之後多次修改會報Duplicate entry 'aa' for key 'UK_ob8kqyqqgmefl0aco34akdtpe'類似的錯誤,如下,我的mysql字符集好像沒有修改成功,正確的reg_time應該是:2018年10月22日 CST 上午12:14:40【沒錯,我還在熬夜】,這個待會在改吧  * ^ *

還有如果,你和我一樣使用的JDK  8以上的版本,需要在maven中新增以下依賴:

 <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>

thymeleaf模板

Spring boot 推薦使用來代替jsp,thymeleaf模板到底是什麼來頭呢,讓spring大哥來推薦,下面我們來聊聊

Thymeleaf 介紹

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

好了,你們說了我們已經習慣使用了什麼 velocity,FreeMaker,beetle之類的模版,那麼到底好在哪裡呢? 比一比吧 Thymeleaf是與眾不同的,因為它使用了自然的模板技術。這意味著Thymeleaf的模板語法並不會破壞文件的結構,模板依舊是有效的XML文件。模板還可以用作工作原型,Thymeleaf會在執行期替換掉靜態值。Velocity與FreeMarker則是連續的文字處理器。 下面的程式碼示例分別使用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 專案建議使用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?WebJars是將客戶端(瀏覽器)資源(JavaScript,Css等)打成jar包檔案,以對資源進行統一依賴管理。WebJars的jar包部署在Maven中央倉庫上。

為什麼使用

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

如何使用

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

<dependency>
    <groupId>org.webjars.bower</groupId>
    <artifactId>vue</artifactId>
    <version>1.0.21</version>
</dependency>

2、頁面引入

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

就可以正常使用了!

相關推薦

SpringBoot入門熟悉web開發

web開發 spring boot web開發非常的簡單,其中包括常用的json輸出、filters、property、log等 json 介面開發 在以前的spring 開發的時候需要我們提供json介面的時候需要做那些配置呢 新增 jackjson 等相關jar

GAN網路入門教程之GAN原理

在一篇部落格[GAN網路從入門教程(一)之GAN網路介紹](https://www.cnblogs.com/xiaohuiduan/p/13237486.html)中,簡單的對GAN網路進行了一些介紹,介紹了其是什麼,然後大概的流程是什麼。 在這篇部落格中,主要是介紹其數學公式,以及其演算法流程。當然數學公

Spring bootWeb開發

final 一次 org init 調用 mat 重要 映射 ppi 上篇文章介紹了Spring boot初級教程:spring boot(一):入門篇,方便大家快速入門、了解實踐Spring boot特性;本篇文章接著上篇內容繼續為大家介紹spring boot的其它特性

SpringBoot入門筆記IDEA下springboot專案spring+mybatis+sqlserver+log4j+簡單登入驗證攔截器的框架搭建

IDEA下springboot專案spring+mybatis+sqlserver+log4j+簡單登入驗證攔截器的框架搭建 先貼一個專案的目錄結構 Attention:templates.html5是templates目錄下新建了一個html5目錄 1.專案建立 這個簡單,選

SpringBoot學習---- web綜合開發

一、常用web開發功能 json輸出、filter、property、log等 1,json介面 在需要類中新增@RestController即可 @RestController public class JsonController { @RequestMappin

Springboot 入門

springboot是基於spring框架上的,可以輕鬆建立可用獨立執行的應用程式。springboot是對spring框架和第三庫的整合,這樣就能輕鬆上手了, 大多數springboot應用程式只需要很少的spring配置。可以使用springboot建立一個jar應用程

python爬蟲"Hello World"級入門例項,使用json中國天氣網抓取資料

一、二話不說先上程式碼 python2.7版 #!/usr/bin/python2.7 #-*- coding=UTF-8 -*- import urllib import json def get_dic(url): page = urll

SpringBoot 入門 SpringBoot常用註解以及自動配置

一、SpringBoot常用註解 二、SpringBoot自動配置機制 一、SpringBoot常用註解   在上一篇文章中https://blog.csdn.net/zhichao_qzc/article/details/806421

Android入門熟悉androidstudio開發軟體

本章將說明如何在專案中加入各種元件(文字框、按鈕、輸入欄位)、設計使用者介面的各種基本知識、示範使用簡單的方式編寫程式,建立具有互動效果的程式邏輯。 (一)Android App主要組成 Android App程式主要由4種類型組成: 1.Activity

Spring Boot 系列入門 web工程識別JSP

開發環境描述 IntelliJ IDEA 2017.2.6 JDK 1.8 建立Web工程 1. File->New->Project 2. 在New Project選擇Spring Initiali

SpringBoot入門系列如何返回統一的資料格式

前面介紹了Spring Boot的優點,然後介紹瞭如何快速建立Spring Boot 專案。不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。 今天來說一說Spring的@Controller和@RestCo

Struts2框架 Web.xml, Struts.xml, Action.Java 基本配置

str web.xml images ava img ima blog XML ges Struts2框架(二) Web.xml, Struts.xml, Action.Java 基本配置

cocos2dx 3.1零學習——菜單、場景切換、場景傳值

天空 ptr select 特效 new 要點 綁定 使用 water 回想一下上一篇的內容,我們已經學會了創建一個新的場景scene,加入sprite和label到層中。掌握了定時事件schedule。我們能夠順利的寫出打飛機的主場景框架。 上一篇的內容我練習了七個新

Asp.Net Core WebAPI入門整理簡單示例

序列 open exc tor pda template ssa net found 一、Core WebAPI中的序列化 使用的是Newtonsoft.Json,自定義全局配置處理: // This method gets called by the runtime.

Struts2入門介紹

輸入 clu ons dom 訪問路徑 訪問 filter pri locale 一、Struts執行過程的分析。   當我們在瀏覽器中輸入了網址http://127.0.0.1:8080/Struts2_01/hello.action的時候,Struts2做了如下過程:

CodeArt入門教程

本質 文件夾 不同的 存在 切換數據庫 站點 ear 新的 組裝 4.第一個示例的編碼工作   使用CA編碼項目的核心結構是:由多個子系統組成多個不同的服務來提供項目的各種功能。請不要將這裏提到的子系統與大家在別的項目實施方法裏的概念混為一談,CA裏的子系統概念是完全不一樣

OpenCV入門筆記 圖片的文件操作

strong asc nump str destroy type convert 代碼 creat 以下介紹一下重要的幾個,設計基本 圖片處理 的函數,依次來了解OpenCV的入門知識。具體的具體使用方法還是以官方的API【Official Tutori

Dapper入門教程——執行非查詢語句

文本 resp -exec factor -h spa onf fec table 描述 你可以從任意實現IDbConnection的類對象中調用Dapper的擴展方法“Execute”。它能夠執行一條命令(Command)一次或者多次,並返回受影響的行數。這個方法通常用來

Maven入門指南

deploy ... web服務器 快速 repos 必須 轉載 關於 net 轉載自並發編程網 – ifeve.com本文鏈接地址: Maven入門指南(二) Maven目錄結構 Maven有一個標準的目錄結構。如果你在項目中遵循Maven的目錄結構,就無需在pom文件中

Hyperledger Fabric 1.0 零開始——公網環境構建

1.3 項目 htm move 自己 lvm2 fast 情況 tor 1:環境構建 在本文中用到的宿主機環境是Centos ,版本為Centos.x86_647.2,通過Docker 容器來運行Fabric的節點,版本為v1.0。因此,啟動Fabric網絡中的節點需要先安