注:本文用的是PostgreSQL,所以引的包和数据库配置也是PostgreSQL的,可以根据自己需要修改即可
1.建立maven工程
(1)File->New->Maven Project
(2)点击Next
(3) 选中默认的maven-archetype-quickstart,点击Next
(4)输入Group Id和Artifact Id,点击Finish
(5)添加Source Folder src/main/resources
然后在Folder name中输入src/main/resources,点击Finish
(6)配置Build Path
右键项目->Build Path->Configure Build Path...
设定Source中的输出Output folder,双击修改
分别修改输出路径为
src/main/resources 对应 target/classes
src/main/java 对应 target/classes
src/test/java 对应 target/test-classes
(7)设定Libraries
Libraries->Add Library
点击Finish
点击OK,配置完后目录结构如下:
2.转换为web项目
右键项目->Properties->Project Facets,选中Dynamic Web Module,更换version,然后点击Further configuration available...
修改Content directory 为 src/main/webapp ,单击OK,跳到外面一层继续点击OK即可:
3.设置部署程序集(Web Deployment Assembly)
在项目上右键单击,选择Properties,在左侧选择Deployment Assembly
4.设置部署时的文件发布路径
1,我们删除test的一项,因为test是测试使用,并不需要部署。
2,设置将Maven的jar包发布到lib下。
Add -> Java Build Path Entries -> Maven Dependencies -> Finish
设置完成后如图
ok后,web项目就创建完毕
5.修改pom文件
<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>com.ccc</groupId> <artifactId>SSH-Demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>SSH-Demo</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</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.16</version> <!-- 这里的 exclusions 是排除包,因为 Struts2中有javassist,Hibernate中也有javassist, 所以如果要整合Hibernate,一定要排除掉Struts2中的javassist,否则就冲突了。 <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> --> </dependency> <!-- convention-plugin插件,使用了这个插件之后,就可以采用注解的方式配置Action --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.20</version> </dependency> <!--config-browser-plugin插件,使用了这个插件之后,就可以很方便的浏览项目中的所有action及其与 jsp view的映射 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-config-browser-plugin</artifactId> <version>2.3.20</version> </dependency> <!-- Struts2和Spring整合插件 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.4.1</version> </dependency> <!-- hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.1.7.Final</version> </dependency> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901.jdbc4</version> </dependency> <!--Druid连接池包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.12</version> </dependency> <!--aspectjweaver包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> </dependencies> <build> <finalName>SSH-demo</finalName> </build> </project>
6.增加配置文件
(1)新建struts.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" /> <!-- 是否启用开发模式(开发时设置为true,发布到生产环境后设置为false) --> <constant name="struts.devMode" value="true" /> <!-- struts配置文件改动后,是否重新加载(开发时设置为true,发布到生产环境后设置为false) --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 设置浏览器是否缓存静态内容(开发时设置为false,发布到生产环境后设置为true) --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 请求参数的编码方式 --> <constant name="struts.i18n.encoding" value="utf-8" /> <!-- 每次HTTP请求系统都重新加载资源文件,有助于开发(开发时设置为true,发布到生产环境后设置为false) --> <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>
(2)新建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: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 "> <!-- 引入属性文件,config.properties位于src/main/resources目录下 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="com.ccc.dao,com.ccc.service,com.ccc.service.impl,com.ccc.dao.impl" /> </beans>
(3) 新建spring-hibernate文件
<?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> <!-- 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.ccc.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.ccc.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
(4)新建config.properties文件
#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=gacl
#jdbc_password=xdp
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
driverClassName=org.postgresql.Driver
validationQuery=SELECT version();
jdbc_url=jdbc:postgresql://localhost:5432/test
jdbc_username=postgres
jdbc_password=123456
#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/sshe
#jdbc_username=sa
#jdbc_password=123456
#jndiName=java:comp/env/dataSourceName
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.temp.use_jdbc_metadata_defaults false
(5)修改web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value> </context-param> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- openSessionInView配置 --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- Struts2的核心过滤器配置 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- Struts2过滤器拦截所有的.action请求 --> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- druid监控页面,使用${pageContext.request.contextPath}/druid/index.html访问 --> <servlet> <servlet-name>druidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>druidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> </web-app>
7.相关代码
目录结构如图:
(1)TestAction
package com.ccc.action; import java.util.Date; import java.util.UUID; 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 com.ccc.model.User; import com.ccc.service.UserServiceI; @ParentPackage("basePackage") @Action(value="Test")//使用convention-plugin插件提供的@Action注解将一个普通java类标注为一个可以处理用户请求的Action @Namespace("/")//使用convention-plugin插件提供的@Namespace注解为这个Action指定一个命名空间 public class TestAction { /** * 注入userService */ @Autowired private UserServiceI userService; /** * http://localhost:8080/SSH-Demo/Test!test.action * @author ccc */ public void test(){ System.out.println("进入TestAction"); userService.test(); } /** * http://localhost:8080/SSH-Demo/Test!saveUser.action */ public void saveUser(){ User user = new User(); user.setId(UUID.randomUUID().toString().replaceAll("-", "")); user.setName("ccc"); user.setPwd("123456"); user.setCreateDate(new Date()); userService.save(user); } }
(2)UserDaoI
package com.ccc.dao; import java.io.Serializable; import com.ccc.model.User; public interface UserDaoI { /** * 保存用户 * @param user * @return */ Serializable save(User user); }
(3)UserDaoImpl
package com.ccc.dao.impl; import java.io.Serializable; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.ccc.dao.UserDaoI; import com.ccc.model.User; @Repository("userDao") public class UserDaoImpl implements UserDaoI { /** * 使用@Autowired注解将sessionFactory注入到UserDaoImpl中 */ @Autowired private SessionFactory sessionFactory; public Serializable save(User user) { System.out.println("sessionFactory:["+sessionFactory.getCurrentSession()+"]"); return sessionFactory.getCurrentSession().save(user); } }
(4)User
package com.ccc.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "USER_INFO") public class User implements java.io.Serializable { // Fields private String id; private String name; private String pwd; private Date createDate; private Date modifyDate; // Constructors /** default constructor */ public User() { } /** minimal constructor */ public User(String id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } /** full constructor */ public User(String id, String name, String pwd, Date createDate, Date modifyDate) { this.id = id; this.name = name; this.pwd = pwd; this.createDate = createDate; this.modifyDate = modifyDate; } // Property accessors @Id @Column(name = "ID", unique = true, nullable = false, length = 36) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name = "NAME",nullable = false, length = 100) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "PWD", nullable = false, length = 32) public String getPwd() { return this.pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "CREATE_DATE", length = 7) public Date getCreateDate() { return this.createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "MODIFY_DATE", length = 7) public Date getModifyDate() { return this.modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }
(5)UserServiceI
package com.ccc.service; import java.io.Serializable; import com.ccc.model.User; /** * 测试 * @author ccc * */ public interface UserServiceI { /** * 测试方法 */ void test(); /** * 保存用户 * @param user * @return */ Serializable save(User user); }
(6)UserServiceImpl
package com.ccc.service.impl; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ccc.dao.UserDaoI; import com.ccc.model.User; import com.ccc.service.UserServiceI; //使用Spring提供的@Service注解将UserServiceImpl标注为一个Service @Service("userService") public class UserServiceImpl implements UserServiceI { /** * 注入userDao */ @Autowired private UserDaoI userDao; public void test() { System.out.println("Hello World!"); } public Serializable save(User user) { return userDao.save(user); } }
8.Build
右键项目->Run as->Maven install
BUILD SUCCESS 即成功
9.部署项目到tomcat或Jetty
启动成功:
访问http://localhost:8080/SSH-Demo/Test!test.action:
控制台输出:
10.数据库保存操作
访问http://localhost:8080/SSH-Demo/Test!saveUser.action:
说明保存成功,数据库user_info表中数据:
配置就OK了,可能自己所需要的网页jsp自己添加即可
参考资料:
1.http://www.cnblogs.com/leiOOlei/p/3361633.html
2.http://www.cnblogs.com/xdp-gacl/p/4239501.html