SSH环境搭建(巨详细!!!)

来源:互联网 发布:测温软件有悬浮 编辑:程序博客网 时间:2024/05/12 18:16

前言:搭建SSH会使用很多包,一般需要到处复制,放在lib下,这样会很麻烦。因此,我使用Maven搭建ssh环境,如果你没听过maven,不用惊慌,主要是为了使用它的pom.xml,它可以自动导入你需要的jar包,使开发更方便。let's go!(注:此工程是引入别人的代码)

一、建立web project工程(不同版本,以下顺序有差别,但内容不变)

 1.file--new--web project

2.name:SSHE,选择mavensupport,next

 

输入项目的group id:一般为域名+项目名,

Artifact id:项目名,

选择标准maven工程,finish

3.新建的工程视图

修改配置:这里的JDK要选择默认的,这样别人在使用的时候,如果JDk不一致的话也不会出错

二、搭建Spring3开发环境

1.引入spring3的jar包:在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>

2.编写spring.xml:在src/main/resources目录下创建一个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="me.gacl.dao,me.gacl.service" />

</beans>

3.在src/main/resources目录下创建一个config.properties文件,config.properties文件主要是用来编写一些系统的配置信息,例如数据库连接信息,config.properties文件中的内容暂时先不编写,等整合到Hibernate时再编写具体的数据库连接信息。(虽然为空,但一定要有,否则出错)

4.测试

首先,在src/main/java中创建me.gacl.service包,在包中编写一个 UserServiceI 接口

package me.gacl.service;

/**
 * 测试
 * @author gacl
 *
 */
public interface UserServiceI {

    /**
     * 测试方法
     */
    void test();
}

 

 

然后,在src/main/java中创建me.gacl.service.impl包,在包中编写UserServiceImpl实现类

package me.gacl.service.impl;

import org.springframework.stereotype.Service;

import me.gacl.service.UserServiceI;
//使用Spring提供的@Service注解将UserServiceImpl标注为一个Service
@Service("userService")
public class UserServiceImpl implements UserServiceI {

    @Override
    public void test() {
        System.out.println("Hello World!");
    }

}

 

 

进行单元测试时需要使用到Junit,所以需要在pom.xml文件中添加Junit的jar包描述

<!-- Junit:<scope>test</scope>这里的test表示测试时编译src/main/test文件夹中的文件,等发布的时候不编译。 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

 

最后,在src/main/test中创建me.gacl.test包,在包中编写 TestSpring类

package me.gacl.test;

import me.gacl.service.UserServiceI;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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();
    }
}

5.run as--junit 运行

6.在web.xml中配置Spring监听器

<!-- 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</param-value>
    </context-param>

7.先执行【Maven install】命令发布项目,然后启动tomcat服务器,tomcat服务器启动的过程中没有出现报错,输入地址:http://localhost:8080/SSHE

测试通过,Spring3开发环境搭建成功!

三、搭建Struts2

1.引包:在pom.xml文件中编写Struts2所需要的jar包

<!-- 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>

 

2.在src/main/resources目录下创建一个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>

3.在web.xml中配置Struts2的过滤器

<!-- 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>

4.测试:在src/main/java中创建me.gacl.action包,在包中编写一个 TestAction类

package me.gacl.action;

import me.gacl.service.UserServiceI;

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;

@ParentPackage("basePackage")
@Action(value="strust2Test")//使用convention-plugin插件提供的@Action注解将一个普通java类标注为一个可以处理用户请求的Action,Action的名字为struts2Test
@Namespace("/")//使用convention-plugin插件提供的@Namespace注解为这个Action指定一个命名空间
public class TestAction {
   
    /**
     * 注入userService
     */
    @Autowired
    private UserServiceI userService;

    /**
     * http://localhost:8080/SSHE/strust2Test!test.action
     * MethodName: test
     * Description:
     * @author xudp
     */
    public void test(){
        System.out.println("进入TestAction");
        userService.test();
    }
}

5.先执行【Maven install】操作,然后启动tomcat服务器运行,输入访问地址:http://localhost:8080/SSHE/strust2Test!test.action,结果会在控制台输出,每刷新一次地址就会在控制台打印以下信息

测试通过,Struts2的开发环境搭建并整合Spring成功!

四、搭建Hibernate4

1.引包:在pom.xml文件中编写Hibernate4所需要的jar包

注意:一定要排除掉Struts2中的javassist,否则就冲突了(在Struts包中有删除的方法,去掉注释即可)。

<!-- hibernate4 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.7.Final</version>
        </dependency>

 

<!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>

<!--Druid连接池包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.12</version>
        </dependency>

<!--aspectjweaver包:使用Spring的aop时需要使用到aspectjweaver包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>

2.在config.properties文件中编写连接数据库需要使用到的相关信息:注意此处数据库名称sshe,用户名和密码都是root,根据需要自己改

#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=root

#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

3.在src/main/resources目录下新建一个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>
                <!-- 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>

4.创建sshe数据库:

打开cmd,输入mysql的用户名:mysql -uroot -p和密码:root

CREATE DATABASE sshe;

5.测试

在src/main/java中创建me.gac.model包,在包中编写一个 User类

package me.gacl.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 = "T_USER", schema = "SSHE")
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;
    }
}

 

在src/main/java中创建me.gacl.dao包,在包中编写一个 UserDaoI接口

package me.gacl.dao;

import java.io.Serializable;

import me.gacl.model.User;

public interface UserDaoI {

    /**
     * 保存用户
     * @param user
     * @return
     */
    Serializable save(User user);
}

 

在src/main/java中创建me.gacl.dao.impl包,在包中编写 UserDaoImpl实现类

package me.gacl.dao.impl;

import java.io.Serializable;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import me.gacl.dao.UserDaoI;
import me.gacl.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 me.gacl.service;

import java.io.Serializable;
import me.gacl.model.User;

/**
 * 测试
 * @author gacl
 *
 */
public interface UserServiceI {

    /**
     * 测试方法
     */
    void test();
   
    /**
     * 保存用户
     * @param user
     * @return
     */
    Serializable save(User user);
}

 

在UserServiceImpl类中实现save方法

package me.gacl.service.impl;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.gacl.dao.UserDaoI;
import me.gacl.model.User;
import me.gacl.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);
    }
}

 

在src/main/test下的me.gacl.test包中编写 TestHibernate类

package me.gacl.test;

import java.util.Date;
import java.util.UUID;

import me.gacl.model.User;
import me.gacl.service.UserServiceI;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHibernate {

    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("孤傲苍狼");
        user.setPwd("123");
        user.setCreatedatetime(new Date());
        userService.save(user);
    }
}

6.run as--junit

测试能够通过,并查看数据库

到此,Hibernate4开发环境的搭建并且与Spring整合的工作算是全部完成并且测试通过了。

五、三大框架综合测试

1.完善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>

2、编写测试代码

在TestAction类中添加一个saveUser方法

package me.gacl.action;

import java.util.Date;
import java.util.UUID;

import me.gacl.model.User;
import me.gacl.service.UserServiceI;

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;

@ParentPackage("basePackage")
@Action(value="strust2Test")//使用convention-plugin插件提供的@Action注解将一个普通java类标注为一个可以处理用户请求的Action
@Namespace("/")//使用convention-plugin插件提供的@Namespace注解为这个Action指定一个命名空间
public class TestAction {
   
    /**
     * 注入userService
     */
    @Autowired
    private UserServiceI userService;

    /**
     * http://localhost:8080/SSHE/strust2Test!test.action
     * MethodName: test
     * Description:
     * @author xudp
     */
    public void test(){
        System.out.println("进入TestAction");
        userService.test();
    }
   
    /**
     * http://localhost:8080/SSHE/strust2Test!saveUser.action
     */
    public void saveUser(){
        User user = new User();
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setName("xdp孤傲苍狼");
        user.setPwd("123456");
        user.setCreatedatetime(new Date());
        userService.save(user);
    }
}

 

修改TestSpring这个测试类中的test方法的代码

package me.gacl.test;

import me.gacl.service.UserServiceI;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {

    @Test
    public void test(){
        //通过spring.xml配置文件创建Spring的应用程序上下文环境
        //ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
        /**
         *因为已经整合了Hibernate,UserServiceImpl类中使用到了userDao,
         *userDao是由spring创建并且注入给UserServiceImpl类的,而userDao中又使用到了sessionFactory对象
         *而创建sessionFactory对象时需要使用到spring-hibernate.xml这个配置文件中的配置项信息,
         *所以创建Spring的应用程序上下文环境时,需要同时使用spring.xml和spring-hibernate.xml这两个配置文件
         *否则在执行Maven install命令时,因为maven会先执行test方法中的代码,而代码执行到
         *UserServiceI userService = (UserServiceI) ac.getBean("userService");
         *这一行时就会因为userDao中使用到sessionFactory对象无法正常创建的而出错,这样执行Maven install命令编译项目时就会失败!
         *
         */
        ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
        //从Spring的IOC容器中获取bean对象
        UserServiceI userService = (UserServiceI) ac.getBean("userService");
        //执行测试方法
        userService.test();
    }
}

 3.执行【Maven install】命令,再启动tomcat,输入地址:http://localhost:8080/SSHE/strust2Test!saveUser.action进行访问,访问没有出错会在控制台打印以下信息

 

 到此全部结束,此时可能会出现的错误是在建包期间,Javassist-XX-GA.jar这个包,要求删过一次,但是在新建完工程之初,自带的还有一个,我这里的解决方法是,在建完工程时,把pom.xml<dependencies>.....</dependencies>中的jar包全部删除,还是按步骤添加jar包,最后会在index.jsp中报错,再添加一个jar包解决

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>
  <scope>provided</scope>
 </dependency>

OK!有需要代码的,去http://download.csdn.net/download/fang30890/9985403下载

 

 

原创粉丝点击