搜尋
首頁Javajava教程SpringBoot如何實現整合Jsp和Thymeleaf?

這篇文章帶給大家的內容是關於SpringBoot如何實現整合Jsp和Thymeleaf ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

前言

本篇文章主要講述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文件的存放路径

整體工程結構圖:
SpringBoot如何實現整合Jsp和Thymeleaf?

工程結構確認之後,我們再來新增對應的配置。
只需在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和Thymeleaf?

##新增一條資料之後的介面:


SpringBoot如何實現整合Jsp和Thymeleaf?

SpringBoot如何實現整合Jsp和Thymeleaf?

其它的修改和刪除也能實現,這裡就在一一不貼圖了。

springBoot整合 Jsp到這就結束了。

SringBoot整合Thymeleaf

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文件。

它的项目结构图如下:
SpringBoot如何實現整合Jsp和Thymeleaf?

代码基本和SringBoot整合Jsp一致,这里就不在赘述了。

功能测试

启动该项目,在浏览器输入:http://localhost:8085
主界面:
SpringBoot如何實現整合Jsp和Thymeleaf?

修改用户数据之后的:
SpringBoot如何實現整合Jsp和Thymeleaf?

SpringBoot如何實現整合Jsp和Thymeleaf?

其它的功能也是可以实现的,这里就不再过多贴图了。
springBoot整合 Thymeleaf到这就结束了。

SpringBoot整合Jsp和Thymeleaf

注:这个是后来新加的一个项目。
SpringBoot单独整合JspThymeleaf都还好,没出现什么问题。但是在一起之后,就有了改变,因为SpringBoot默认的模板引擎是Thymeleaf,加上JSP之后,JSP的模板引擎并不会生效。但是如果想用JSP模板,此时的禁用到Thymeleaf,虽然可以通过多态更改配置实现,但是感觉太过麻烦了。于是研究了一下,找到了共存的方法。

和前面来两个项目区别如下:

  1. 之前的JspThymeleaf配置都是在application.properties
    文件中,这里我将它们的配置改到代码中获取。

2.之前Thymeleaf相关文件是放在 src/main/resources 目录下,这里移动到WEB-INF目录下,和之前的jsp文件夹同级。

3.增加一个控制层,严格区分访问JspThymeleaf的路径。访问Jsp的路径前缀加上jsp,访问Thymeleaf前缀加上templates

那么新增的配置代码如下:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {
    
       @Bean
       public ViewResolver viewResolver() {
           InternalResourceViewResolver resolver = new InternalResourceViewResolver();
           resolver.setPrefix("/WEB-INF/");
           resolver.setSuffix(".jsp");
           resolver.setViewNames("jsp/*");
           resolver.setOrder(2);
           return resolver;
       }

       @Bean
       public ITemplateResolver templateResolver() {
           SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
           templateResolver.setTemplateMode("HTML5");
           templateResolver.setPrefix("/WEB-INF/");
           templateResolver.setSuffix(".html");
           templateResolver.setCharacterEncoding("utf-8");
           templateResolver.setCacheable(false);
           return templateResolver;
       }

       @Bean
       public SpringTemplateEngine templateEngine() {
           SpringTemplateEngine templateEngine = new SpringTemplateEngine();
           templateEngine.setTemplateResolver(templateResolver());
           return templateEngine;
       }

       @Bean
       public ThymeleafViewResolver viewResolverThymeLeaf() {
           ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
           viewResolver.setTemplateEngine(templateEngine());
           viewResolver.setCharacterEncoding("utf-8");
           viewResolver.setViewNames(new String[]{"thymeleaf/*"});
           viewResolver.setOrder(1);
           return viewResolver;
       }

       @Override
       public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
           configurer.enable();
       }

       @Override
       public void addResourceHandlers(ResourceHandlerRegistry registry) {
           super.addResourceHandlers(registry);
       }
}

项目的结构图如下:
SpringBoot如何實現整合Jsp和Thymeleaf?

功能测试

在浏览器输入:http://localhost:8089/list
查看Thymeleaf模板的界面
SpringBoot如何實現整合Jsp和Thymeleaf?

在浏览器输入:http://localhost:8089/list2
查看JSP模板的界面
SpringBoot如何實現整合Jsp和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
SpringBoot整合Jsp和Thymeleaf的项目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-jsp-thymeleaf

相关推荐:

SpringBoot整合Netty并使用Protobuf进行数据传输的实现过程

SpringBoot如何进行简单的打包部署?

以上是SpringBoot如何實現整合Jsp和Thymeleaf?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
是否有任何威脅或增強Java平台獨立性的新興技術?是否有任何威脅或增強Java平台獨立性的新興技術?Apr 24, 2025 am 12:11 AM

新興技術對Java的平台獨立性既有威脅也有增強。 1)雲計算和容器化技術如Docker增強了Java的平台獨立性,但需要優化以適應不同雲環境。 2)WebAssembly通過GraalVM編譯Java代碼,擴展了其平台獨立性,但需與其他語言競爭性能。

JVM的實現是什麼,它們都提供了相同的平台獨立性?JVM的實現是什麼,它們都提供了相同的平台獨立性?Apr 24, 2025 am 12:10 AM

不同JVM實現都能提供平台獨立性,但表現略有不同。 1.OracleHotSpot和OpenJDKJVM在平台獨立性上表現相似,但OpenJDK可能需額外配置。 2.IBMJ9JVM在特定操作系統上表現優化。 3.GraalVM支持多語言,需額外配置。 4.AzulZingJVM需特定平台調整。

平台獨立性如何降低發展成本和時間?平台獨立性如何降低發展成本和時間?Apr 24, 2025 am 12:08 AM

平台獨立性通過在多種操作系統上運行同一套代碼,降低開發成本和縮短開發時間。具體表現為:1.減少開發時間,只需維護一套代碼;2.降低維護成本,統一測試流程;3.快速迭代和團隊協作,簡化部署過程。

Java的平台獨立性如何促進代碼重用?Java的平台獨立性如何促進代碼重用?Apr 24, 2025 am 12:05 AM

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

您如何在Java應用程序中對平台特定問題進行故障排除?您如何在Java應用程序中對平台特定問題進行故障排除?Apr 24, 2025 am 12:04 AM

要解決Java應用程序中的平台特定問題,可以採取以下步驟:1.使用Java的System類查看系統屬性以了解運行環境。 2.利用File類或java.nio.file包處理文件路徑。 3.根據操作系統條件加載本地庫。 4.使用VisualVM或JProfiler優化跨平台性能。 5.通過Docker容器化確保測試環境與生產環境一致。 6.利用GitHubActions在多個平台上進行自動化測試。這些方法有助於有效地解決Java應用程序中的平台特定問題。

JVM中的類加載程序子系統如何促進平台獨立性?JVM中的類加載程序子系統如何促進平台獨立性?Apr 23, 2025 am 12:14 AM

類加載器通過統一的類文件格式、動態加載、雙親委派模型和平台無關的字節碼,確保Java程序在不同平台上的一致性和兼容性,實現平台獨立性。

Java編譯器會產生特定於平台的代碼嗎?解釋。Java編譯器會產生特定於平台的代碼嗎?解釋。Apr 23, 2025 am 12:09 AM

Java編譯器生成的代碼是平台無關的,但最終執行的代碼是平台特定的。 1.Java源代碼編譯成平台無關的字節碼。 2.JVM將字節碼轉換為特定平台的機器碼,確保跨平台運行但性能可能不同。

JVM如何處理不同操作系統的多線程?JVM如何處理不同操作系統的多線程?Apr 23, 2025 am 12:07 AM

多線程在現代編程中重要,因為它能提高程序的響應性和資源利用率,並處理複雜的並發任務。 JVM通過線程映射、調度機制和同步鎖機制,在不同操作系統上確保多線程的一致性和高效性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)