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

 

网上虽然有很多SSH整合的小例子,但很多程序都出现了不是这样,就是那样的错误。自己总结了一下,终于做出的Struts+Spring+Hibernate整合的小例子,也是最基础的SSH实例,虽然是小例子,但什么程序都是从基础的做起。如果你弄明白了这个小实例,相信你的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 specification Struts 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 folder TLDs 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 Id sessionFactory à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标记上)

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

               码:<html:text property="password"/><html:errors property="password"/><br/>          

           <html:submit value="注册"/>    <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.xmlvalue>list>

       property>

    bean>

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

       <property name="sessionFactory">

           <ref bean="sessionFactory" />

       property>

    bean>

   

    <bean name="/register"

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

      

       <property name="userDao">

          

           <ref bean="dao" />

       property>

    bean>

beans>

修改web .xml文件

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

web.xml

<filter>

    <filter-name>encodingFilterfilter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>

    <init-param>

       <param-name>encodingparam-name>

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

    init-param>

    <init-param>

       <param-name>forceEncodingparam-name>

       <param-value>trueparam-value>

    init-param>

filter>

<context-param>

    <param-name>contextConfigLocationparam-name>

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

context-param>

<filter-mapping>

    <filter-name>encodingFilterfilter-name>

    <url-pattern>/*url-pattern>

filter-mapping>

<listener>

    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

listener>

   <welcome-file-list>

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

welcome-file-list>

web-app>

如有问题:

QQ244077575

Email[email protected]

你可能感兴趣的:(Java)