如下为此三种框架整合配置的详细备注,以及部分问题备忘
项目结构和配置文件可访问 Github 查看javascript
尽可能使用 Maven 管理项目依赖以减小包引入时的麻烦,以及避免跨开发工具问题css
<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>
<!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>
文件名与
web.xml
第 12 行匹配html
<?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>
文件名与
application-context.xml
第 17 行匹配java
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost/ecollaboration?characterEncoding=UTF-8 jdbc.username=dbusername jdbc.password=dbpassword
文件名与
web.xml
第 46 行匹配mysql
<?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>
在 web.xml
中,若是配置信息为:git
<!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,即将配置信息改成:github
<?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>
/*
与 /**
的区别/*
中的通配符 *
会止于分隔符 /
,而 /**
则不会。如 <url-pattern>/resources/*</url-pattern>
没法匹配 /resources/images/xxx.jpg
,而只能匹配 /resources/xxx.jpg
。
换作 <url-pattern>/resources/**</url-pattern>
能够解决这一问题。web
在 Java 项目中,/path/to/xxx
表示以 webapp
为起点的路径;path/to/xxx
表示以项目根目录为起点的路径;classpath:path/to/xxx
标识以 classpath 为起点的路径;
注:也可使用 this.getClass().getClassLoader().getResource("")
获得类对于系统的绝对路径进而获得所需资源的路径。spring
classpath:
和 classpath*:
区别classpath*:
能够从多个 jar 文件中加载相同的文件,而 classpath:
只会加载找到的第一个文件。如引入的两个 jar 包都存在 com.a
下的 xx.xml
文件,使用 classpath:
只会加载找到的第一个文件,而 classpath*:
则会加载所有。sql
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>
Could not obtain transaction-synchronized Session for current thread
报错解决方法若是不使用 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:advisor
中pointcut
属性所覆盖的类与方法,若是操做session
的方法不在此包含内,则仍会报错。
注:固然也可使用session.openSession()
并经过 Hibernate 的事务管理方式组织代码。
有时可能出现:在配置了 @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.html
或 index.jsp
文件,如访问 localhost/foo
等同于访问 localhost/foo/index.html
或 localhost/foo/index.jsp
( 依次检测这两个文件是否存在 )。于是须要在 spring-mvc.xml
( Spring mvc 配置文件 )中添加以下配置:
<mvc:default-servlet-handler />
context:property-placeholder
导入多个 .properties
配置文件因为 Spring 容器容许最多定义一个 placeholder
,加入多个文件会忽略。而因为 IDE 不会进行这一判断,于是会出现 IDE 中没有警告提示,但运行时却报错的状况。
这时咱们可使用通配符解决引入多个配置文件的需求:
<context:property-placeholder location="classpath*:*.properties"/>
WARNING: Exception encountered during context initialization - cancelling refresh attempt
发生这一问题多是因为在进行代码迁移时,tomcat 和编译器的 jdk 指定版本不一样,致使前者没法识别后者编译的的字节码文件。只需将两者保持一致便可,详情可参考 Stackoverflow。
若要在项目中使用 Thymeleaf 模板引擎,须要对以前进行的配置进行如下修改
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>
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>
因为 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>
th
命名空间声明的 .html
文件框架因为开发工具 与 emmet 插件等自动生成的 .html 文件框架中不含上述声明,每次都要写入声明也比较麻烦,能够在开发工具中添加一个文件模板以免重复工做,这里以 IDEA 为例:
在 File > Other Settings > Default Settings > Editor > File and Code Templates
中新建一个文件模板,以下图:
Spring: Difference of /* and / with regards to paths - stackoverflow
Spring 注解 @Component、@Repository、@Service、@Controller 区别 - CSND
The content of element type "web-app" must match 问题之解决办法 - CSDN
context:component-scan 扫描使用上的容易忽略的 use-default-filters - iteye
在使用 spring mvc 时,我使用了 @Service 这样的注解, 发现使用注解 @Transactional 声明的事务不起做用 - CSDN
SpringMVC4+thymeleaf3的一个简单实例(篇二:springMVC与thymeleaf的整合) - 博客园
thymeleaf code completion not working intellij 14 - stackoverflow
SpringMVC4+thymeleaf3的一个简单实例(篇二:springMVC与thymeleaf的整合) - 博客园
Spring 注解:@Repository、@Service、@Controller、@Autowired - CSDN