在做本例前,需要熟悉对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文件(全部)
<?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/beanshttp://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>
SSH的整合使用 (2) 开发工具:Eclipse3.1,MyEclipse4.0 ,Tomcat5.0.28,mysql-4.0.1 开发步骤: 1:创建web projectSSHlogin 加入struts1.2 创建loginForm选择DynaValidatorForm,加入password,username,创建jsp文件打上钩,将路径改为 /login.jsp,然后下一步,改LoginAction的Input source改为/login.jsp,加入 <forward name="ok" path="ok.jsp" />点击完成 完成后修改struts-config.xml文件加入 <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" /> </plug-in> 拷贝validator-rules.xml和validation.xml到WEB-INF目录中 在validation.xml文件中加入 <form-validation> <formset> <form name="loginForm"> <field property="username" depends="required"> <arg0 key="prompt.username" /> </field> <field property="password" depends="required"> <arg0 key="prompt.password" /> </field> </form> </formset> </form-validation> validator-rules.xml文件直接考一个就行。 编辑资源文件“ApplicationResources.properties” 增加以下内容 prompt.username=User Name prompt.password=User Password errors.required={0} is required. 修改LoginAction.java文件的execute方法,内容如下 public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { DynaValidatorForm loginForm = (DynaValidatorForm) form; String username=loginForm.getString("username"); String password=loginForm.getString("password"); if(username.equals("test")||password.equals("test")){ return mapping.findForward("indexGo"); }else{ return mapping.getInputForward(); } } 好了,现在可以启动Tomcat进行测试了如果不输入任何数据而直接提交表单的话就可以看到效果了。 好了,如果没有什么问题的话就继续往下看吧,如果有问题的话就得往上看了^_^ 2:加入Spring框架 在这里我将Spring所有的包全部加载进去,因为我还不知道具体用到哪些类,全部加进去方便点 单选框选第二个,这样的话所有的类库和标签等都将拷贝到项目中去,这样方便以后的布署 下一步后是创建配置文件,将文件放到“WebRoot/WEB-INF”目录下,文件名称为“applicationContext.xml” 配置struts-config.xml文件,添加(spring)的插件 <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" /> </plug-in> 修改LoginAction配置 原: <action attribute="loginForm" input="/login.jsp" name="loginForm" path="/login" scope="request" validate="true" type="com.test.struts.action.LoginAction" > <forward name="ok" path="ok.jsp" /> </action> </action-mappings> 改为: <action attribute="loginForm" input="/login.jsp" name="loginForm" path="/login" scope="request" validate="true" type="org.springframework.web.struts.DelegatingActionProxy"> <forward name="ok" path="ok.jsp" /> </action> </action-mappings> 这里将使用spring的代理器来对Action进行控制 当提交到/login.do是将控制权交给了spring,然后由spring来决定是否转回到struts的Action 现在来配置spring <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean name="/login" class="com.test.struts.action.LoginAction" singleton="false"></bean> </beans> 好了,现在可以启动Tomcat进行测试了如果没有什么问题的话就继续往下看吧,如果有问题的话就得往上看了^_^ 3:创建Hibernate框架 建立数据库在 这里我使用的是mysql4.1.18 CREATE TABLE `user` ( `ID` int(11) NOT NULL auto_increment, `USERNAME` varchar(50) NOT NULL default '', `PASSWORD` varchar(50) NOT NULL default '', PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 添加记录 insert into user (USERNAME,PASSWORD) values ('test','test') 在配置界面中配置数据库的连接部份,重要的是点击链接将jdbc驱动拷贝到lib目录中 使用MyEclipse的数据Database Explorer工具创建User.hmb.xml、AbstractUser.java、User.java映射文件 创建UserDAO.java、UserDAOImp.java UserDAO.java: public interface UserDAO { public abstract boolean isValidUser(String username, String password); } UserDAOImp.java: import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class UserDAOImp extends HibernateDaoSupport implements UserDAO { private static String hql = "from User u where u.username=? and password=?"; public boolean isValidUser(String username, String password) { String[] userlist=new String[2]; userlist[0]=username; userlist[1]=password; List userList = this.getHibernateTemplate().find(hql,userlist); if (userList.size() > 0) { return true; } return false; } } SSH整合实例(3)
所谓SSH就是spring+struts+hibernate的整合。他们各司其职:hibernate对数据持久化进行操作,struts对页面和 Action进行交互与控制。而spring它就象一个轻量型的容器,它把struts和hibernate通过代理模式写入自己的XML中并对其进行管 理。它包括IOC和AOP,它们实现了对对象的生成,组装和销毁。另外它还对事务,国际化,持久化的支持。
下面用一个用户登录的页面来进行一个小小的整合。 包结构:src ---entity ---dao ---biz ---sql ----config ---web 1.在entity包下建User.java 代码:package com.kettas.entity; import java.io.Serializable; public class User implements Serializable{ private Integer uid; private String name; private String password; public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User() { super(); // TODO Auto-generated constructor stub } public User(String name, String password) { super(); this.name = name; this.password = password; } } 2.sql包中建数据库:user.sql create table u_table( id number(7) primary key, name varchar2(15), password varchar2(15) ); create sequence u_table_seq; insert into u_table values(1001,'admin','admin'); insert into u_table values(1002,'liang','liang'); insert into u_table values(1003,'amanda','1234'); insert into u_table values(1004,'aaaa','1111'); 3.entity包下建user.hbm.xml 其中代码: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="com.entity"> <class name="User" table="u_table"> <id name="uid" column="id"> <generator class="sequence"> <param name="sequence">u_table_seq</param> </generator> </id> <property name="name" column="name"></property> <property name="password"></property> </class> </hibernate-mapping> 4.在dao和biz包中分别建立UserDao.java UserBiz.java 接口,具体实现略。 public interface UserDao { public void insert(User user); public void update(User user); public void delete(Integer id); public User queryById(Integer id); public List<User> queryAll(Page page); public User selectByName(String username); public User selectById(Integer id); } public interface UserBiz { public User login(String userName,String password); } 5.index.jsp ok.jsp failed.jsp index.jsp <%@ page contentType="text/html; charset=utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <h3 align="center"> 欢迎来到主页面 </h3> <form action="<%=request.getContextPath()%>/login.do" method="post"> <table align="center"> <tr> <td align="center"> 用户名: </td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td align="center"> 密码: </td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td> <input type="submit" name="submit"> </td> <td> <input type="reset" name="reset"> </td> </tr> </table> </form> </body> </html> 6.下面该进行配置了
Hibernate:主要是对数据持久化操作。hibernate.cfg.xml 在src 下面
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" > <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">sa</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <property name="dialect"> org.hibernate.dialect.Oracle9Dialect </property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="current_session_context_class">thread</property> <mapping resource="com/entity/User.hbm.xml" /> </session-factory> </hibernate-configuration> 7.Struts方面: 7.1 在web包下建UserAction.java public class UserAction extends MappingDispatchAction { private UserBiz userBiz; public UserBiz getUserBiz() { return userBiz; } public void setUserBiz(UserBiz userBiz) { this.userBiz = userBiz; } public ActionForward login(ActionMapping mapping,ActionForm form,HttpServletRequest req,HttpServletResponse resp) throws IOException{ String username= req.getParameter("username"); String password = req.getParameter("password"); User u = userBiz.login(username, password); if(u!=null &&username.equals(u.getName()) && password.equals(u.getPassword())){ req.getSession().setAttribute(username, u); return mapping.findForward("ok"); }else{ return mapping.findForward("ff"); } } } 7.2 在在WEB-INF下建立web.xml <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> 7.3 在在WEB-INF下建立stuts-config.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config> <action-mappings> <action path="/login" type="org.springframework.web.struts.DelegatingActionProxy" parameter="login"> <forward name="ok" path="/ok.jsp" /> <forward name ="ff" path="/failed.jsp"/> </action> </action-mappings> </struts-config> 8.spring方面 8.1 对spring:在config包下建立bean.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" > <beans> <bean id="factory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:Hibernate.cfg.xml</value> </property> </bean> <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="factory"/> </property> </bean> <bean id="basicdao" class="com.dao.BasicDao" abstract="true"> <property name="template"> <ref bean="template"/> </property> </bean> <bean id="userdao" class="com.dao.impl.UserDaoImpl" parent="basicdao"></bean> <bean id="dao" class="com.dao.impl.ManagerModelDaoImpl" parent="basicdao"></bean> <bean id="biz" class="com.biz.impl.ManagerModelBizImpl"> <property name="dao"> <ref bean="dao"/> </property> </bean> <bean id="ubiz" class="com.biz.impl.UserBizImpl"> <property name="userDao"> <ref bean="userdao"/> </property> </bean> <bean id="transaction" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="factory"/> </property> </bean> <bean id="interceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> <property name="transactionManager"> <ref bean="transaction"/> </property> </bean> <bean id="proxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <value>*biz</value> </list> </property> <property name="interceptorNames"> <list> <value>interceptor</value> </list> </property> </bean> <bean name="/login" class="com.web.UserAction"> <property name="userBiz"> <ref bean="ubiz"/> </property> </bean> </beans> 8.2 web.xml 添加如下代码: <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/com/config/bean.xml</param-value> </context-param> 最后编译成功运行。 |