SSM集成Thymeleaf


SSM整合Thymeleaf

目前很多后端技術棧采用Spring+SpringMVC+MyBatis的項目,其模板引擎大多使用JSP。基於現在前后端分離趨勢,我們使用Thymeleaf這個模板引擎和SSM框架配合。但是Thymeleaf不算是真正意義上的前后端分離。

創建項目

  1. 創建一個maven項目,在例子中,我們創建一個名為SSMAndThymeleaf的項目。

  2. 引入全部依賴

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

        <modelVersion>4.0.0</modelVersion>
        <groupId>com.wang</groupId>
        <artifactId>SSMAndThymeleaf</artifactId>
        <version>1.0-SNAPSHOT</version>
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>
        <dependencies>
            <!--導入spring,下面幾個為spring和springmvc需要的依賴-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.4</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <!--導入springmvc-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>

            <!--導入mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
      <!--mysql數據庫的依賴-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.17</version>
            </dependency>
      <!-- 例子中使用的數據庫連接池是C3P0,當然,你也可以選擇Druid數據庫連接池-->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>

            <!--導入Thymeleaf模板引擎 -->
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf-spring5</artifactId>
                <version>3.0.9.RELEASE</version>
            </dependency>
            <!-- servlet api-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf</artifactId>
                <version>3.0.11.RELEASE</version>
            </dependency>

            <!--導入jackson注解-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.9.8</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.8</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.9.8</version>
            </dependency>
        </dependencies>
    </project>
  3. 為項目添加web框架支持。

Spring+SpringMVC+MyBatis的配置文件

  1. Spring的配置文件

    主要是掃描數據持久層和業務層,然后數據庫的相關配置。

    <?xml version="1.0" encoding="utf-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd"
    >


        <!--掃描dao層-->
        <context:component-scan base-package="com.wang.dao"/>
        <context:component-scan base-package="com.wang.service"/>

        <!--加載properties文件,這里的properties文件是數據源配置需要的內容-->
        <context:property-placeholder location="classpath:properties/db.properties"/>

        <!--配置數據源-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <!-- 初始連接池大小 -->
            <property name="initialPoolSize" value="10"/>
            <!-- 連接池中連接最小個數 -->
            <property name="minPoolSize" value="5"/>
            <property name="maxPoolSize" value="20"/>
        </bean>

        <!--配置SqlSession工廠對象,MyBatis配置SqlSessionFactory,Spring中將它封裝成了一個Bean-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!--MyBatis配置文件的位置-->
            <property name="configLocation" value="classpath:mybatis/mybatis-SqlMapConfig.xml"/>
            <!--MyBatis映射文件的位置-->
            <property name="mapperLocations" value="classpath*:mapper/*Dao.xml"/>
        </bean>

        <!--加載dao的接口對象,這一配置是為了讓他能通過反射創建mapper對象-->
        <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.wang.dao"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
    </beans>
  2. SpringMVC的配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"
    >


        <!--掃描controller層注解-->
        <context:component-scan base-package="com.wang"/>
     
        <!--配置模板引擎-->
        <bean id="springResourceTemplateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
            <property name="prefix" value="/WEB-INF/templates/"/>
            <property name="suffix" value=".html"/>
            <!--解決頁面的中文亂碼-->
            <property name="characterEncoding" value="UTF-8"/>
            <property name="order" value="1"/>
            <property name="templateMode" value="HTML5"/>
            <property name="cacheable" value="false"/>
        </bean>
        <bean id="springTemplateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver" ref="springResourceTemplateResolver"/>
        </bean>
        
     <!-- 配置thymeleaf視圖解析器 -->
        <bean id="thymeleafViewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
            <property name="templateEngine" ref="springTemplateEngine"/>
            <property name="characterEncoding" value="UTF-8"/>
        </bean>

     <!--開啟注解驅動-->
        <mvc:annotation-driven />
    </beans>
  3. MyBatis的配置文件

    其實MyBatis的配置在Spring中都已經配置完,即使我們使用事務,也是使用Spring的事務處理,所以這里只需要配置一點點東西。

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">

    <configuration>
        <!--掃描pojo對象,起個別名-->
        <typeAliases>
            <package name="com.wang.model"/>
        </typeAliases>
    </configuration>

數據庫內容

數據庫內容
數據庫內容

dao層+service層+controller層

  1. 創建一個實體類(Country)

    package com.wang.model;

    /**
     * @author wya
     * @version 1.0
     * @school hhu
     * @date 2022/3/21 19:10
     */

    public class Country {
        private Integer id;
        
        private String countryName;
        
        private String countryCode;
        
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getCountryName() {
            return countryName;
        }

        public void setCountryName(String countryName) {
            this.countryName = countryName;
        }

        public String getCountryCode() {
            return countryCode;
        }

        public void setCountryCode(String countryCode) {
            this.countryCode = countryCode;
        }

    }
  2. 創建dao接口

    import com.wang.model.Country;
    import org.apache.ibatis.annotations.Param;
    import org.springframework.stereotype.Repository;

    /**
     * @author wya
     * @version 1.0
     * @school hhu
     * @date 2022/3/21 19:11
     */

    @Repository
    public interface CountryDao {
        
        Country selectACountry(@Param("countryId")int id);

    }
  3. 創建service接口

    package com.wang.service;

    import com.wang.model.Country;

    /**
     * @author wya
     * @version 1.0
     * @school hhu
     * @date 2022/3/21 19:11
     */

    public interface CountryService {

        Country getCountryById(int id);

    }
  4. 實現service接口

    package com.wang.service.impl;

    import com.wang.dao.CountryDao;
    import com.wang.model.Country;
    import com.wang.service.CountryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    /**
     * @author wya
     * @version 1.0
     * @school hhu
     * @date 2022/3/21 19:11
     */

    @Service
    public class CountryServiceImpl implements CountryService {

        @Autowired
        CountryDao countryDao;

        @Override
        public Country getCountryById(int id) {
            /**
             * 這里是業務層的操作,我們這里省略
             */

            return countryDao.selectACountry(id);
        }
    }

  5. 創建controller

    package com.wang.controller;

    import com.wang.model.Country;
    import com.wang.service.CountryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;

    /**
     * @author wya
     * @version 1.0
     * @school hhu
     * @date 2022/3/21 19:09
     */

    @Controller
    public class CountryController {

        @Autowired
        CountryService countryService;

        @RequestMapping("hello")
        public String test(Model model) {
            Country country = countryService.getCountryById(1);
            model.addAttribute("country",country);
            return "hello";
        }

    }

映射文件

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--定義為當前的命名空間-->
<mapper namespace="com.wang.dao.CountryDao">
    <select id="selectACountry" resultType="com.wang.model.Country">
        select * from country where id = #{countryId};
    </select>

</mapper>

前端簡單頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<center><h1>顯示成功!!!</h1>
國家名字: <p th:text="${country.countryName}"></p>
國家ID:  <p th:text="${country.countryCode}"></p>
</body>
</html>

配置tomcat,運行顯示

總體項目架構

補充

后續需要其他依賴的再加入即可,像文件的上傳下載依賴等。

有問題請聯系我。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM