上篇文章介紹了Spring boot初級教程:spring boot(一):入門篇,方便大家快速入門、了解實踐Spring boot特性;本篇文章接著上篇內容繼續為大家介紹spring boot的其它特性(有些未必是spring boot體系桟的功能,但是是spring特別推薦的一些開源技術本文也會介紹),對了這里只是一個大概的介紹,特別詳細的使用我們會在其它的文章中來展開說明。
web開發
spring boot web開發非常的簡單,其中包括常用的json輸出、filters、property、log等
json 接口開發
在以前的spring 開發的時候需要我們提供json接口的時候需要做那些配置呢
- 添加 jackjson 等相關jar包
- 配置spring controller掃描
- 對接的方法添加@ResponseBody
就這樣我們會經常由于配置錯誤,導致406錯誤等等,spring boot如何做呢,只需要類添加 @RestController
即可,默認類中的方法都會以json的格式返回
@RestController
public class HelloWorldController {
@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方法
- 添加
@Configurationz
注解,將自定義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
}
}
}
自定義Property
在web開發的過程中,我經常需要自定義一些配置文件,如何使用呢
配置在application.properties中
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方法
}
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
主要是指定生成表名的存儲引擎為InneoDB
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", "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,主從分離等等,這里就不詳細講了
thymeleaf模板
Spring boot 推薦使用來代替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與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中的
文章列表