SpringBoot整合Jsp和Thymeleaf (附工程)

來源:互聯網
上載者:User

標籤:格式   相關配置   main   VID   rop   web.xml   osi   jpa   編號   

前言

本篇文章主要講述SpringBoot整合Jsp以及SpringBoot整合Thymeleaf,實現一個簡單的使用者增刪改查樣本工程。事先說明,這兩個是單獨整合的,也就是兩個工程。如需其中一個,只需看相應部分的介紹即可。若需工程原始碼,可以直接跳到底部,通過連結下載工程代碼。

SpringBoot整合Jsp開發準備

環境要求
JDK: 1.7或以上
SQL: MySql

這裡我們需要在mysql中建立一張使用者表,用於儲存使用者的資訊。
資料庫指令碼如下:

CREATE TABLE `t_user` (  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',  `name` varchar(10) DEFAULT NULL COMMENT '姓名',  `age` int(2) DEFAULT NULL COMMENT '年齡',  `password` varchar(24) NOT NULL COMMENT '密碼',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8

建立好表之後,我們再來建立工程。
我們的這個工程是通過maven建立一個普通的web工程。
建立好工程之後,我們需要下載相應的jar包,然後再來進行相關的開發。
這些jar包我們在pom.xml檔案中添加springBoot和Jsp相關的jar即可。
相關的注釋以及寫在其中了,這裡就不在過多講述了。
Maven依賴如下:

 <dependencies>        <!-- Spring Boot Web 依賴 核心 -->        <dependency>            <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <!-- Spring Boot 熱部署 class檔案之後會自動重啟 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-devtools</artifactId>            <optional>true</optional>        </dependency>        <!-- Spring Boot Test 依賴 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>                <!-- Spring Boot JPA -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>                  <!-- Spring Boot Mybatis 依賴 -->        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>${mybatis-spring-boot}</version>        </dependency>                <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>                <!--fastjson 相關jar -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>fastjson</artifactId>            <version>${fastjson}</version>        </dependency>                        <!--JSP 依賴  -->        <!-- servlet依賴. -->          <dependency>              <groupId>javax.servlet</groupId>              <artifactId>jstl</artifactId>        </dependency>                  <dependency>              <groupId>javax.servlet</groupId>              <artifactId>javax.servlet-api</artifactId>            <scope>provided</scope>          </dependency>                 <!-- tomcat的支援.-->        <dependency>            <groupId>org.apache.tomcat.embed</groupId>            <artifactId>tomcat-embed-jasper</artifactId>            <scope>provided</scope>        </dependency>      </dependencies>

相關的Jar包下載完畢之後,我們再來確認項目的工程結構。
首先是後台相關包說明:

src/main/javacom.pancm.web - Controller 層com.pancm.dao - 資料操作層 DAOcom.pancm.pojo- 實體類com.pancm.service - 商務邏輯層Application - 應用啟動類src/main/resourcesapplication.properties - 應用設定檔,應用啟動會自動讀取配置

前端的相關檔案存放說明:

src/main/webappWEB-INF - web.xml web相關的核心配置WEB-INF/jsp - JSP檔案的存放路徑

整體工程結構圖:

工程結構確認之後,我們再來添加相應的配置。
只需在application.properties 添加相應的配置即可。
資料來源的配置和之前的差不多,需要注意的是Jsp的相關配置。
由於springBoot預設的支援的模版是Thymeleaf,所以這裡我們需要進行相應的更改。

配置如下:

?## 編碼banner.charset=UTF-8server.tomcat.uri-encoding=UTF-8spring.http.encoding.charset=UTF-8spring.http.encoding.enabled=truespring.http.encoding.force=truespring.messages.encoding=UTF-8## 連接埠server.port=8088## 資料來源spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver## JSP配置# 頁面預設首碼spring.mvc.view.prefix=/WEB-INF/jsp/# 響應頁面預設尾碼spring.mvc.view.suffix=.jsp
代碼編寫

其實這裡的代碼和之前文章講述的基本一致,唯一有點區別的是,這裡我是用JPA實現對資料庫進行操作的(也就是順便說下JPA這個架構的使用)。

首先是實體類,這裡因為用了JPA,所以和之前的有點不同,添加了一些註解。
Entity:表示這是個實體類。
Table:該實體類映射的資料表名。
Column:指定該欄位的屬性,nullable 表示是否非空,unique 表示是否是唯一。

那麼實體類的代碼如下:

@Entity@Table(name = "t_user")public class User {         /** 編號 */     @Id     @GeneratedValue     private Long id;     /** 姓名 */     @Column(nullable = false, unique = true)     private String name;     /** 密碼*/     @Column(nullable = false)     private String password;     /** 年齡 */     @Column(nullable = false)     private Integer age;        //getter和setter略}    

由於用的是JPA,dao層這塊只需繼承JpaRepository該類即可,需要指定實體類和主鍵類型。
dao層代碼如下:

@Mapperpublic interface UserDao extends JpaRepository<User, Long>{    }

業務層這塊和之前一樣調用即可,雖然用的是JPA,但是方法也是很簡單的,新增和修改就用save,刪除就是delete,findOne就是通過ID尋找,findAll就是查詢所有等等。

services代碼如下:

@Servicepublic class UserServiceImpl implements UserService {    @Autowired    private UserDao userDao;            @Override    public boolean addUser(User user) {        boolean flag=false;        try{            userDao.save(user);            flag=true;        }catch(Exception e){            System.out.println("新增失敗!");            e.printStackTrace();        }        return flag;    }    @Override    public boolean updateUser(User user) {        boolean flag=false;        try{            userDao.save(user);            flag=true;        }catch(Exception e){            System.out.println("修改失敗!");            e.printStackTrace();        }        return flag;    }    @Override    public boolean deleteUser(Long id) {        boolean flag=false;        try{            userDao.delete(id);            flag=true;        }catch(Exception e){            System.out.println("刪除失敗!");            e.printStackTrace();        }        return flag;    }    @Override    public User findUserById(Long id) {        return userDao.findOne(id);    }    @Override    public List<User> findAll() {        return userDao.findAll();    }}

到了控制層這塊,這裡提供還是提供介面給Jsp進行調用,不過這裡類的註解就不能用之前的RestController這個註解,這個註解以json的格式返回資料,但是我們有時返回的時候需要跳轉介面,所以應該使用Controller這個註解。如果想在某個方法中返回的資料格式是json的話,在該方法上加上ResponseBody這個註解即可。

控制層代碼如下:

@Controllerpublic class UserRestController {        @Autowired        private UserService userService;         @RequestMapping("/hello")        public String hello() {            return "hello";        }                @RequestMapping("/")        public String index() {            return "redirect:/list";        }                        @RequestMapping("/list")        public String list(Model model) {            System.out.println("查詢所有");            List<User> users=userService.findAll();            model.addAttribute("users", users);            return "user/list";        }        @RequestMapping("/toAdd")        public String toAdd() {            return "user/userAdd";        }        @RequestMapping("/add")        public String add(User user) {            userService.addUser(user);            return "redirect:/list";        }        @RequestMapping("/toEdit")        public String toEdit(Model model,Long id) {            User user=userService.findUserById(id);            model.addAttribute("user", user);            return "user/userEdit";        }        @RequestMapping("/edit")        public String edit(User user) {            userService.updateUser(user);            return "redirect:/list";        }        @RequestMapping("/toDelete")        public String delete(Long id) {            userService.deleteUser(id);            return "redirect:/list";        }}
功能測試

後端代碼介紹就到這裡了,至於前端JSP的代碼就不在多說了(主要原因是介面寫得太醜了...),我們直接啟動項目,查看效果。
啟動項目,在瀏覽器上輸入:http://localhost:8088/list
主介面:

添加一條資料之後的介面:

其它的修改和刪除也能實現,這裡就在一一不貼圖了。
springBoot整合 Jsp到這就結束了。

SringBoot整合Thymeleaf

該工程參考:http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html

Thymeleaf介紹

Thymeleaf是個模板引擎,可以用於Web與非Web應用,它可以XML/XHTML/HTML5, JavaScript, CSS ,甚至文字檔。

Thymeleaf的使用

Thymeleaf這塊個人使用不太熟練,這個也不是本篇文章主要講述的內容,詳細的可以查看官方文檔。
https://www.thymeleaf.org/documentation.html

開發準備

基本和上面的SringBoot整合Jsp差不多,這裡就不再贅述了。

由於SpringBoot預設的模版引擎就是Thymeleaf,所以Maven 依賴這塊只需要在原先的springBoot項目添加Thymeleaf的依賴就行。

  <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

application.properties 配置這塊,可以和之前的項目基本一致,需要注意的也只有spring.thymeleaf.cache配置,為false的時候是關閉Thymeleaf的緩衝,更改介面之後會自動重啟然後生效。

SringBoot整合Thymeleaf和SringBoot整合Jsp有個比較大的不同是,Thymeleaf的資源檔是放在src/main/resources目錄下,Jsp的是放在src/main/webapp目錄下。其中resources目錄下的的static目錄用於放置靜態內容,比如css、js、jpg圖片等。templates目錄用於放置項目使用的頁面模板,也就是.html檔案。

它的項目結構圖如下:

代碼基本和SringBoot整合Jsp一致,這裡就不在贅述了。

功能測試

啟動該項目,在瀏覽器輸入:http://localhost:8085
主介面:

修改使用者資料之後的:

其它的功能也是可以實現的,這裡就不再過多貼圖了。
springBoot整合 Thymeleaf到這就結束了。

其它

關於SpringBoot整合Jsp和Thymeleaf 到這裡就結束了。
SpringBoot整合Jsp的項目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-jsp-jpa
SpringBoot整合Thymeleaf的項目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-thymeleaf

原創不易,如果感覺不錯,希望給個推薦!您的支援是我寫作的最大動力!
著作權聲明:
虛無境
部落格園出處:http://www.cnblogs.com/xuwujing
CSDN出處:http://blog.csdn.net/qazwsxpcm    
個人部落格出處:http://www.panchengming.com

SpringBoot整合Jsp和Thymeleaf (附工程)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.