在Eclipse上搭建SSH框架(Struts 2.5.1 + Spring 4.3.0 + Hibernate 4.3.11)

1、下载文件

Struts 2.5.1,地址:http://www.apache.org/dist/struts/2.5.1/struts-2.5.1-all.zip

Spring 4.3.0,地址:http://repo.spring.io/release/org/springframework/spring/4.3.0.RELEASE/spring-framework-4.3.0.RELEASE-dist.zip

Hibernate 4.3.11,地址:http://211.162.175.14/files/90490000022FD7D4/freefr.dl.sourceforge.net/project/hibernate/hibernate4/4.3.11.Final/hibernate-release-4.3.11.Final.zip

Eclipse 4.5.2,地址:http://mirrors.neusoft.edu.cn/eclipse/eclipse/downloads/drops4/R-4.5.2-201602121500/eclipse-SDK-4.5.2-win32-x86_64.zip

Log4j 2.6.1,地址:http://www.apache.org/dist/logging/log4j/2.6.1/apache-log4j-2.6.1-bin.zip

 

2、创建工程

2.1、打开Eclipse,新建Project,选择Web - Daynamic Web Object,点击Next。

2.2、设置Project name,例如:sshTest,Target Runtime选择New,弹出页面中选择Apache Tomcat V7.0,Next,选择Tomcat安装目录,选择JRE,点击Finish。工程窗口中点击Next。

2.3、源码与Build Path使用默认的值,点击Next。

2.4、选中Generate web.xml deployment descriptor。点击Finish。

 

3、创建MySQL数据库test,建立表User,新建用户devel,密码123456,授予devel对test数据库的所有权限。

create database test default charset utf8 collate utf8_general_ci;
use test;
create table user (
id int auto_increment not null,
userName varchar(50) not null,
password char(32) not null,
gender tinyint not null,
primary key(id)
)ENGINE=MyISAM;
grant all privileges on test.* to 'devel'@'localhost' identified by '123456';

 

4、编辑web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="sshTest" 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>sshTest</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

5、创建WEB-INF/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="<a target=_blank href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>"
 xmlns:xsi="<a target=_blank href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"
 xmlns:tx="<a target=_blank href="http://www.springframework.org/schema/tx">http://www.springframework.org/schema/tx</a>"
 xmlns:aop="<a target=_blank href="http://www.springframework.org/schema/aop">http://www.springframework.org/schema/aop</a>"
 xsi:schemaLocation="
 <a target=_blank href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a> <a target=_blank href="http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">http://www.springframework.org/schema/beans/spring-beans-4.3.xsd</a>
 <a target=_blank href="http://www.springframework.org/schema/tx">http://www.springframework.org/schema/tx</a> <a target=_blank href="http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">http://www.springframework.org/schema/tx/spring-tx-4.3.xsd</a>
 <a target=_blank href="http://www.springframework.org/schema/aop">http://www.springframework.org/schema/aop</a> <a target=_blank href="http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">http://www.springframework.org/schema/aop/spring-aop-4.3.xsd</a>
 ">
	<bean id="autowired" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="jdbcUrl">
			<value>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true</value>
		</property>
		<property name="user">
			<value>devel</value>
		</property>
		<property name="password">
			<value>123456</value>
		</property>
		<property name="maxPoolSize">
			<value>80</value>
		</property>
		<property name="minPoolSize">
			<value>1</value>
		</property>
		<property name="initialPoolSize">
			<value>1</value>
		</property>
		<property name="maxIdleTime">
			<value>20</value>
		</property>
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>org/ssh/beans/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="show_sql">true</prop>
				<prop key="hibernate.jdbc.batch_size">20</prop>
			</props>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="baseDao" class="org.ssh.daoImpl.UserDao">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
	<bean id="userManager" class="org.ssh.serviceImpl.UserManagerImpl">
		<property name="dao">
			<ref bean="baseDao" />
		</property>
	</bean>
	<bean id="registerAction" class="org.ssh.action.RegisterAction">
		<property name="userManager">
			<ref bean="userManager" />
		</property>
	</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
     <tx:method name="save*" propagation="REQUIRED"/> 
     <tx:method name="update*" propagation="REQUIRED"/>
     <tx:method name="delete*" propagation="REQUIRED"/>
     <tx:method name="*" read-only="true"/>
   </tx:attributes>
 </tx:advice>
 
 <aop:config>
   <aop:pointcut id="bussinessService" expression="execution(* org.ssh.daoImpl.*.*(..))" />
   <aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" />
 </aop:config>
</beans>


 6、各种文件与类

org.ssh.action.RegisterAction.java

package org.ssh.action;

import com.opensymphony.xwork2.ActionSupport;
import org.ssh.forms.UserForm;
import org.ssh.service.UserManager;

public class RegisterAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    private UserForm user;

    private UserManager userManager;

    public UserForm getUser() {
        return user;
    }

    public void setUser(UserForm user) {
        this.user = user;
    }

    public UserManager getUserManager() {
        return userManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public String execute() {
        try {
            userManager.regUser(user);
            return SUCCESS;

        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }

}

RegisterAction.java同目录下建立RegisterAction-validation.xml

<?xml version="1.0" encoding="GBK"?>
<!--
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">

 -->
 <!DOCTYPE validators PUBLIC
 "-//Apache Struts//XWork Validator 1.0.3//EN" 
 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>
    <!-- 添加对用户名的校验 -->
    <field name="user.userName">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>用户名不能为空</message>
        </field-validator>
        <field-validator type="regex">
            <param name="regex"><![CDATA[\w{6,16}]]></param>
            <message>用户名输入不合法,必须为长度在6~16中间的数字或字母</message>
        </field-validator>
    </field>
    
    <!-- 添加对密码的校验 -->
    <field name="user.password">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>密码不能为空</message>
        </field-validator>
        <field-validator type="regex">
            <param name="regex"><![CDATA[\w{6,16}]]></param>
            <message>密码输入不合法,必须为长度在6~16之间的数字或者字母</message>
        </field-validator>
    </field>
</validators>

org.ssh.beans.User.java

package org.ssh.beans;

public class User {
	private int id;
	private String userName;
	private String password;
	private int gender;
	
	public void setId(int id){
		this.id = id;
	}
	public int getId(){
		return id;
	}
	public void setUserName(String userName){
		this.userName = userName;
	}
	public String getUserName(){
		return userName;
	}
	public void setPassword(String password){
		this.password = password;
	}
	public String getPassword(){
		return password;
	}
	public void setGender(int gender){
		this.gender = gender;
	}
	public int getGender(){
		return gender;
	}
}

User.java同目录下建立User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.ssh.beans.User" table="USER">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="USERNAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
        <property name="gender" type="int">
            <column name="GENDER" />
        </property>
    </class>
</hibernate-mapping>

org.ssh.dao.BaseDao.java

package org.ssh.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;

public interface BaseDao {
    public void saveObject(Object obj) throws HibernateException;
}

org.ssh.daoImpl.UserDao.java

package org.ssh.daoImpl;

<p>import org.hibernate.HibernateException;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;</p><p>import org.ssh.dao.BaseDao;</p><p>public class UserDao extends HibernateDaoSupport implements BaseDao {
    
    @Override
    public void saveObject(Object obj) throws HibernateException {
     HibernateTemplate htpl = getHibernateTemplate();
     htpl.save(obj);
     htpl.flush();
    }</p><p>}
</p>

org.ssh.forms.UserForm.java

package org.ssh.forms;

public class User {
	private String userName;
	private String password;
	private int gender;
	
	public void setUserName(String userName){
		this.userName = userName;
	}
	public String getUserName(){
		return userName;
	}
	public void setPassword(String password){
		this.password = password;
	}
	public String getPassword(){
		return password;
	}
	public void setGender(int gender){
		this.gender = gender;
	}
	public int getGender(){
		return gender;
	}
}

org.ssh.service.UserManager.java

package org.ssh.service;

import org.ssh.forms.UserForm;

public interface UserManager {

    public void regUser(UserForm user);

}

org.ssh.serviceImpl.UserManagerImpl.java

package org.ssh.serviceImpl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.codec.digest.DigestUtils;
import org.ssh.beans.User;
import org.ssh.dao.BaseDao;
import org.ssh.forms.UserForm;
import org.ssh.service.UserManager;

public class UserManagerImpl implements UserManager {

    private BaseDao dao;
    private Session session;
    @Autowired
    private HttpServletRequest request;

    public void setDao(BaseDao dao) {
        this.dao = dao;
    }
    
    public BaseDao getDao() {
    	return dao;
    }

    @Override
    public void regUser(UserForm userForm) throws HibernateException {
    	System.out.println("Register from IP Address: " + request.getRemoteAddr());
    	User user = new User();
        BeanUtils.copyProperties(userForm, user);
        user.setPassword(DigestUtils.md5Hex(userForm.getPassword()));
        dao.saveObject(user);
    }

}

org.ssh.serviceImpl.HibernateSessionFactory.java

package org.ssh.serviceImpl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateSessionFactory {

    private static final String CFG_FILE_LOCATION = "hibernate.cfg.xml";

    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    private static final Configuration cfg = new Configuration().configure(CFG_FILE_LOCATION);

    private static StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());

    private static ServiceRegistry registry;

    private static SessionFactory sessionFactory;

    public static Session currentSession() throws HibernateException {
        Session session = threadLocal.get();

        if (session == null || session.isOpen() == false) {

            if (sessionFactory == null) {
                try {
                    registry = builder.build();
                    sessionFactory = cfg.buildSessionFactory(registry);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            session = sessionFactory.openSession();
            threadLocal.set(session);

        }

        return session;
    }

    public static void closeSession() throws HibernateException {
        Session session = threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close();
        }
    }

}

src/hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="HibernateSessionFactory">
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true</property>
        <property name="hibernate.connection.username">devel</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping resource="org/ssh/beans/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


src/hibernate.properties

hibernate.temp.use_jdbc_metadata_defaults=false
hibernate.bytecode.use_reflection_optimizer=false

src/log4j.properties

log4j.rootLogger=warn, stdout
log4j.logger.cn.sengtang=debug
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

src/struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <include file="struts-default.xml" />
    <constant name="struts.objectFactory" value="spring" />
    <package name="org.ssh" extends="struts-default">
        <action name="register" class="registerAction">
            <result name="input">/Register.jsp</result>
            <result name="success">/Success.jsp</result>
            <result name="error">/Failed.jsp</result>
        </action>
    </package>

</struts>


WebContent/Register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Register Page</title>
</head>
<body>

    <s:form action="register">
        <s:textfield name="user.userName" label="用户名"></s:textfield>
        <s:password name="user.password" label="密码"></s:password>
        <s:select list="#{'1':'男','0':'女'}" listKey="key" listValue="value" name="user.gender" label="性别" value="1"></s:select>
        <s:submit value="注册"></s:submit>
    </s:form>
</body>
</html>


WebContent下的Success.jsp与Failed.jsp随便写一句话即可,这里略过。

 

7、WEB-INF/lib下的jar文件:

antlr-2.7.7.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
c3p0-0.9.2.1.jar
commons-codec-1.10.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
commons-lang3-3.4.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
freemarker-2.3.23.jar
hibernate-c3p0-4.3.11.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.11.Final.jar
hibernate-entitymanager-4.3.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
log4j-api-2.5.jar
log4j-core-2.5.jar
mchange-commons-java-0.2.3.4.jar
ognl-3.1.8.jar
spring-aop-4.3.0.RELEASE.jar
spring-aspects-4.3.0.RELEASE.jar
spring-beans-4.3.0.RELEASE.jar
spring-context-4.3.0.RELEASE.jar
spring-context-support-4.3.0.RELEASE.jar
spring-core-4.3.0.RELEASE.jar
spring-expression-4.3.0.RELEASE.jar
spring-instrument-4.3.0.RELEASE.jar
spring-instrument-tomcat-4.3.0.RELEASE.jar
spring-jdbc-4.3.0.RELEASE.jar
spring-jms-4.3.0.RELEASE.jar
spring-messaging-4.3.0.RELEASE.jar
spring-orm-4.3.0.RELEASE.jar
spring-oxm-4.3.0.RELEASE.jar
spring-test-4.3.0.RELEASE.jar
spring-tx-4.3.0.RELEASE.jar
spring-web-4.3.0.RELEASE.jar
spring-webmvc-4.3.0.RELEASE.jar
spring-webmvc-portlet-4.3.0.RELEASE.jar
spring-websocket-4.3.0.RELEASE.jar
struts2-core-2.5.1.jar
struts2-spring-plugin-2.5.1.jar

 

备注:

1、将各种action/service/dao/托管给Spring,必须在struts.xml中设置

<constant name="struts.objectFactory" value="spring" />

这样struts.xml中设置的action的类就能用ID指向applicationContext.xml中的bean的ID

struts.xml: <action name="register" class="registerAction">
applicationContext.xml: <bean id="registerAction" class="org.ssh.action.RegisterAction">
		<property name="userManager">
			<ref bean="userManager" />
		</property>
	</bean>

2、在Spring能作用的类中,需要引用HttpServletRequest时,必须设置如下三点:

1)applicationContext.xml中设置Autowired处理器

<bean id="autowired" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

2)web.xml中添加Request监听

<listener>
	<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

3)在java文件中添加@Autowired注释

import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;

Class AnyClass {
    @Autowired
    private HttpServletRequest request;
}




 

你可能感兴趣的:(eclipse,spring,Hibernate,struts,struts2.0)