②SpringBoot之Web綜合開發

Spring boot初級教程 :《SpringBoot入門教學篇①》,方便你們快速入門、瞭解實踐Spring boot特性,本文介紹springBoot的web開發css

web開發
spring boot web開發很是的簡單,其中包括經常使用的json輸出、filters、property、log等。
json 接口開發html

在之前的spring 開發的時候須要咱們提供json接口的時候須要作那些配置呢?
添加 jackjson 等相關jar包
配置spring controller掃描
對接的方法添加@ResponseBody

就這樣咱們會常常因爲配置錯誤,致使406錯誤等等,spring boot如何作呢,只須要類添加 @RestController 便可,默認類中的方法都會以json的格式返回。
自定義Filter前端

咱們經常在項目中會使用filters用於錄調用日誌、排除有XSS威脅的字符、執行權限驗證等等。Spring Boot自動添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,而且咱們能夠自定義Filter。 java

兩個步驟:mysql

實現Filter接口,實現Filter方法
添加@Configurationz 註解,將自定義Filter加入過濾鏈

代碼示例:web

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@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 {
                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
            }

        }
}

自定義Propertyspring

在web開發的過程當中,我常常須要自定義一些配置文件,如何使用呢?sql

配置在application.properties中。數據庫

com.bosssoft.title=springBoot測試
com.bosssoft.description=測試配置文件

自定義配置類apache

import org.springframework.beans.factory.annotation.Value;

public class BossProperties {

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    
    
}

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中使用。

一、添加相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>

二、添加配置文件

spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=123456
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參數的做用主要用於:自動建立|更新|驗證數據庫表結構,有四個值:

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

dialect 主要是指定生成表名的存儲引擎爲InneoDB show-sql 是否打印出自動生產的SQL,方便調試的時候查看。

三、添加實體類和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;

    public User() {
        super();
    }
    public User(String email, String nickName, String passWord, String userName, String regTime) {
        super();
        this.email = email;
        this.nickName = nickName;
        this.passWord = passWord;
        this.userName = userName;
        this.regTime = regTime;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getRegTime() {
        return regTime;
    }
    public void setRegTime(String regTime) {
        this.regTime = regTime;
    }

}

dao只要繼承JpaRepository類就能夠,幾乎能夠不用寫方法,還有一個特別有尿性的功能很是贊,就是能夠根據方法名來自動的生產SQL,好比findByUserName 會自動生產一個以 userName 爲參數的查詢方法,好比 findAlll 自動會查詢表裏面的全部數據,好比自動分頁等等。
Entity中不映射成列的字段得加@Transient 註解,不加註解也會映射成列。

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

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

四、測試

@RunWith(SpringRunner.class)
@SpringBootTest
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模板究竟是什麼來頭呢,下面來聊聊。

Thymeleaf 介紹

Thymeleaf是一款用於渲染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>

WebJars

WebJars是一個很神奇的東西,可讓你們以jar包的形式來使用前端的各類框架、組件。

什麼是WebJars

什麼是WebJars?WebJars是將客戶端(瀏覽器)資源(JavaScript,Css等)打成jar包文件,以對資源進行統一依賴管理。WebJars的jar包部署在Maven中央倉庫上。

爲何使用

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

如何使用

一、 WebJars主官網 查找對於的組件,好比bootstrap:

<dependency>
     <groupId>org.webjars.bower</groupId>
     <artifactId>bootstrap</artifactId>
     <version>3.0.3</version>
</dependency>

二、頁面引入

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

就能夠正常使用了!

相關文章
相關標籤/搜索