1,建立一个maven工程,在选择Archetype时选择webapp: html
2,下一步配置maven的pom.xml文件,获取依赖的jar包: java
<!-- struts2核心包 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.1.2</version> </dependency>
<!-- struts2与spring整合的包 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.1.2</version> </dependency>
<!-- 在 Struts2中要使用 Ajax得到Json数据。要使用Ajax必须引用此Jar --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.1.2</version> </dependency>
<!-- Hibernate核心包 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version> </dependency>
<!-- spring3可选的依赖注入,不可缺乏 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.3</version> </dependency>
<!-- 扩展Java类与实现Java接口 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency>
<!-- 运用Log4j必须用到这个包 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> <scope>compile</scope> </dependency>
<!-- Spring包 --> <!-- Spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> <type>jar</type> </dependency>
<!-- Spring在WEB上的MVC框架上加上这个包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency>
<!-- log4j日志包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <scope>compile</scope> </dependency>
<!-- jsp接口 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency>
<!-- 链接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
<!-- servlet接口 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency>
<!-- Mysql数据库JDBC链接包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> <scope>compile</scope> </dependency>
若是没使用maven,eclipse默认会去bin目录找class文件,若是使用了maven,则会去target\test-classes目录下去找class文件。恰好个人打包脚本中包含了mvn clean命令,将target\test-classes目录下的文件清空了,在target\test-classes目录尚未对应的class文件,因此会抛ClassNotFoundException!Project-clean操做让eclipse从新编译,恰好能够解决这个问题。 mysql
3,在src下建立目录webapp/WEB-INF/,并在WEB-INF下建立web.xml文件。 web
一,spring环境搭建+测试 spring
在web.xml文件中添加spring的启动监听器ContextLoaderListener sql
<!-- 监听器Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 定位applicationContext.xml的物理位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
这样在web容器启动的时候,会自动装配Spring的位于/WEB-INF/下的applicationContext.xml配置文件通常状况下,因为须要配置的bean较多,因此都是将bean按业务分类,在不一样的配置文件中进行配置。而后在applicationContext.xml文件中导入分类的配置文件的。 数据库
可是如今测试的时候会直接在applicationContext.xml文件下进行bean配置: express
<bean name="person" class="us.xuhang.project.domain.Person"> <property name="age" value="23" /> </bean>测试:
@Test public void testSpringEnv(){ //加载Spring的配置文件,获得ApplicationContext对象 ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml"); //获取bean对象 Person person = (Person) context.getBean("person"); System.out.println(person.getAge()); }
SessionFactory是Hibernate中的一个类,这个类主要负责保存HIbernate的配置信息,以及对Session的操做。
apache
在Hibernate的核心配置文件hibernate.cfg.xml中配置<session-factory/>: json
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!-- sessionFactory表明一个数据库的描述 --> <session-factory> <!-- 数据库用户名、密码、驱动、URL、数据库方言 --> <property name="connection.password">123456</property> <property name="connection.username">root</property> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/eclipseweb </property> <!-- 告诉hibernate连接的是什么数据库 --> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- 显示sql语句 --> <property name="show_sql">true</property> <!-- validate 默认值 根据持久化类和映射文件检查表的结构 update hibernate容器在启动的时候,会根据持久化类和映射文件检查表的结构 若是不存在,则建立,若是存在,则更新 create 每次启动hibernate容器,无论表是否存在,都会建立 create-drop 当启动hibernate容器时建立表,当hibernate容器销毁时,删除表 --> <property name="hbm2ddl.auto">update</property> <property name="format_sql">true</property> <!-- 持久化类和数据库表的映射文件 --> <mapping resource="us/xuhang/project/domain/Person.hbm.xml" /> </session-factory> </hibernate-configuration>
在Hibernate3.6版本中的dtd文有变化,改为上面的,否则会提示错误。
编写Person的映射文件Person.hbm.xml(位于和Person类相同的目录下)。配置实体类和数据库表的映射关系。
<hibernate-mapping> <class name="us.xuhang.project.domain.Person"> <id name="pid" length="40"> <generator class="assigned"></generator> </id> <property name="name" length="20"></property> <property name="age" type="int"></property> </class> </hibernate-mapping>
src/main/resources/us/xuhang/project/domain/测试:
@Test public void testHibernateEnv(){ //加载指定目录下的配置文件,获得configuration对象 Configuration cfg = new Configuration().configure("hibernate/hibernate.cfg.xml"); //根据configuration对象获得session工厂对象 SessionFactory factory = cfg.buildSessionFactory(); //使用工厂类打开一个session Session session = factory.openSession(); //开启事务 Transaction tx = session.beginTransaction(); //建立待插入数据库的对象 ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml"); Person p = (Person) context.getBean("person"); p.setPid(UUID.randomUUID().toString()); p.setName("xxx"); //保存对象 session.save(p); //提交事务 tx.commit(); //关闭资源 session.close(); factory.close(); }
以上是Hibernate本身管理SessionFactory的建立,下面将SessionFactory的建立过程交给Spring容器:
若是关于数据库的链接信息等仍然在Hibernate的配置文件中配置,即由Hibernate管理数据库的链接,则只须要在Spring的配置文件中配置SessionFactory的bean时注入configLocation,值为Hibernate的配置文件路径:classpath:hibernate/hibernate.cfg.xml
<!-- 若是关于数据库的属性在hibernate.cfg.xml中配置了,设置hibernate.cfg.xml的location便可 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate/hibernate.cfg.xml</value> </property> </bean>还有一种方法是有Spring来管理数据库的链接,这里使用c3p0来帮助管理数据源
<!-- 用Bean定义c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc\:mysql\://localhost\:3306/eclipseweb" /> <property name="user" value="root" /> <property name="password" value="123456" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <!-- 经过classpath的方式指向了映射文件所在的目录,把domain包及子包下全部的映射文件所有加载了 --> <property name="mappingDirectoryLocations"> <value>classpath:us/xuhang/project/domain</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 定义事务管理器(声明式的事务) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 切入点表达式 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:pointcut id="interceptorPointCuts" expression="execution(* us.xuhang.project.dao.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" /> </aop:config>
将SessionFactory对象的建立交给Spring容器来管理,在Spring的配置文件中配置SessionFactory的bean。
若是SessionFactory交给Hibernate管理,能够直接在Hibernate的配置文件hibernate.cfg.xml中使用<session-factory/>配置数据库的链接信息,而后在Spring的配置文件中导入Hibernate的配置文件:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate/hibernate.cfg.xml</value> </property> </bean>同时在<session-factory/>中加入持久化类和数据库表的映射文件路径:
<mapping resource="us/xuhang/project/domain/Person.hbm.xml" />
若是SessionFactory交给Spring容器管理,其中在Spring的配置文件中给SessionFactory注入数据源DataSource,数据源可使用JDBC数据源,也可使用第三方的C3P0数据源管理。
若是使用JDBC数据源,只需将DataSource的bean的class属性值改成org.springframework.jdbc.datasource.DriverManagerDataSource,而后给该类注入相应的属性。
<!-- 用Bean定义jdbc数据源 --> <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>若是使用C3P0数据源,则将DataSource的bean的class属性值改成对应的类com.mchange.v2.c3p0.ComboPooledDataSource,而后注入该类的相应的属性。
<!-- 用Bean定义c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>
以后将数据源注入到SessionFactory中,同时加入映射文件的路径和数据库的方言等配置
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="mappingDirectoryLocations"> <value>classpath:us/xuhang/project/domain</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hbm2ddl.auto">update</prop> </props> </property> </bean>
三,Spring和Struts2的整合
在web.xml中加入struts2的核心过滤器:
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>struts的配置文件struts.xml需放在classpath路径下,而后按照业务不一样分类配置struts,而后再在struts中include:
<struts> <!-- 告诉struts由spring容器做为bean工厂 --> <constant name="struts.objectFactory" value="spring"></constant> <include file="struts/struts-person.xml" /> </struts>struts/struts-person.xml:
<package name="person" namespace="/" extends="struts-default"> <!-- 这里action对象的建立有spring容器管理,因此class值再也不指定具体的全路径类名,而是直接从spring容器中取,这里的值为spring容器管理action的id值 --> <action name="personAction1" class="personAction1" method="personAction"> <result name="success">index.jsp</result> </action> </package>spring的配置文件中管理action的bean:
<bean id="personAction1" class="us.xuhang.project.controller.PersonAction" scope="prototype"> <property name="param" value="springControlStruts" /> </bean>
struts和Spring整合以后就会发现struts的映射文件中action的class值应为Spring中相应action的id。
因为struts的action是多例的,因此在spring容器管理action对象建立的时候须要指明一下,设置action的scope属性值为prototype。
SSH零配置整合
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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"> <!-- 监听器Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 定位applicationContext.xml的物理位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <!-- hibernate 懒加载的问题过滤 ,能够不配置 --> <filter> <description>hibernate Session 过滤器</description> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts配置 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>applicationContext.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"> <context:annotation-config /> <context:component-scan base-package="us.xuhang.project.ssh" /> <context:property-placeholder location="classpath:hibernate.properties"/> <import resource="classpath:hibernate.cfg.xml"/> <aop:aspectj-autoproxy /> <!-- 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 加载事务驱动 --> <!-- 对@Transactional这个注解进行的驱动,这是基于注解的方式使用事务配置声明,这样在具体应用中能够指定对哪些方法使用事务 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 事务的策略 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="select*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <!-- AOP配置 --> <aop:config> <!-- 对知足下面表达式的(业务逻辑层)方法实施事务 --> <aop:pointcut id="txPointcut" expression="execution(* us.xuhang.project.service.*.*(..))" /> <!-- 引用上面的事务策略txAdvice --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <!-- 声明日志记录通知 --> <bean id="logInterceptor" class="us.xuhang.project.interceptor.LogInterceptor"></bean> <aop:config> <!-- 配置一个切面 --> <aop:aspect id="point" ref="logInterceptor"> <!-- 配置切入点,指定切入点表达式 --> <!-- 此句也可放到 aop:aspect标签外依然有效 --> <aop:pointcut expression="execution(public * us.xuhang.project.service..*.*(..))" id="myMethod" /> <!-- 应用前置通知 --> <aop:before method="before" pointcut-ref="myMethod" /> <!-- 应用环绕通知需指定向下进行 --> <aop:around method="around" pointcut-ref="myMethod" /> <!-- 应用后通知 --> <aop:after-returning method="afterReturning" pointcut-ref="myMethod" /> <!-- 应用抛出异常后通知 --> <aop:after-throwing method="afterThrowing" pointcut-ref="myMethod" /> </aop:aspect> </aop:config> </beans>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> <!-- 使用Spring --> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.devMode" value="true" /> <constant name="struts.configuration.xml.reload" value="true" /> <package name="default" extends="struts-default" namespace="/"> <!-- 声明拦截器 --> <interceptors> <!-- 权限拦截器 --> <interceptor name="authority" class="us.xuhang.project.interceptor.AuthorityInterceptor" /> <!-- 异常拦截器 --> <interceptor name="exceptionInterceptor" class="us.xuhang.project.interceptor.ExceptionInterceptor" /> <!-- 声明拦截器栈!解决struts安全漏洞,拦截全部的带有#号的url --> <interceptor-stack name="MyStack"> <interceptor-ref name="authority" /> <interceptor-ref name="exceptionInterceptor" /> <interceptor-ref name="params"> <param name="excludeParams">.*\\u0023.*</param> </interceptor-ref> <!-- 使用自定义拦截器后就不会再使用默认拦截器栈,这里须要把默认拦截器栈加进来。 --> <interceptor-ref name="defaultStack" /> </interceptor-stack> </interceptors> <default-interceptor-ref name="MyStack" /> <!-- 定义全局的result --> <global-results> <result name="login">/index.jsp</result> <result name="error">/error.jsp</result> </global-results> </package> </struts>hibernate.cfg.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" 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"> <!-- C3P0 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${hibernate.connection.driver_class}" /> <property name="jdbcUrl" value="${hibernate.connection.url}" /> <property name="user" value="${hibernate.connection.username}" /> <property name="password" value="${hibernate.connection.password}" /> <property name="initialPoolSize" value="${hibernate.connection.initialPoolSize}" /> <property name="minPoolSize" value="${hibernate.connection.minPoolSize}" /> <property name="maxPoolSize" value="${hibernate.connection.maxPoolSize}" /> <property name="preferredTestQuery" value="select 1 from dual " /> </bean> <!-- SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.tianlihu.projects.ssh.*.po" /> <property name="useTransactionAwareDataSource" value="true" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.temp.use_jdbc_metadata_defaults">${hibernate.temp.use_jdbc_metadata_defaults}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.connection.autocommit">false</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> </bean> <!-- 配置事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:aspectj-autoproxy /> <tx:annotation-driven /> </beans>hibernate.properties:
## hibernate hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl.auto=create-drop hibernate.temp.use_jdbc_metadata_defaults=false ## hibernate cache hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider hibernate.cache.use_query_cache=false hibernate.cache.use_second_level_cache=true ## C3P0 configuration hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK hibernate.connection.username=root hibernate.connection.password=root hibernate.connection.initialPoolSize=1 hibernate.connection.minPoolSize=1 hibernate.connection.maxPoolSize=3