搭建Spring
1.porm.xml中添加jar包
<!-- spring3 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
porm.xml
2.将spring.xml,log4j.proprtities,config.properities添加到项目当中
<?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:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描dao和service包(自动注入) -->
<context:component-scan base-package="dao,service" /> </beans>
spring.xml
log4j.rootLogger=INFO,A1,R log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=sshe.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.Threshold=ALL
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
log4j.properities
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#jdbc_username=sshe
#jdbc_password=sshe hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/tables?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=123 #hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=sa
#jdbc_password=123456 #jndiName=java:comp/env/dataSourceName hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false sessionInfoName=sessionInfo uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
config.properities
3.测试
package service.impl; import org.springframework.stereotype.Service; import service.UserServiceI; @Service(value="userService")
public class UserServiceImpl implements UserServiceI{ public void test(){
System.out.println("ssss");
}
}
UserServiceImpl.java
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import service.UserServiceI; public class SpringTest { @Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"classpath:spring.xml"});
UserServiceI userService = (UserServiceI) ac.getBean("userService");
userService.test();
}
}
SpringTest.java
4.配置web.xml(若在test环境下,则无须配置此处)
<?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">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- spring监听器 只有配置了监听器,我才能在web项目启动的过程中,把spring上下文启动-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
web.xml
整合Spring+Struts2
1.porm.xml中添加jar
<!-- struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.4.1</version>
<!-- <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId>
</exclusion> </exclusions> -->
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.4.1</version>
</dependency>
porm.xml
2.web.xml中添加拦截器包
<!-- spring监听器 只有配置了监听器,我才能在web项目启动的过程中,把spring上下文启动-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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>*.action</url-pattern>
</filter-mapping>
web.xml
3.添加struts2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts> <!-- 指定由spring负责action对象的创建 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 所有匹配*.action的请求都由struts2处理 -->
<constant name="struts.action.extension" value="action" />
<!-- 是否启用开发模式 -->
<constant name="struts.devMode" value="true" />
<!-- struts配置文件改动后,是否重新加载 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 设置浏览器是否缓存静态内容 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 请求参数的编码方式 -->
<constant name="struts.i18n.encoding" value="utf-8" />
<!-- 每次HTTP请求系统都重新加载资源文件,有助于开发 -->
<constant name="struts.i18n.reload" value="true" />
<!-- 文件上传最大值 -->
<constant name="struts.multipart.maxSize" value="104857600" />
<!-- 让struts2支持动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<!-- Action名称中是否还是用斜线 -->
<constant name="struts.enable.SlashesInActionNames" value="false" />
<!-- 允许标签中使用表达式语法 -->
<constant name="struts.tag.altSyntax" value="true" />
<!-- 对于WebLogic,Orion,OC4J此属性应该设置成true -->
<constant name="struts.dispatcher.parametersWorkaround" value="false" /> <package name="basePackage" extends="struts-default"> </package> </struts>
struts.xml
4.编写action测试
package action; import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import service.UserServiceI; @ParentPackage("basePackage")
@Namespace("/")
@Action(value="userAction")
public class UserAction { private UserServiceI userService; public UserServiceI getUserService() {
return userService;
} @Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
} public void test(){
//System.out.println("进入action");
//ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
//UserServiceI u = (UserServiceI) ac.getBean("userService");
//u.test();
userService.test();
}
}
UserAction.java
整合Spring+Struts2+hibernate4
1.porm.xml中添加jar
<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>sy.sshe</groupId>
<artifactId>sshe</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name />
<description />
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- <dependency> <groupId>org.apache.openejb</groupId> <artifactId>javaee-api</artifactId>
<version>5.0-1</version> <scope>provided</scope> </dependency> <dependency>
<groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version>
<scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope>
</dependency> -->
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11-beta-1</version>
<scope>test</scope>
</dependency>
<!-- spring3 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.4.1</version>
<exclusions>
<exclusion>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.4.1</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- hibernate4 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.0</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- <groupId>org.apache.maven.plugins</groupId> <version>3.0.0</version> -->
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.7.2</version>
<configuration>
<argLine></argLine>
</configuration>
</plugin>
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.4.2</version> <configuration> <skipTests>true</skipTests> </configuration>
</plugin> -->
</plugins>
</build>
</project>
porm.xml
2.添加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
"> <!-- JNDI方式配置数据源 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" /> <!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean> <!-- 配置hibernate session工厂 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<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>
</props>
</property> <!-- 自动扫描注解方式配置的hibernate类文件 -->
<property name="packagesToScan">
<list>
<value>sy.model</value>
</list>
</property> <!-- 自动扫描hbm方式配置的hibernate文件和.hbm文件 -->
<!--
<property name="mappingDirectoryLocations">
<list>
<value>classpath:sy/hbm</value>
</list>
</property>
-->
</bean> <!-- 配置事务管理器 事务一般都配置在service层,而不是dao -->
<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(* sy.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config> </beans>
spring-hibernate.xml
3.配置web.xml
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
</context-param>
web.xml
4.测试
4.1添加UserDao及UserDaoImpl
package dao.impl; import java.io.Serializable; import model.Tuser; import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import dao.UserDaoI; @Repository("userDao")
public class UserDaoImpl implements UserDaoI { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() {
return sessionFactory;
} @Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} @Override
public Serializable save(Tuser user) {
// 因为事务交给了spring来管理,spring就会在使用(eg:save)前自行open一个session,save之后自动关闭session
//因为事务配置在了service层,所以这里是不可以opensession的,但是可以getcurrentsession
return this.getSessionFactory().getCurrentSession().save(user);
} }
UserDaoImpl
4.2在UserServiceImpl中添加save方法
package service.impl; import java.io.Serializable; import model.Tuser; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import dao.UserDaoI; import service.UserServiceI; @Service(value="userService")
public class UserServiceImpl implements UserServiceI{ private UserDaoI userDao ; public UserDaoI getUserDao() {
return userDao;
} @Autowired
public void setUserDao(UserDaoI userDao) {
this.userDao = userDao;
} public void test(){
System.out.println("ssss");
} @Override
public Serializable save(Tuser t) {
// TODO Auto-generated method stub
return userDao.save(t);
}
}
UserServiceImpl
4.3添加UserAction添加addUser方法
package action; import java.util.Date;
import java.util.UUID; import model.Tuser; import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired; import service.UserServiceI; @ParentPackage("basePackage")
@Namespace("/")
@Action(value="userAction")
public class UserAction { private UserServiceI userService; public UserServiceI getUserService() {
return userService;
} @Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
} public void test(){
//System.out.println("进入action");
//ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
//UserServiceI u = (UserServiceI) ac.getBean("userService");
//u.test();
userService.test();
} public void addUser(){
Tuser t = new Tuser();
t.setId(UUID.randomUUID().toString());
t.setName("林志玲");
t.setPwd("12345");
t.setCreatdatetime(new Date());
userService.save(t);
}
}
UserAction
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:等线;
mso-ascii-font-family:等线;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:等线;
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:等线;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}