Spring & Spring MVC & Hibernate 整合备忘

以下为此三种框架整合配置的详细备注,以及部分问题备忘
项目结构和配置文件可访问 Github 查看

1. pom.xml

尽量使用 Maven 管理项目依赖以减少包引入时的麻烦,以及避免跨开发工具问题

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ecollaboration</groupId>
    <artifactId>ecollaboration_v1</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>ecollaboration_v1 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- 避免 IDEA 重置编译配置为 1.5 而提醒版本过时 -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <junit.version>4.12</junit.version>
        <spring.version>4.3.3.RELEASE</spring.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <jackson.version>2.8.6</jackson.version>
        <commons-fileupload.version>1.3.2</commons-fileupload.version>
        <servlet.version>3.1.0</servlet.version>
        <mysql.jdbc.version>5.1.21</mysql.jdbc.version>
        <aspectj.version>1.8.9</aspectj.version>
    </properties>
    <dependencies>
    
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <!-- Spring 注:引入这一依赖后,spring-context, spring-core 等包会被 Maven 基于依赖管理引入,Spring 中各个包的依赖关系详见本文参考「1. Spring 各 jar 包的作用及依赖关系」 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Mysql JDBC Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.jdbc.version}</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- Jackson 注:引入 jackson-databind 以便 Spring mvc 对 json、html 等不同返回类型进行配置 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- Common fileupload 注:用于 Spring mvc 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>

        <!-- Servlet API 注:需要使用到 Servlet api 时需要引入这一依赖 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
        </dependency>

        <!-- AspectJ 注:Spring 中使用基于 AspectJ 的声明式 xml 事务配置方式 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>ecollaboration_v1</finalName>
    </build>
</project>

2. web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!-- Spring 容器初始化配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 此配置指定 Spring 的配置文件为 application-context.xml -->
        <param-value>classpath:application-context.xml</param-value>
    </context-param>

    <!-- 强制 UTF-8 编码,避免中文乱码问题。注:如果按照此配置开头的 web-app_2_3.dtd 规范,filter 配置项必须位于 context-param 和 listener 之间。详情见参考 14.「The content of element type "web-app" must match 问题之解决办法」 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>

    <!-- 使用此配置避免用 new ClassPathXmlApplicationContext("") 的方式得到 Spring 上下文-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring MVC Servlet -->
    <servlet>
        <servlet-name>spring-mvc-servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        
        <!-- 进行此配置指定 spring mvc 的配置文件为 spring-mvc.xml,否则会默认寻找 xxx-servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc-servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3. application-context.xml

文件名与 web.xml 第 12 行匹配

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

    <!-- 引用 jdbc.properties 文件中的配置,该配置会用于 dataSource bean 中 -->
    <context:property-placeholder location="classpath:properties/jdbc.properties" />

    <!-- 添加 aspectJ 支持 -->
    <aop:aspectj-autoproxy/>

    <!-- 配置 Spring 容器扫描的路径,这里排除需要载入 Spring MVC 上下文而使用的注解 @Controller。可见参考 15.「spring mvc 和 spring 各自扫描自己的注解不要相互混淆,以及参考 20.「context:exclude-filter 与 context:include-filter」-->
    <context:component-scan base-package="com.ecollaboration">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 配置 dataSource bean,这里的 ${jdbc.url} 等对应第 17 行 jdbc.properties 文件中的键名 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!-- 配置 sessionFactory bean,这里用到 dataSource bean -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 进行部分 hibernate 配置 -->
        <property name="hibernateProperties">
            <props>
                <!-- 是否打印执行的 SQL 语句 -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 是否格式化 SQL 语句 -->
                <prop key="hibernate.format_sql">true</prop>
                <!-- 数据库方言 -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <!-- 自动创建 | 更新 | 验证数据库表结构,若这里配置的值为 create,则会在执行 hibernate 表操作时重建表结构( 表会被清空 ) -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 添加此配置以使用 sessionFactory.getCurrentSession() 得到一个 session -->
                <prop key="current_session_context_class">thread</prop>
                <!-- 添加此配置将事务管理交给 Spring,即无需再写 session.beginTransaction() 等事务管理和连接资源关闭代码。参见参考 17.「current_session_context_class」 -->
                <prop key="hibernate.current_session_context_class">
                    org.springframework.orm.hibernate4.SpringSessionContext
                </prop>
            </props>
        </property>

        <!-- 使用配置文件的方式 -->
        <property name="mappingResources">
            <list>
                <!-- 引入实体配置 -->
                <value>hibernates/UserEntity.hbm.xml</value>
            </list>
        </property>

        <!-- 使用注解的方式,确定所需扫描的注解所在包的路径,若仅使用配置的方式,可以注释这一配置 -->
        <!-- <property name="packagesToScan">
            <list>
                <value>com.ecollaboration.entities</value>
            </list>
        </property> -->
    </bean>
    
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- 配置 AOP Advice -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 添加配置使得符合以下条件的方法会被织入事务管理切面 -->
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="list*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置 AOP 切入点,这里使用 AspectJ 的事务配置方式,参见参考 18.「aop:aspectj-autoproxy 作用」,此处的 poincut 属性需按照实际情况配置 -->
    <aop:config proxy-target-class="true">
        <aop:advisor pointcut="execution(public * com.ecollaboration.services.*Service.*(..))" advice-ref="txAdvice"/>
    </aop:config>
</beans>

4. jdbc.properties

文件名与 application-context.xml 第 17 行匹配

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/ecollaboration?characterEncoding=UTF-8
jdbc.username=dbusername
jdbc.password=dbpassword

5. spring-mvc.xml

文件名与 web.xml 第 46 行匹配

<?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:mvc="http://www.springframework.org/schema/mvc"
       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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 指定 Spring MVC 扫描含有如 @Controller 等注解的包的路径,一般为项目控制器所在包的路径。进行这一配置后无需再写入 <context:component-config />。有关 component-scan 的内容可以参见参考 13.「Spring 注解 @Component、@Repository、@Service、@Controller 区别」。这里使用 include-filter 使得只有含有 @Controller 注解的控制器 bean 会使用 Spring mvc 的上下文,参见参考 19.「在使用 spring mvc 时... @Transactional 声明的事务不起作用」。-->
    <context:component-scan base-package="com.ecollaboration.controllers">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 指定视图文件后缀和所在的路径,在控制器的方法中返回的字符串值会表示这一路径下的同名文件 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 此配置使得 @ResponseBody 等注解可以生效 -->
    <mvc:annotation-driven/>

    <!-- 此配置使得控制器可以根据返回类型返回 json 数据或视图文件 -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

        <property name="order" value="1"/>

        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
            </list>
        </property>

        <property name="contentNegotiationManager">
            <bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
                <property name="favorParameter" value="true"/>
                <property name="parameterName" value="format"/>
                <property name="ignoreAcceptHeader" value="false"/>
                <property name="mediaTypes">
                    <value>
                        json=application/json
                        xml=application/xml
                        html=text/html
                    </value>
                </property>
                <property name="defaultContentType" value="text/html"/>
            </bean>
        </property>

    </bean>

    <!-- 添加 Spring mvc 的文件上传支持 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    <!-- 添加此配置用于排除 Spring mvc 对静态资源文件的处理。有关静态资源路径问题参见参考 31.「Spring mvc 访问静态资源的三种方式」 -->
    <mvc:resources mapping="/resources/**" location="/resources/"/>

    <!-- 添加拦截器 -->
    <mvc:interceptors>
        <!-- 全局拦截器,会对所有的请求拦截 -->
        <bean id="normalInterceptor" class="com.ecollaboration.interceptors.NormalInterceptor"/>

        <!-- 局部拦截器,只拦截与 mapping 匹配的请求 -->
        <mvc:interceptor>
            <mvc:mapping path="/hello/register"/>
            <mvc:mapping path="/hello/index/*"/>
            <bean id="testInterceptor" class="com.ecollaboration.interceptors.TestInterceptor"/>
        </mvc:interceptor>

    </mvc:interceptors>
</beans>

6. 问题备忘

6.1 JSP 中无法使用 EL 表达式

web.xml 中,如果配置信息为:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>  
  
</web-app> 

则表示其采用 JSP 1.2,EL 表达式默认关闭,此时需要在 .jsp 中添加 <% @page isELIgnored="false" %>
或采用 JSP 2.0,即将配置信息改为:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app id="MyApp" version="2.4"   
        xmlns="http://java.sun.com/xml/ns/j2ee"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  

</web-app>  

6.2 /*/** 的区别

/* 中的通配符 * 会止于分隔符 /,而 /** 则不会。如 <url-pattern>/resources/*</url-pattern> 无法匹配 /resources/images/xxx.jpg,而只能匹配 /resources/xxx.jpg
换做 <url-pattern>/resources/**</url-pattern> 可以解决这一问题。

6.3 路径问题

在 Java 项目中,/path/to/xxx 表示以 webapp 为起点的路径;path/to/xxx 表示以项目根目录为起点的路径;classpath:path/to/xxx 标识以 classpath 为起点的路径;
注:也可以使用 this.getClass().getClassLoader().getResource("") 得到类对于系统的绝对路径进而得到所需资源的路径。

6.4 classpath:classpath*: 区别

classpath*: 可以从多个 jar 文件中加载相同的文件,而 classpath: 只会加载找到的第一个文件。如引入的两个 jar 包都存在 com.a 下的 xx.xml 文件,使用 classpath: 只会加载找到的第一个文件,而 classpath*: 则会加载全部。

6.5 class path resource [beans.xml] cannot be opened because it does not exist 报错解决方法

application-context.xml 配置中,关于 sessionFactory 的配置中,其属性 mappingResource 不能加入 classpath:( 默认即为 classpath 下的文件 ),也不能使用通配符。

<property name="mappingResources">
    <list>
        <!-- 引入实体配置 -->
        <value>hibernates/UserEntity.hbm.xml</value>
        
        <!-- 这里不能写成 -->
        <!-- <value>hibernates/*.hbm.xml</value> -->
        <!-- 也不能写成 -->
        <!-- <value>classpath:hibernates/UserEntity.hbm.xml</value> -->
    </list>
</property>

6.6 Could not obtain transaction-synchronized Session for current thread 报错解决方法

《Spring & Spring MVC & Hibernate 整合备忘》

如果不使用 Spring 的事务管理机制,且使用 session.getCurrentSession() 时,会出现如上图所示错误,此时需要对 application-context (Spring 配置文件)进行更改( 参见 application-context 第 50 行 ):

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        
    <!-- ... 其他配置 -->    

    <property name="hibernateProperties">
        <props>
            <!-- ... 其他配置 -->
                
            <prop key="current_session_context_class">thread</prop>
            <prop key="hibernate.current_session_context_class">
                org.springframework.orm.hibernate4.SpringSessionContext
            </prop>

            <!-- ... 其他配置 -->
        </props>
    </property>

    <!-- ... 其他配置 -->
</bean>

并添加配置将事务管理交给 Spring( 参见 application-context 第 90 行 ):

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
    </tx:attributes>
</tx:advice>

<aop:config proxy-target-class="true">
    <!-- 与具体包结构有关 -->
    <aop:advisor pointcut="execution(public * com.*(..))" advice-ref="txAdvice"/>
</aop:config>

注:需要注意 aop:advisorpointcut 属性所覆盖的类与方法,如果操作 session 的方法不在此包含内,则仍会报错。
注:当然也可以使用 session.openSession() 并通过 Hibernate 的事务管理方式组织代码。

6.7 Spring MVC 路由失效问题

有时可能出现:在配置了 @Controller 后,访问该控制器对应的 URL 时,返回 404 错误。此时需要检查 web.xml 中是否添加了 welcome-file-list,如下:

<welcome-file-list>  
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file> 
</welcome-file-list> 

此时,对某一 url 的访问会等同于访问该路径所对应文件夹下的 index.htmlindex.jsp 文件,如访问 localhost/foo 等同于访问 localhost/foo/index.htmllocalhost/foo/index.jsp( 依次检测这两个文件是否存在 )。因而需要在 spring-mvc.xml ( Spring mvc 配置文件 )中添加如下配置:

<mvc:default-servlet-handler />

6.8 context:property-placeholder 导入多个 .properties 配置文件

由于 Spring 容器允许最多定义一个 placeholder,加入多个文件会忽略。而由于 IDE 不会进行这一判断,因而会出现 IDE 中没有警告提示,但运行时却报错的情况。

这时我们可以使用通配符解决引入多个配置文件的需求:

<context:property-placeholder location="classpath*:*.properties"/> 

6.9 运行出现警告 WARNING: Exception encountered during context initialization - cancelling refresh attempt

发生这一问题可能是由于在进行代码迁移时,tomcat 和编译器的 jdk 指定版本不同,导致前者无法识别后者编译的的字节码文件。只需将二者保持一致即可,详情可参考 Stackoverflow

7. 扩展 – 添加 Thymeleaf 模板引擎支持

若要在项目中使用 Thymeleaf 模板引擎,需要对之前进行的配置进行以下修改

7.1 修改 pom.xml 以增加 Thymeleaf 支持

<!-- 添加 thymeleaf-spring 依赖,会自动引入 thymeleaf 包 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>3.0.3.RELEASE</version>
</dependency>

<!-- 引入 Thymeleaf layout dialect 以使用 layout:fragment 等组织视图布局。详情见参考 33. 「Thymeleaf Layout Dialect」 -->
<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.1.2</version>
</dependency>

7.2 修改 spring-mvc.xml 以改变 View Resolver

这里需要将 spring-mvc.xml 第 16 – 19 行注释,并添加 ThymeleafViewResolver 的相应配置:

<!-- 注释这一段 -->

<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
    <!--<property name="prefix" value="/WEB-INF/views/"/>-->
    <!--<property name="suffix" value=".jsp"/>-->
<!--</bean>-->

<!-- 添加 ThymeleafViewResolver -->

<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
    <!-- 配置视图所在文件路径,并指定视图的文件扩展名 -->
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".html"/>
    <property name="templateMode" value="HTML"/>
    <property name="characterEncoding" value="UTF-8"/>
    <!-- 禁用视图缓存,方便开发阶段调试 -->
    <property name="cacheable" value="false"/>
</bean>

<!-- 添加一个新的 bean,用于在使用 layout 组织视图布局时对 head 中的 css 和 javascript 标签有序组织 -->
<bean id="groupingStrategy" class="nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy"/>

<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver"/>
    <!-- 引入 Layout Dialect 以使用 layout 布局 -->
    <property name="additionalDialects">
        <set>
            <bean class="nz.net.ultraq.thymeleaf.LayoutDialect">
                <!-- 传入上面声明的 groupingStrategy bean -->
                <constructor-arg ref="groupingStrategy"/>
            </bean>
        </set>
    </property>
</bean>

<bean id="thymeleafViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine"/>
    <property name="characterEncoding" value="UTF-8"/>
</bean>

7.3 添加 Thymeleaf namespace 支持

由于 Thymeleaf 使用如 <p th:text=""></p> 的方式解析视图,若要开发工具能够支持 th:xxx 的代码提示,需要在 html 标签中加入声明:<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">,( 如需使用 layout 布局,还需加入 xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" ),此时 html 文件框架为:

<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

</body>
</html>

7.4 在 IDEA 中添加含有 th 命名空间声明的 .html 文件框架

由于开发工具 与 emmet 插件等自动生成的 .html 文件框架中不含上述声明,每次都要写入声明也比较麻烦,可以在开发工具中添加一个文件模板以避免重复工作,这里以 IDEA 为例:
File > Other Settings > Default Settings > Editor > File and Code Templates 中新建一个文件模板,如下图:

《Spring & Spring MVC & Hibernate 整合备忘》

7.5 Thymeleaf 资料参考

  1. thymeleaf使用详解 – 知乎专栏

  2. Thymeleaf 模板的使用 – 博客园

  3. ${}, *{}, #{}, @{}, ~{} 的区别 – stackoverflow

  4. 新一代Java模板引擎Thymeleaf – 天马营

  5. Thymeleaf Layout Dialect

参考

  1. Spring 各 jar 包的作用及依赖关系 – 博客园

  2. hibernate.hbm2ddl.auto配置详解 – 博客园

  3. Spring-mvc 解决EL表达式不能使用问题 – CSDN

  4. Spring: Difference of /* and / with regards to paths – stackoverflow

  5. Spring 中 property-placeholder 的使用与解析 – 博客园

  6. IDEA 新建 Spring 配置文件的方法 – CSDN

  7. SPRING4配置文件模板 – 博客园

  8. JAVA获取CLASSPATH路径

  9. Spring 加载 resource 时 classpath*: 与 classpath: 的区别 – CSDN

  10. SSM_config 配置 springmvc.xml 模板 – CSDN

  11. <context:component-scan>使用说明 – CSDN

  12. java.io.FileNotFoundException: class path resource beans.xml cannot be opened because it does not exist 解决方法 – CSDN

  13. Spring 注解 @Component、@Repository、@Service、@Controller 区别 – CSND

  14. The content of element type “web-app” must match 问题之解决办法 – CSDN

  15. spring mvc 和 spring 各自扫描自己的注解不要相互混淆 – 博客园

  16. context:component-scan 扫描使用上的容易忽略的 use-default-filters – iteye

  17. current_session_context_class – CSDN

  18. aop:aspectj-autoproxy 作用 – 360DOC

  19. 在使用 spring mvc 时,我使用了 @Service 这样的注解, 发现使用注解 @Transactional 声明的事务不起作用 – CSDN

  20. context:exclude-filter 与 context:include-filter – CSDN

  21. SpringMVC + Spring + Hibernate 整合 – 慕课网

  22. Spring 事务管理 – 慕课网

  23. @resource和@autowired的区别是什么 – CSDN

  24. SpringMVC4+thymeleaf3的一个简单实例(篇二:springMVC与thymeleaf的整合) – 博客园

  25. IntelliJ IDEA 2016.3 Help

  26. thymeleaf code completion not working intellij 14 – stackoverflow

  27. Intellij Idea: Thymeleaf namespace unknown

  28. SpringMVC4+thymeleaf3的一个简单实例(篇二:springMVC与thymeleaf的整合) – 博客园

  29. Spring MVC中使用Thymeleaf模板引擎 – 知乎专栏

  30. Spring 注解:@Repository、@Service、@Controller、@Autowired – CSDN

  31. Spring mvc 访问静态资源的三种方式 – CSDN

  32. thymeleaf 中文乱码问题 – CSDN

  33. Thymeleaf Layout Dialect – Gitbook

  34. spring中 context:property-placeholder 导入多个独立的配置文件

  35. WARNING: Exception encountered during context initialization – cancelling refresh attempt – Stackoverflow

    原文作者:dailybird
    原文地址: https://segmentfault.com/a/1190000008265825
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞