[转载]Struts+Spring+Hibernate--SSH整合实例

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

开发工具:MyEclipse+MySQL+Tomcat

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

数据库脚本:user.sql

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (

`Id` int(11) NOT NULL AUTO_INCREMENT,

`username` varchar(255) DEFAULT NULL,

`password` varchar(255) DEFAULT NULL,

PRIMARY KEY (`Id`)

) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 

开发步骤:

1建立Web项目

   选择: Java EE 5.5

2添加Struts支持(项目右键àMyEclipse Struts Capabilities …

       选择:

1Struts specificationStruts 1.3

2Base package for 那位classesedu.syict.struts

3添加Spring支持(项目右键àMyEclipse Spring Capabilities …

       选择:

1) Spring versionSpring 2.0

2) Select the libraries to add the buildpath

Spring 2.0 AOP Libraries

Spring 2.0 Core Libraries

Spring 2.0 Persistence Core Libraries

Spring 2.0 Persistence JDBC Libraries

Spring 2.0 Web Libraries

       3) JAR Library Installation

Copy checked Library contents to project folderTLDs always copied

       Next

4) Spring配置文件选择目录FolderWebRoot/WEB-INF

Finish

4 添加Hibernate支持(项目右键àMyEclipse Hibernate Capabilities …

       选择:

       1Hibernate SpecificationHibernate3.1

       2Select the libraries to ad to the buildpathHibernate 3.1 Core Libraries

3JAR Library InstallationCopy checked Library Jars to project folder and add to build-path

Next

4)选择:Spring configuration file(applicationContext.xml) Next

       5)选择:Existing Spring configuration file

SessionFactory IdsessionFactory àNext

       6Bean IddataSource

DB Driver:选择配置好的Hibernate。àNext

       7)不建立SessionFactory(不选择Create SessionFactory class?

       8Finish

二 数据库方面

       1)建立包edu.syict.pojo

Hibernate反向工程:

          选择下列内容:

Create POJO<>DB Table mapping information复选框

                     Create a Hibernate mapping file单选框

                     Update Hibernate configuration with mapping resource location复选框

            Java Data ObjectPOJO<>DB Table)复选框  

            其余的都不选择。àNext          

Id Generatornative àFinish

 

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

 

package edu.syict.dao;

import edu.syict.pojo.User;

public interface UserDao {

    public void save(User user);

}

 

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

       类继承HibernateDaoSupport,接口继承UserDao

 

package edu.syict.dao;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import edu.syict.pojo.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

    public void save(User user) {

       try{

           this.getHibernateTemplate().saveOrUpdate(user);

       }catch(RuntimeException re){

           throw re;

       }

    }

}

 

三 建立JSP 页面,Action

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

       2) User caseregister

       Form ImplDynamic FormBean

       Propertiesusername password

       JSP:选择Create JSP form àNext

3) Action 默认就可以了 àFinish

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

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

 

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

    <set-property property="contextConfigLocation"

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

</plug-in>

 

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

 

<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>

 

       struts-config.xml文件(全部)

       struts-config.xml文件(全部)

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

 

<struts-config>

<form-beans >

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

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

      <form-property name="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>

<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>

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

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

    <set-property property="contextConfigLocation"

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

</plug-in>  

</struts-config>

 

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

 

<%@ page language="java" pageEncoding="UTF-8"%>

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

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

 

<html>

    <head>

       <title>用户注册</title>

    </head>

    <body>

    SSH整合<br><hr>

    <h3>用户注册</h3>

       <html:form action="/register">

           用户名:<html:text property="username"/><html:errors property="username"/><br/>

           密&nbsp;&nbsp;&nbsp;&nbsp;码:<html:text property="password"/><html:errors property="password"/><br/>          

           <html:submit value="注册"/>&nbsp;&nbsp;&nbsp;&nbsp;<html:reset value="重置"/>

       </html:form>

    </body>

</html>

 

  

6)修改RegisterAction.java

 

package edu.syict.struts.action;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.DynaActionForm;

 

import edu.syict.dao.UserDao;

import edu.syict.pojo.User;

 

public class RegisterAction extends Action {

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

    private UserDao dao;

    public void setDao(UserDao dao) {

       this.dao = dao;

    

    public ActionForward execute(ActionMapping mapping, ActionForm form,

           HttpServletRequest request, HttpServletResponse response) {

       DynaActionForm registerForm = (DynaActionForm) form;

      

       //在控制台输出

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

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

      

       User user=new User();

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

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

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

             

       return new ActionForward("/form/register.jsp");

    }

}

   

 

四 修改Spring配置文件applicationContext.xml      

       1)配置数据库UserDao

右键àSpringàNew Bean

              Bean Iddao

              Bean classedu.syict.dao.UserDaoImpl

              PropertiesàAddNamesessionFactory

                                   ReferencesessionFactory

          Finish

       2)配置ActionRegisterAction

右键àSpringàNew Bean

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

              Bean classedu.syict.struts.action.RegisterAction

              PropertiesàAddNameuserDao

                            Referencedao

applicationContext.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"

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

 

 

   

 

 

 

        <bean id="sessionFactory"

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

       <property name="dataSource">

           <ref bean="dataSource" />

       </property>

       <property name="hibernateProperties">

           <props>

              <prop key="hibernate.dialect">

                  org.hibernate.dialect.MySQLDialect

              </prop>

           </props>

       </property>

       <property name="mappingResources">

           <list>

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

       </property>

    </bean>

    <bean id="dao" class="edu.syict.dao.UserDaoImpl">

       <property name="sessionFactory">

           <ref bean="sessionFactory" />

       </property>

    </bean>

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

    <bean name="/register"

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

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

       <property name="userDao">

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

           <ref bean="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>

 

posted @ 2012-07-03 16:29  刘竹青  阅读(165)  评论(0编辑  收藏  举报