spring4+hibernate4+struts2环境搭建
tomact配置请查看下面的文章
javaEE_maven_struts2_tomcat_first
http://www.cnblogs.com/luotuoke/p/4543686.html
pom.xml
<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>signng</groupId> <artifactId>signn</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>signn Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.4</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.24</version> </dependency> <!-- spring4 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.1.5.RELEASE</version> </dependency> <!-- hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.10.Final</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.5</version> </dependency> <!-- mysql驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 数据连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.1_3</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.2</version> <exclusions> <exclusion> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> </exclusion> <exclusion> <groupId>xerces</groupId> <artifactId>xerces</artifactId> </exclusion> </exclusions> </dependency> <!-- spring的aop jar --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> </dependencies> <build> <finalName>signn</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat6-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost/manager</url> <path>/sign</path> <port>8010</port> <warSourceDirectory>${basedir}/src/main/webapp</warSourceDirectory> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>src\main\webapp</warSourceDirectory> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>7</source> <target>7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.4.2</version> <configuration> <filesets> <fileset> <directory>target</directory> <includes> <include>signn</include> </includes> </fileset> </filesets> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd " version="2.5"> <display-name>sign</display-name> <!-- 引入spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <!-- 编码过滤 --> <filter> <filter-name>encodingFilter</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> <filter-name>compressingFilter</filter-name> <filter-class>com.planetj.servlet.filter.compression.CompressingFilter</filter-class> </filter> --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener><!-- 释放与掉这个web 应用 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener><!-- 启动Web容器时,自动装配ApplicationContext的配置信息 --> <!-- struts2 --> <filter> <filter-name>struts</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> <init-param> <param-name>struts.i18n.encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <error-page> <error-code>404</error-code> <location>/common/404.html</location> </error-page> <error-page> <error-code>500</error-code> <location>/common/500.html</location> </error-page> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
spring.xml
<?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:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <import resource="spring/spring-annotation.xml"/> <import resource="spring/spring-hibernate.xml"/> <import resource="spring/spring-resources.xml"/> </beans>
spring-annotation.xml
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName"> <context:component-scan base-package="com.sign"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan> <context:component-scan base-package="com.sign"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <context:component-scan base-package="com.sign"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
spring-hibernate.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- 配置数据源 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${database.driverClass}" /> <property name="jdbcUrl" value="${database.jdbcUrl}" /> <property name="user" value="${database.user}" /> <property name="password" value="${database.password}" /> <property name="initialPoolSize" value="${database.initialPoolSize}" /> <property name="maxPoolSize" value="${database.maxPoolSize}" /> <property name="minPoolSize" value="${database.minPoolSize}" /> <property name="acquireIncrement" value="${database.acquireIncrement}" /> <property name="maxIdleTime" value="${database.maxIdleTime}" /> <property name="maxConnectionAge" value="${database.maxConnectionAge}" /> <property name="maxIdleTimeExcessConnections" value="${database.maxIdleTimeExcessConnections}" /> <property name="preferredTestQuery" value="${database.preferredTestQuery}" /> <property name="testConnectionOnCheckout" value="${database.testConnectionOnCheckout}" /> <property name="idleConnectionTestPeriod" value="${database.idleConnectionTestPeriod}" /> <property name="numHelperThreads" value="${database.numHelperThreads}" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <!-- web项目启动时是否更新表结构 --> <!-- <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> --> <!-- 系统使用的数据库方言,也就是使用的数据库类型 --> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <!-- 是否打印Hibernate生成的SQL到控制台 --> <prop key="hibernate.show_sql">${hibernate.show.sql}</prop> <!-- 是否格式化打印出来的SQL --> <prop key="hibernate.format_sql">${hibernate.format.sql}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <value>com.sign.user.model</value> </list> </property> <!-- 自动扫描hbm方式配置的hibernate文件和.hbm文件 --> <!-- <property name="mappingDirectoryLocations"> <list> <value>classpath:me/gacl/model/hbm</value> </list> </property> --> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 以如下关键字开头的方法使用事物 --> <tx:method name="add*" /> <tx:method name="save*" /> <tx:method name="update*" /> <tx:method name="modify*" /> <tx:method name="edit*" /> <tx:method name="delete*" /> <tx:method name="remove*" /> <tx:method name="repair" /> <tx:method name="deleteAndRepair" /> <!-- 以如下关键字开头的方法不使用事物 --> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <!-- 其他方法不使用事物 --> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <!-- 切面,将事物用在哪些对象上 --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.sign.user.service.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
spring-resource.xml
<?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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="appMessageResource" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/jdbc.properties</value> </list> </property> </bean> </beans>
jdbc.properties
#hibernate configuration hibernate.cache.provider=org.hibernate.cache.EhCacheProvider hibernate.cache.query.isSupport=false hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show.sql=true hibernate.format.sql=true validationQuery=SELECT 1 database.user=root database.password=root database.driverClass=com.mysql.jdbc.Driver database.jdbcUrl=jdbc:mysql://localhost:3306/sign?useUnicode=true&characterEncoding=UTF-8 database.initialPoolSize=3 database.minPoolSize=3 database.maxPoolSize=60 database.acquireIncrement=3 database.maxIdleTime=3600 database.maxConnectionAge=14400 database.maxIdleTimeExcessConnections=3600 database.preferredTestQuery=select 1 database.testConnectionOnCheckout=false database.idleConnectionTestPeriod=60 database.numHelperThreads=4
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encodeing" value="GBK"/> <constant name="struts.multipart.maxSize" value="52428800" /> <include file="struts/struts-user.xml"/> </struts>
struts-user.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encodeing" value="GBK"/> <constant name="struts.multipart.maxSize" value="52428800" /> <package name="user" namespace="/" extends="struts-default"> <action name="user" class="com.sign.action.UserAction" method="toUser"> <result name="SUCCESS">/view/user.jsp</result> </action> </package> </struts>
User.java
/** * */ package com.sign.user.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author Administrator * create on 2015年5月30日 * */ @Entity @Table(name="s_user") public class User implements Serializable{ @Id private Long id; @Column(name ="user_name",nullable=true) private String userName; @Column(name ="user_mobile",nullable=true) private String userMobile; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserMobile() { return userMobile; } public void setUserMobile(String userMobile) { this.userMobile = userMobile; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
UserManager.java
package com.sign.user.service; import com.sign.user.model.User; /** * @author Administrator * create on 2015年5月30日 * */ public interface UserManager { public User getUserByUserName(String userName); public void save(User user); }
UserManagerImpl.java
package com.sign.user.service.impl; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sign.user.model.User; import com.sign.user.service.UserManager; /** * @author Administrator * create on 2015年5月30日 * */ @Service("userManager") public class UserManagerImpl implements UserManager { @Autowired private SessionFactory sessionFactory; @Override public User getUserByUserName(String userName) { System.out.println("hello world"); return null; } @Override public void save(User user) { sessionFactory.getCurrentSession().save(user); } }
UserAction.java
package com.sign.action; /** * @author Administrator * create on 2015年5月30日 * */ public class UserAction { public String toUser(){ return "SUCCESS"; } }
SpringTest.java
/** * */ package test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sign.user.service.UserManager; import com.sign.user.service.impl.UserManagerImpl; /** * @author Administrator * create on 2015年6月1日 * */ public class SpringTest { @Test public void test(){ //通过spring.xml配置文件创建Spring的应用程序上下文环境 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml"); //从Spring的IOC容器中获取bean对象 UserManager userManager = (UserManager) ac.getBean("userManager"); //执行测试方法 userManager.getUserByUserName("hahah"); } }
HibernateTest.java
package test; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sign.user.model.User; import com.sign.user.service.UserManager; import com.sign.user.service.impl.UserManagerImpl; /** * @author Administrator * create on 2015年6月2日 * */ public class HibernateTest { /** * 这个before方法在所有的测试方法之前执行,并且只执行一次 * 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行 * 比如在before方法里面初始化ApplicationContext和userService */ @Before public void before(){ } @Test public void testSaveMethod(){ ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml"); UserManager userManager = (UserManager) ac.getBean("userManager"); User user = new User(); user.setId(Long.valueOf("1111")); user.setUserName("dddsedsds"); user.setUserMobile("123333"); userManager.save(user); } }
整体结构
spring测试结果:
hibernate测试结果
---------------
当在sturts.xml中配置了
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 不允许使用action通配符如<action name="login_*" method="{1}" -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<!-- 你可以引用对象池中的对象,借助Spring中的对象池 -->
<constant name="struts.objectFactory" value="spring" />
<!-- struts.objectFactory.spring.autoWire是用spring插件通过覆盖(override)Struts2的ObjectFactory来增强核心框架对象的创建。当创建一个对象的时候,它会用Struts2配置文件中的class属性去和Spring配置文件中的id属性进行关联,如果能找到则由Spring创建,否则由Struts2框架自身创建,然后由Spring来装配。 -->
<constant name="struts.objectFactory.spring.autoWire" value="name" />
<!-- 开启使用开发模式,详细错误提示 -->
<constant name="struts.devMode" value="true"/>
<!-- 指定每次请求到达,重新加载资源文件 -->
<!-- <constant name="struts.i18n.reload" value="true"/>-->
<!-- 指定每次配置文件更改后,自动重新加载 -->
<!-- <constant name="struts.configuration.xml.reload" value="true"/>-->
<!-- 指定XSLT Result使用样式表缓存 -->
<!-- <constant name="struts.xslt.nocache" value="true"/>-->
<constant name="struts.i18n.encodeing" value="GBK"/>
<constant name="struts.multipart.maxSize" value="52428800" />
<include file="struts/struts-user.xml"/>
</struts>
得在pom.xml
<!-- struts2-spring --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.16.3</version> <type>jar</type> <scope>compile</scope> </dependency>