一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術(shù)|正則表達(dá)式|

服務(wù)器之家 - 編程語(yǔ)言 - JAVA教程 - Spring Boot(二)之web綜合開(kāi)發(fā)

Spring Boot(二)之web綜合開(kāi)發(fā)

2020-09-27 15:04純潔的微笑 JAVA教程

本篇文章為大家介紹spring boot的其它特性(有些未必是spring boot體系桟的功能,但是是spring特別推薦的一些開(kāi)源技術(shù)本文也會(huì)介紹),對(duì)了這里只是一個(gè)大概的介紹,特別詳細(xì)的使用我們會(huì)在其它的文章中來(lái)展開(kāi)說(shuō)明

上篇文章介紹了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ā)的時(shí)候需要我們提供json接口的時(shí)候需要做那些配置呢

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

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

?
1
2
3
4
5
6
7
8
9
10
@RestController
public class HelloWorldController {
 @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. 添加@Configurationz 注解,將自定義Filter加入過(guò)濾鏈

好吧,直接上代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@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ù)

自定義配置類

?
1
2
3
4
5
6
7
8
@Component
public class NeoProperties {
 @Value("${com.neo.title}")
 private String title;
 @Value("${com.neo.description}")
 private String description;
 //省略getter settet方法
 }

log配置

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

?
1
2
3
4
5
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包

?
1
2
3
4
5
6
7
8
<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、添加配置文件

?
1
2
3
4
5
6
7
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è)值:

create: 每次加載hibernate時(shí)都會(huì)刪除上一次的生成的表,然后根據(jù)你的model類再重新來(lái)生成新表,哪怕兩次沒(méi)有任何改變也要這樣執(zhí)行,這就是導(dǎo)致數(shù)據(jù)庫(kù)表數(shù)據(jù)丟失的一個(gè)重要原因。

create-drop :每次加載hibernate時(shí)根據(jù)model類生成表,但是sessionFactory一關(guān)閉,表就自動(dòng)刪除。

update:最常用的屬性,第一次加載hibernate時(shí)根據(jù)model類會(huì)自動(dòng)建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫(kù)),以后加載hibernate時(shí)根據(jù) model類自動(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ì)。

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ǔ)引擎為InneoDB

show-sql 是否打印出自動(dòng)生產(chǎn)的SQL,方便調(diào)試的時(shí)候查看

3、添加實(shí)體類和Dao

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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類就可以,幾乎可以不用寫(xiě)方法,還有一個(gè)特別有尿性的功能非常贊,就是可以根據(jù)方法名來(lái)自動(dòng)的生產(chǎn)SQL,比如findByUserName 會(huì)自動(dòng)生產(chǎn)一個(gè)以 userName 為參數(shù)的查詢方法,比如 findAlll 自動(dòng)會(huì)查詢表里面的所有數(shù)據(jù),比如自動(dòng)分頁(yè)等等。。

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

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

4、測(cè)試

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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"));
 }
}

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

thymeleaf模板

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

Thymeleaf 介紹

Thymeleaf是一款用于渲染XML/XHTML/HTML5內(nè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之類的模版,那么到底好在哪里呢?
比一比吧

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

下面的代碼示例分別使用Velocity、FreeMarker與Thymeleaf打印出一條消息:

?
1
2
3
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:

?
1
<a th:href="@{http://www.thymeleaf.org}" rel="external nofollow" >Thymeleaf</a>

條件求值

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

for循環(huán)

?
1
2
3
4
5
<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)境,然后各類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)目建議使用Gradle進(jìn)行構(gòu)建項(xiàng)目,相比maven來(lái)講 Gradle更簡(jiǎn)潔,而且gradle更時(shí)候大型復(fù)雜項(xiàng)目的構(gòu)建。gradle吸收了maven和ant的特點(diǎn)而來(lái),不過(guò)目前maven仍然是Java界的主流,大家可以先了解了解。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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?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

?
1
2
3
4
5
<dependency>
 <groupId>org.webjars.bower</groupId>
 <artifactId>vue</artifactId>
 <version>1.0.21</version>
</dependency>

2、頁(yè)面引入

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

就可以正常使用了!

本文所有講的代碼示例都在這里

原文鏈接:http://www.cnblogs.com/ityouknow/p/5730412.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 龟甲情感超市全文阅读 小说 | 亚洲一级特黄特黄的大片 | 国产一区二区视频免费 | 国产91在线精品狼人 | a毛片久久免费观看 | 日韩一区二区三区四区五区 | 国产91精选学生在线观看 | 免费一级欧美片在线观免看 | 亚洲色图15p | 美女流白浆| 楚乔传第二部免费播放电视连续剧 | 99久久一区二区精品 | 国产精品嫩草影院一二三区 | 91免费精品国自产拍在线可以看 | 成人在线视频在线观看 | 国产香蕉在线视频 | 5555kkkk香蕉在线观看 | 天天做日日爱 | 色综久久天天综合绕视看 | 日产精品卡一卡2卡三卡乱码工厂 | 欧美成人精品福利网站 | 久久精品中文騷妇女内射 | 9966国产精品视频 | 热剧库 | 国内自拍第1页 | 褪色的憎恨 | 国产综合欧美日韩视频一区 | 欧美作爱福利免费观看视频 | 国模娜娜一区二区三区 | 久9青青cao精品视频在线 | 欧美xxoo黑人又粗暴 | 6080伦理久久精品亚洲 | 欧美人shou交在线播放 | 日本男男gaygays| 国产欧美视频高清va在线观看 | bb18lv黑料正能量 | 69av美女 | 丝瓜茄子绿巨人秋葵榴莲污 | 男同激情视频 | 天堂在线中文无弹窗全文阅读 | 丝瓜视频黄瓜视频 |