网上虽然有很多SSH整合的小例子,但很多程序都出现了不是这样,就是那样的错误。自己总结了一下,终于做出的Struts+Spring+Hibernate整合的小例子,也是最基础的SSH实例,虽然是小例子,但什么程序都是从基础的做起。如果你弄明白了这个小实例,相信你的SSH整合框架技术也会提高很多。
在做本例前,需要熟悉对Struts,Hibernate的反向工程等的基本操作。
开发工具: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 …)
选择:
1)Struts specification: Struts 1.3
2)Base package for 那位classes:edu.syict.struts
3添加Spring支持(项目右键àMyEclipse Spring Capabilities …)
选择:
1) Spring version:Spring 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配置文件选择目录Folder:WebRoot/WEB-INF
Finish
4 添加Hibernate支持(项目右键àMyEclipse Hibernate Capabilities …)
选择:
1)Hibernate Specification:Hibernate3.1
2)Select the libraries to ad to the buildpath:Hibernate 3.1 Core Libraries
3)JAR Library Installation:Copy 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
6)Bean Id:dataSource
DB Driver:选择配置好的Hibernate。àNext
7)不建立SessionFactory(不选择Create SessionFactory class?)
8)Finish。
二 数据库方面
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 Object(POJO<>DB Table)复选框
其余的都不选择。àNext
Id Generator:native à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 case:register
Form Impl:Dynamic FormBean
Properties:username 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/> 密 码:<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 Id:dao
Bean class:edu.syict.dao.UserDaoImpl
PropertiesàAdd:Name:sessionFactory
Reference:sessionFactory
Finish
2)配置Action(RegisterAction)
右键àSpringàNew Bean:
Name(与上不同,上位Id):/register
Bean class:edu.syict.struts.action.RegisterAction
PropertiesàAdd:Name:userDao
Reference:dao
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> |
如有问题:
QQ:244077575
Email:lupeng0527@sina.com