Struts+Spring+Hibernate--SSH整合实例

在做本例前,需要熟悉对Struts,Hibernate的反向工程等的基本操作。

开发工具:MyEclipse+MySQL+Tomcat

说明:本实例是简单注册程序(只有两个属性)

数据库脚本:user.sql

DROPTABLEIFEXISTS`user`;

CREATETABLE`user`(

`Id`int(11)NOTNULLAUTO_INCREMENT,

`username`varchar(255)DEFAULTNULL,

`password`varchar(255)DEFAULTNULL,

PRIMARYKEY(`Id`)

)ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8;

开发步骤:

1建立Web项目

选择:JavaEE5.5

2添加Struts支持(项目右键àMyEclipseStrutsCapabilities…)

选择:

1)Strutsspecification:Struts1.3

2)Basepackagefor那位classes:edu.syict.struts

3添加Spring支持(项目右键àMyEclipseSpringCapabilities…)

选择:

1)Springversion:Spring2.0

2)Selectthelibrariestoaddthebuildpath:

Spring2.0AOPLibraries

Spring2.0CoreLibraries

Spring2.0PersistenceCoreLibraries

Spring2.0PersistenceJDBCLibraries

Spring2.0WebLibraries

3)JARLibraryInstallation:

CopycheckedLibrarycontentstoprojectfolder(TLDsalwayscopied)

Next

4)Spring配置文件选择目录Folder:WebRoot/WEB-INF

Finish

4添加Hibernate支持(项目右键àMyEclipseHibernateCapabilities…)

选择:

1)HibernateSpecification:Hibernate3.1

2)Selectthelibrariestoadtothebuildpath:Hibernate3.1CoreLibraries

3)JARLibraryInstallation:CopycheckedLibraryJarstoprojectfolderandaddtobuild-path

Next

4)选择:Springconfigurationfile(applicationContext.xml)Next

5)选择:ExistingSpringconfigurationfile

SessionFactoryId:sessionFactoryàNext

6)BeanId:dataSource

DBDriver:选择配置好的Hibernate。àNext

7)不建立SessionFactory(不选择CreateSessionFactoryclass?)

8)Finish。

二数据库方面

1)建立包edu.syict.pojo

Hibernate反向工程:

选择下列内容:

CreatePOJO<>DBTablemappinginformation复选框

CreateaHibernatemappingfile单选框

UpdateHibernateconfigurationwithmappingresourcelocation复选框

JavaDataObject(POJO<>DBTable)复选框

其余的都不选择。àNext

IdGenerator:nativeàFinish

2)新建接口:edu.syict.dao.UserDao.java(所在包:edu.syict.dao)

packageedu.syict.dao;

importedu.syict.pojo.User;

publicinterfaceUserDao{

publicvoidsave(Useruser);

}

3)建立UserDao接口实现类edu.syict.dao.impl.UserDaoImpl

类继承HibernateDaoSupport,接口继承UserDao

packageedu.syict.dao;

importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;

importedu.syict.pojo.User;

publicclassUserDaoImplextendsHibernateDaoSupportimplementsUserDao{

publicvoidsave(Useruser){

try{

this.getHibernateTemplate().saveOrUpdate(user);

}catch(RuntimeExceptionre){

throwre;

}

}

}

三建立JSP页面,Action类

1)打开struts-config.xml配置文件:右键newàForm,ActionandJSP

2)Usercase:register

FormImpl:DynamicFormBean

Properties:usernamepassword

JSP:选择CreateJSPformàNext

3)Action默认就可以了àFinish

4)配置struts-config.xml文件,将Struts交给Spring管理

a)加入插件(message-resources标记下)

<plug-inclassname="org.springframework.web.struts.ContextLoaderPlugIn">

<set-propertyproperty="contextConfigLocation"

value="/WEB-INF/applicationContext.xml"/>

</plug-in>

b)将Action类移交(message-resources标记上)

<controllerprocessorclass="org.springframework.web.struts.DelegatingRequestProcessor"/>

struts-config.xml文件(全部)

struts-config.xml文件(全部)

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEstruts-configPUBLIC"-//ApacheSoftwareFoundation//DTDStrutsConfiguration1.3//EN""http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

<form-beans>

<form-beanname="registerForm"type="org.apache.struts.action.DynaActionForm">

<form-propertyname="password"type="java.lang.String"/>

<form-propertyname="username"type="java.lang.String"/>

</form-bean>

</form-beans>

<global-exceptions/>

<global-forwards/>

<action-mappings>

<action

attribute="registerForm"

input="/form/register.jsp"

name="registerForm"

path="/register"

scope="request"

type="edu.syict.struts.action.RegisterAction"/>

</action-mappings>

<controllerprocessorclass="org.springframework.web.struts.DelegatingRequestProcessor"/>

<message-resourcesparameter="edu.syict.struts.ApplicationResources"/>

<plug-inclassname="org.springframework.web.struts.ContextLoaderPlugIn">

<set-propertyproperty="contextConfigLocation"

value="/WEB-INF/applicationContext.xml"/>

</plug-in>

</struts-config>

5)register.jsp页面(WebRoot/form/register.jsp)

<%@pagelanguage="java"pageEncoding="UTF-8"%>

<%@tagliburi="http://struts.apache.org/tags-bean"prefix="bean"%>

<%@tagliburi="http://struts.apache.org/tags-html"prefix="html"%>

<html>

<head>

<title>用户注册</title>

</head>

<body>

SSH整合<br><hr>

<h3>用户注册</h3>

<html:formaction="/register">

用户名:<html:textproperty="username"/><html:errorsproperty="username"/><br/>

密&nbsp;&nbsp;&nbsp;&nbsp;码:<html:textproperty="password"/><html:errorsproperty="password"/><br/>

<html:submitvalue="注册"/>&nbsp;&nbsp;&nbsp;&nbsp;<html:resetvalue="重置"/>

</html:form>

</body>

</html>

6)修改RegisterAction.java

packageedu.syict.struts.action;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;

importorg.apache.struts.action.ActionForm;

importorg.apache.struts.action.ActionForward;

importorg.apache.struts.action.ActionMapping;

importorg.apache.struts.action.DynaActionForm;

importedu.syict.dao.UserDao;

importedu.syict.pojo.User;

publicclassRegisterActionextendsAction{

//数据库Dao接口,并添加get方法,

privateUserDaodao;

publicvoidsetDao(UserDaodao){

this.dao=dao;

}

publicActionForwardexecute(ActionMappingmapping,ActionFormform,

HttpServletRequestrequest,HttpServletResponseresponse){

DynaActionFormregisterForm=(DynaActionForm)form;

//在控制台输出

System.out.println(registerForm.get("username"));

System.out.println(registerForm.get("password"));

Useruser=newUser();

user.setUsername((String)registerForm.get("username"));

user.setPassword((String)registerForm.get("password"));

dao.save(user);//向数据库中保存信息

returnnewActionForward("/form/register.jsp");

}

}

四修改Spring配置文件applicationContext.xml

1)配置数据库UserDao

右键àSpringàNewBean:

BeanId:dao

Beanclass:edu.syict.dao.UserDaoImpl

PropertiesàAdd:Name:sessionFactory

Reference:sessionFactory

Finish

2)配置Action(RegisterAction)

右键àSpringàNewBean:

Name(与上不同,上位Id):/register

Beanclass:edu.syict.struts.action.RegisterAction

PropertiesàAdd:Name:userDao

Reference:dao

applicationContext.xml全部

<?xmlversion="1.0"encoding="UTF-8"?>

<beans

xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<beanid="sessionFactory"

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<propertyname="dataSource">

<refbean="dataSource"/>

</property>

<propertyname="hibernateProperties">

<props>

<propkey="hibernate.dialect">

org.hibernate.dialect.MySQLDialect

</prop>

</props>

</property>

<propertyname="mappingResources">

<list>

<value>edu/syict/pojo/User.hbm.xml</value></list>

</property>

</bean>

<beanid="dao"class="edu.syict.dao.UserDaoImpl">

<propertyname="sessionFactory">

<refbean="sessionFactory"/>

</property>

</bean>

<!--/register与Action中的path相同-->

<beanname="/register"

class="edu.syict.struts.action.RegisterAction">

<!--RegisterAction中住的DAO的名称-->

<propertyname="userDao">

<!--上面数据库Bean的id-->

<refbean="dao"/>

</property>

</bean>

</beans>

五修改web.xml文件

添加Spring提供的过滤器,并修改欢迎页面(form/register.jsp)

web.xml

<!--Spring提供的过滤器_Start-->

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/applicationContext.xml</param-value>

</context-param>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<!--Spring提供的过滤器_End-->

<!--欢迎页面-->

<welcome-file-list>

<welcome-file>form/register.jsp</welcome-file>

</welcome-file-list>

</web-app>

相关推荐