1. 程式人生 > >SpringBoot整合Jsp和Thymeleaf (附工程)

SpringBoot整合Jsp和Thymeleaf (附工程)

curd scrip implement osi 數據表 del setter esp myba

前言

本篇文章主要講述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/java
com.pancm.web - Controller 層
com.pancm.dao - 數據操作層 DAO
com.pancm.pojo- 實體類
com.pancm.service - 業務邏輯層
Application - 應用啟動類

src/main/resources
application.properties - 應用配置文件,應用啟動會自動讀取配置

前端的相關文件存放說明:

src/main/webapp
WEB-INF - web.xml web相關的核心配置
WEB-INF/jsp - JSP文件的存放路徑

整體工程結構圖:
技術分享圖片

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

配置如下:

?## 編碼
banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
## 端口
server.port=8088

## 數據源
spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.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層代碼如下:

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

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

services代碼如下:

@Service
public 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這個註解即可。

控制層代碼如下:

@Controller
public 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 (附工程)