使用Maven搭建Struts2+Spring3+Hibernate4的整合开发环境
一.新建Maven项目
src/main/resources
src/test/java
src/test/resources
二.搭建struts2开发环境
1.下载Struts2需要的jar包
1.strtus2-core
2.struts2-convention-plugin(使用了这个插件之后,就可以采用注解的方式配置Struts的Action,免去了在struts.xml中的繁琐配置项)
3.struts2-config-browser-plugin(config-browser-plugin插件不是必须的,但是使用了这个插件之后,就可以很方便的浏览项目中的所有action及其与 jsp view的映射)
在pom.xml文件中编写Struts2所需要的jar包,Maven会自动下载这些包
- <!-- Struts2的核心包 -->
- <dependency>
- <groupId>org.apache.struts</groupId>
- <artifactId>struts2-core</artifactId>
- <version>2.3.16</version>
- </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>
2.编写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>
- <!-- 所有匹配*.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>
3.在web.xml中配置Struts2的过滤器
- <?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>
- <!-- 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>
- </web-app>
- package com.cosconet.action;
- import org.apache.struts2.convention.annotation.Action;
- import org.apache.struts2.convention.annotation.Namespace;
- import org.apache.struts2.convention.annotation.ParentPackage;
- import org.apache.struts2.convention.annotation.Result;
- import org.apache.struts2.convention.annotation.Results;
- @ParentPackage("basePackage")
- @Action(value="strust2Test")//使用convention-plugin插件提供的@Action注解将一个普通java类标注为一个可以处理用户请求的Action,Action的名字为struts2Test
- @Namespace("/")//使用convention-plugin插件提供的@Namespace注解为这个Action指定一个命名空间
- @Results( { @Result(name = "success", location = "/success.jsp"),
- @Result(name = "input", location = "/register.jsp") })
- public class TestAction {
- /**
- * http://localhost:8080/SSHE/strust2Test!test.action
- * MethodName: test
- * Description:
- * @author xudp
- */
- public String test(){
- System.out.println("进入TestAction");
- return "success";
- }
- }
测试Struts2的开发环境是否搭建成功,先执行【Maven install】操作,然后部署到tomcat服务器,最后启动tomcat服务器运行,输入访问地址:http://localhost:8080/SSHE/strust2Test!test.action,访问结果如下:
二.搭建spring3开发环境
1.spring-core
2.spring-context
3.spring-jdbc
4.spring-beans
5.spring-web
6.spring-expression
7.spring-orm
在pom.xml中编写Spring3需要的包,maven会自动下载这些包以及相关的依赖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>
- <span style="white-space:pre"> </span><!--aspectjweaver包 -->
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.8.5</version>
- </dependency>
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.cosconet.dao,com.cosconet.service" />
- </beans>
- package com.cosconet.service;
- public interface UserServiceI {
- /**
- * 测试方法
- */
- void test();
- }
- package com.cosconet.service.impl;
- import org.springframework.stereotype.Service;
- import com.cosconet.service.UserServiceI;
- //使用Spring提供的@Service注解将UserServiceImpl标注为一个Service
- @Service("userService")
- public class UserServiceImpl implements UserServiceI {
- @Override
- public void test() {
- System.out.println("Hello World!");
- }
- }
- <span style="white-space:pre"> </span><!-- Junit -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- package com.cosconet.test;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.cosconet.service.UserServiceI;
- public class TestSpring {
- @Test
- public void test(){
- //通过spring.xml配置文件创建Spring的应用程序上下文环境
- ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
- //从Spring的IOC容器中获取bean对象
- UserServiceI userService = (UserServiceI) ac.getBean("userService");
- //执行测试方法
- userService.test();
- }
- }
三.搭建hibernate4开发环境
1.hibernate-core
在pom.xml文件中编写Hibernate4所需要的jar包,Maven会自动下载这些包。
- <!-- hibernate4 -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <version>4.1.7.Final</version>
- <!--
- 这里的 exclusions 是排除包,因为 Struts2中有javassist,Hibernate中也有javassist,
- 所以如果要整合Hibernate,一定要排除掉Struts2中的javassist,否则就冲突了。-->
- <exclusions>
- <exclusion>
- <groupId>javassist</groupId>
- <artifactId>javassist</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <!-- mysql驱动包 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.34</version>
- </dependency>
Step 1
在微软官网下载sqljdbc的jar包:http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774
本次下载了4.0版本
Step 2
通过maven命令将jar包安装到本地。
在有sqljdbc4.jar包的文件夹下,通过shift+右键的方式--》此处打开命令窗口,然后执行以下maven命令
mvn install:install-file -Dfile=sqljdbc4.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0
命令解释:mvn install:install-file -Dfile="jar包的绝对路径" -Dpackaging="文件打包方式" -DgroupId=groupid名 -DartifactId=artifactId名 -Dversion=jar版本
Step 3
在pom.xml中引入本地jar包
- <!--sqlserver驱动包 -->
- <dependency>
- <groupId>com.microsoft.sqlserver</groupId>
- <artifactId>sqljdbc4</artifactId>
- <version>4.0</version>
- </dependency>
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>1.4</version>
- </dependency>
- <span style="white-space:pre"> </span><!--Oracle数据库驱动包,针对Oracle11.2的ojdbc6.jar -->
- <dependency>
- <groupId>com.oracle</groupId>
- <artifactId>ojdbc6</artifactId>
- <version>11.2.0.1.0</version>
- </dependency>
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
- <property name="connection.url">jdbc:sqlserver://172.25.6.146:1433;DatabaseName=xsjdd;SelectMethod=cursor;</property>
- <property name="connection.username">sa</property>
- <property name="connection.password">cosnet</property>
- <!-- SQL dialect -->
- <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
- <!--
- 将Session扔到线程里去处理,Enable Hibernate's automatic session context
- management
- -->
- <property name="current_session_context_class">thread</property>
- <!-- 在控制台打印SQL语句 -->
- <property name="show_sql">true</property>
- <!-- 自动把实体类与属性映射成数据库中的表与列 -->
- <property name="hbm2ddl.auto">update</property>
- <!--
- <mapping resource="cn/com/entity/User.hbm.xml"/>
- -->
- <!-- 在Hibernate中注册User实体类,区别于上面注释掉的resource写法 -->
- <mapping class="com.cosconet.model.User" />
- </session-factory>
- </hibernate-configuration>
代码如下:
- package com.cosconet.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 = "BD_TestUser", schema = "dbo")
- public class User implements java.io.Serializable {
- // Fields
- private String id;
- private String name;
- private String pwd;
- private Date createdatetime;
- private Date modifydatetime;
- // 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 createdatetime, Date modifydatetime) {
- this.id = id;
- this.name = name;
- this.pwd = pwd;
- this.createdatetime = createdatetime;
- this.modifydatetime = modifydatetime;
- }
- // 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 = "CREATEDATETIME", length = 7)
- public Date getCreatedatetime() {
- return this.createdatetime;
- }
- public void setCreatedatetime(Date createdatetime) {
- this.createdatetime = createdatetime;
- }
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "MODIFYDATETIME", length = 7)
- public Date getModifydatetime() {
- return this.modifydatetime;
- }
- public void setModifydatetime(Date modifydatetime) {
- this.modifydatetime = modifydatetime;
- }
- }
代码如下:
- package com.cosconet.test;
- import java.util.Date;
- import java.util.UUID;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.junit.Test;
- import com.cosconet.model.User;
- public class TestHibernate {
- @Test
- public void save()
- {
- User user = new User();
- user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
- user.setName("哈宇华帝");
- user.setPwd("123");
- user.setCreatedatetime(new Date());
- Configuration cfg = new Configuration();
- SessionFactory cf = cfg.configure().buildSessionFactory();
- Session session = cf.openSession();
- session.beginTransaction();
- session.save(user);
- session.getTransaction().commit();
- session.close();
- cf.close();
- }
- }
四.struts2与spring整合
- <!-- Struts2和Spring整合插件 -->
- <dependency>
- <groupId>org.apache.struts</groupId>
- <artifactId>struts2-spring-plugin</artifactId>
- <version>2.3.4.1</version>
- </dependency>
- <!-- 指定由spring负责action对象的创建 -->
- <constant name="struts.objectFactory" value="spring" />
- package com.cosconet.action;
- import org.apache.struts2.convention.annotation.Action;
- import org.apache.struts2.convention.annotation.Namespace;
- import org.apache.struts2.convention.annotation.ParentPackage;
- import org.apache.struts2.convention.annotation.Result;
- import org.apache.struts2.convention.annotation.Results;
- import org.springframework.beans.factory.annotation.Autowired;
- import com.cosconet.service.UserServiceI;
- @ParentPackage("basePackage")
- @Action(value="strust2Test")//使用convention-plugin插件提供的@Action注解将一个普通java类标注为一个可以处理用户请求的Action,Action的名字为struts2Test
- @Namespace("/")//使用convention-plugin插件提供的@Namespace注解为这个Action指定一个命名空间
- @Results( { @Result(name = "success", location = "/success.jsp"),
- @Result(name = "input", location = "/register.jsp") })
- public class TestAction {
- /**
- * 注入userService
- */
- @Autowired
- private UserServiceI userService;
- public TestAction() {
- super();
- }
- /**
- * http://localhost:8080/SSHE/strust2Test!test.action
- * MethodName: test
- * Description:
- * @author xudp
- */
- public String test(){
- System.out.println("进入TestAction");
- userService.test();
- return "success";
- }
- }
五.spring与hibernate整合
配置如下:
- #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.MySQLDialect
- #driverClassName=com.mysql.jdbc.Driver
- #validationQuery=SELECT 1
- #jdbc_url=jdbc:mysql://localhost:3306/sshe?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
- #jdbc_username=root
- #jdbc_password=XDP
- hibernate.dialect=org.hibernate.dialect.SQLServerDialect
- driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
- validationQuery=SELECT 1
- jdbc_url=jdbc\:sqlserver\://172.25.6.146\:1433;DatabaseName\=xsjdd;SelectMethod\=cursor;
- jdbc_username=sa
- jdbc_password=cosnet
- #jndiName=java:comp/env/dataSourceName
- hibernate.hbm2ddl.auto=update
- hibernate.show_sql=true
- hibernate.format_sql=true
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 id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
- <property name="url" value="${jdbc_url}" />
- <property name="username" value="${jdbc_username}" />
- <property name="password" value="${jdbc_password}" />
- </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>me.gacl.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(* me.gacl.service..*Impl.*(..))" />
- <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
- </aop:config>
- </beans>
- package com.cosconet.dao;
- import java.io.Serializable;
- import com.cosconet.model.User;
- public interface UserDaoI {
- /**
- * 保存用户
- * @param user
- * @return
- */
- Serializable save(User user);
- }
- package com.cosconet.dao.impl;
- import java.io.Serializable;
- import org.hibernate.SessionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
- import com.cosconet.dao.UserDaoI;
- import com.cosconet.model.User;
- @Repository("userDao")
- public class UserDaoImpl implements UserDaoI {
- /**
- * 使用@Autowired注解将sessionFactory注入到UserDaoImpl中
- */
- @Autowired
- private SessionFactory sessionFactory;
- @Override
- public Serializable save(User user) {
- return sessionFactory.getCurrentSession().save(user);
- }
- }
在之前创建好的UserServiceI接口中添加一个save方法的定义,如下:
- package com.cosconet.service;
- import java.io.Serializable;
- import com.cosconet.model.User;
- public interface UserServiceI {
- /**
- * 测试方法
- */
- void test();
- /**
- * 保存用户
- * @param user
- * @return
- */
- Serializable save(User user);
- }
- package com.cosconet.service.impl;
- import java.io.Serializable;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import com.cosconet.dao.UserDaoI;
- import com.cosconet.model.User;
- import com.cosconet.service.UserServiceI;
- //使用Spring提供的@Service注解将UserServiceImpl标注为一个Service
- @Service("userService")
- public class UserServiceImpl implements UserServiceI {
- /**
- * 注入userDao
- */
- @Autowired
- private UserDaoI userDao;
- @Override
- public void test() {
- System.out.println("Hello World!");
- }
- @Override
- public Serializable save(User user) {
- return userDao.save(user);
- }
- }
- package com.cosconet.test;
- import java.util.Date;
- import java.util.UUID;
- import org.junit.Before;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.cosconet.model.User;
- import com.cosconet.service.UserServiceI;
- public class TestSpringHibernate {
- private UserServiceI userService;
- /**
- * 这个before方法在所有的测试方法之前执行,并且只执行一次
- * 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行
- * 比如在before方法里面初始化ApplicationContext和userService
- */
- @Before
- public void before(){
- ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
- userService = (UserServiceI) ac.getBean("userService");
- }
- @Test
- public void testSaveMethod(){
- //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
- //UserServiceI userService = (UserServiceI) ac.getBean("userService");
- User user = new User();
- user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
- user.setName("哈宇华帝2");
- user.setPwd("123");
- user.setCreatedatetime(new Date());
- userService.save(user);
- }
- }
测试成功,数据成功保存到数据库,spring与hibernate整合完成。
六.三大框架整合测试
- <!-- Spring配置文件位置 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
- </context-param>
- package com.cosconet.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.apache.struts2.convention.annotation.Result;
- import org.apache.struts2.convention.annotation.Results;
- import org.springframework.beans.factory.annotation.Autowired;
- import com.cosconet.model.User;
- import com.cosconet.service.UserServiceI;
- @ParentPackage("basePackage")
- @Action(value="strust2Test")//使用convention-plugin插件提供的@Action注解将一个普通java类标注为一个可以处理用户请求的Action,Action的名字为struts2Test
- @Namespace("/")//使用convention-plugin插件提供的@Namespace注解为这个Action指定一个命名空间
- @Results( { @Result(name = "success", location = "/success.jsp"),
- @Result(name = "input", location = "/register.jsp") })
- public class TestAction {
- /**
- * 注入userService
- */
- @Autowired
- private UserServiceI userService;
- public TestAction() {
- super();
- }
- /**
- * http://localhost:8080/SSHE/strust2Test!test.action
- * MethodName: test
- * Description:
- * @author xudp
- */
- public String test(){
- System.out.println("进入TestAction");
- userService.test();
- return "success";
- }
- /**
- * http://localhost:8080/SSHE/strust2Test!saveUser.action
- */
- public void saveUser(){
- User user = new User();
- user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
- user.setName("哈宇华帝5");
- user.setPwd("123456");
- user.setCreatedatetime(new Date());
- userService.save(user);
- }
- }
查询数据库,数据已成功保存到数据库,至此,三大框架整合完成。