前言: css
看博文,感受做者對Spring Boot框架已經有了很深的認識,有一種高屋建瓴的感受。 html
原文出處: 純潔的微笑 前端
上篇文章介紹了Spring boot初級教程:spring boot(一):入門篇,方便你們快速入門、瞭解實踐Spring boot特性;本篇文章接着上篇內容繼續爲你們介紹spring boot的其它特性(有些未必是spring boot體系桟的功能,可是是spring特別推薦的一些開源技術本文也會介紹),對了這裏只是一個大概的介紹,特別詳細的使用咱們會在其它的文章中來展開說明。 vue
spring boot web開發很是的簡單,其中包括經常使用的json輸出、filters、property、log等 java
在之前的spring 開發的時候須要咱們提供json接口的時候須要作那些配置呢 mysql
就這樣咱們會常常因爲配置錯誤,致使406錯誤等等,spring boot如何作呢,只須要類添加 @RestController 便可,默認類中的方法都會以json的格式返回 jquery
@RestController
git
public
class
HelloWorldController {
github
@RequestMapping
(
"/getUser"
)
web
public
User getUser() {
User user=
new
User();
user.setUserName(
"小明"
);
user.setPassWord(
"xxxx"
);
return
user;
}
}
若是咱們須要使用頁面開發只要使用 @Controller ,下面會結合模板來講明
咱們經常在項目中會使用filters用於錄調用日誌、排除有XSS威脅的字符、執行權限驗證等等。Spring Boot自動添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,而且咱們能夠自定義Filter。
兩個步驟:
好吧,直接上代碼
@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
}
}
}
在web開發的過程當中,我常常須要自定義一些配置文件,如何使用呢
1
2
com.neo.title=純潔的微笑
com.neo.description=分享生活和技術
自定義配置類
@Component
public
class
NeoProperties {
@Value
(
"${com.neo.title}"
)
private
String title;
@Value
(
"${com.neo.description}"
)
private
String description;
//省略getter settet方法
}
配置輸出的地址和輸出級別
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中使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
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參數的做用主要用於:自動建立|更新|驗證數據庫表結構,有四個值:
dialect 主要是指定生成表名的存儲引擎爲InneoDB show-sql 是否打印出自動生產的SQL,方便調試的時候查看
@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);
@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"
));
}
}
當讓 spring data jpa 還有不少功能,好比封裝好的分頁,能夠本身定義SQL,主從分離等等,這裏就不詳細講了
Spring boot 推薦使用來代替jsp,thymeleaf模板究竟是什麼來頭呢,讓spring大哥來推薦,下面咱們來聊聊
Thymeleaf是一款用於渲染XML/XHTML/HTML5內容的模板引擎。相似JSP,Velocity,FreeMaker等,它也能夠輕易的與Spring MVC等Web框架進行集成做爲Web應用的模板引擎。與其它模板引擎相比,Thymeleaf最大的特色是可以直接在瀏覽器中打開並正確顯示模板頁面,而不須要啓動整個Web應用。
好了,大家說了咱們已經習慣使用了什麼 velocity,FreMaker,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在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>
<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文件。
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是一個很神奇的東西,可讓你們以jar包的形式來使用前端的各類框架、組件。
什麼是WebJars?WebJars是將客戶端(瀏覽器)資源(JavaScript,Css等)打成jar包文件,以對資源進行統一依賴管理。WebJars的jar包部署在Maven中央倉庫上。
咱們在開發Java web項目的時候會使用像Maven,Gradle等構建工具以實現對jar包版本依賴管理,以及項目的自動化管理,可是對於JavaScript,Css等前端資源包,咱們只能採用拷貝到webapp下的方式,這樣作就沒法對這些資源進行依賴管理。那麼WebJars就提供給咱們這些前端資源的jar包形勢,咱們就能夠進行依賴管理。
一、 WebJars主官網 查找對於的組件,好比Vuejs
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>vue</artifactId>
<version>
1.0
.
21
</version>
</dependency>
二、頁面引入
<link th:href=
"@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}"
rel=
"stylesheet"
></link>
就能夠正常使用了!