您的位置:首页 > 编程语言 > Java开发

Struts+Spring+Hibernate整合的简单实例

2012-09-21 22:01 573 查看
SSH具体操作:

1.Struts的简单使用

2.Spring的简单使用

3.Hibernate的简单使用

通过Struts+Spring+Hibernate来实现一个简单的增删改查操作。我们分三层处理这个应用:一、表现层,我们使用Struts实现,负责处理用户请求,提供一个控制其代理。不适合在这层出现JDBC以及业务逻辑。二、持久层,使用Hibernate来查询相关信息、保存更新和删除数据库信息。业务逻辑同样不适合出现在该层。三、业务层,使用Spring来连接Bean,实现业务逻辑和业务验证,预留接口,管理业务层对象之间的依赖。这里程序通过edit,index和input.jsp三个页面实现对数据的增删改查操作。

整合SSH的步骤为:

1. 新建WEB项目

MyEclipse下使用快捷键Alt+Shift+N新建一个WebProject项目,命名为SSH_example,选择JavaEE5.0。

2. 增加Hibernate、Spring开发能力

导入Hibernate开发能力,注意最后一项时不要创建sessionFactory类。Spring导入Cord、AOP、persistenceCore、persistenceJDBC和WebLibraries五个库。最后创建SessionFactory类,使用Spring容器进行统一管理。

3. 增加POJO类文件和Hibernate映射文件

打开DataBaseExplorer视图,将表test生成POJO类和映射文件。这些文件放在com.sshexample.model中。

4. 编写DAO接口和实现类

DAO接口放在包com.sshexample.dao中,代码为:

package com.sshexample.dao;
import java.util.List;
import com.sshexample.model.Test;
public interface TestDao {
//保存
       public void save(Testt);
//     删除
       public voiddelete(Integer i);
//     获得所有对象
       public List getAll();
//     获得一个对象
       public TestgetTest(Integer id);
}


其实现类代码实现该接口的同时继承自HibernateDaoSupport超类,放置在包com.sshexample.dao.hibernate中,实现了增删改查的具体操作,代码如下:

package com.sshexample.dao.hibernate;
 
import java.util.List;
 
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
 
import com.sshexample.dao.TestDao;
import com.sshexample.model.Test;
 
public class TestDaoHibernate extends HibernateDaoSupport implementsTestDao {
       public voiddelete(Integer id) {
              this.getHibernateTemplate().delete(getTest(id));
       }
       public List getAll() {
              returnthis.getHibernateTemplate().find("from Test");
       }
       public TestgetTest(Integer id) {
              return(Test)this.getHibernateTemplate().get(Test.class, id);
       }
       public void save(Test t){
              this.getHibernateTemplate().saveOrUpdate(t);
       }
}


5. 编写服务层接口和实现类

在包com.sshexample.service中,新建服务层接口TestManager,定义增删改查操作接口,这里的增删改查和DAO接口操作类似,但服务对象则是Web层,可能会有一些启发方法。而DAO中,只声明了数据库基本操作。在com.sshexample.service.impl中定义TestManagerImpl实现类,实现了上文中的TestManager接口。

接口TestManager代码为:

packagecom.sshexample.service;
 
importjava.util.List;
 
importcom.sshexample.model.Test;
 
public interfaceTestManager {
       //保存
       public void save(Test t);
//     删除
       public void delete(String id);
//     获得所有对象
       public List getAll();
//     获得一个对象
       public Test getTest(String id);
}


实现类TestManagerImpl代码为:

packagecom.sshexample.service.impl;
 
importjava.util.List;
 
importcom.sshexample.dao.TestDao;
importcom.sshexample.model.Test;
import com.sshexample.service.TestManager;
 
public classTestManagerImpl implements TestManager {
       private TestDao testDao;
       public TestDao getTestDao() {
              return testDao;
       }
 
       public void setTestDao(TestDao testDao) {
              this.testDao = testDao;
       }
 
       public void delete(String id) {
              testDao.delete(new Integer(id));
       }
 
       public List getAll() {
              return testDao.getAll();
       }
 
       public Test getTest(String id) {
              return testDao.getTest(newInteger(id));
       }
 
       public void save(Test t) {
              testDao.save(t);
       }
 
}


6. 修改Spring配置文件

在Spring配置文件applicationContext.xml文件的源码格式下,右击选Spring->newDataSource,新建一个数据源Bean。设值为之前的SQLServer2005 Conn,如果提示出错,可能需要附加Spring PersistenceJDBC库。再新建一个Bean,ID为testDao,class为上文中实现了DAO操作的具体类testDaoHibernate。在其中添加一个属性sessionFactory作为注入的入口。注意保持name栏和具体实现类testDaoHibernate中得方法setTestDao方法名的后半段一致,以方便注入。

7. 增加Struts开发能力

附加struts开饭能力,选择Struts1.3版本,将基础包修改为com.sshexample.web。

8. 新建FormBean

修改Struts-config.xml文件,新建一个From,Action and JSP项目,用例名为test,表格类型为动态表格,添加一个属性为name。下一步进行Action类配置,超类选择分发器动作dispatchAction。去掉输入源前面的form。



9. 编辑Action类TestAction.java实现了操作。

packagecom.sshexample.web.action;
 
importjava.util.List;
 
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.action.DynaActionForm;
importorg.apache.struts.actions.DispatchAction;
 
importcom.sshexample.model.Test;
importcom.sshexample.service.TestManager;
 
public classTestAction extends DispatchAction {
       //testManager对象
       private TestManager testManager;
       //注入口
       public void setTesetManager(TestManagertesetManager) {
              this.testManager = tesetManager;
       }
       //     编辑方法
       public ActionForward edit(ActionMappingmapping, ActionForm form,
                     HttpServletRequest request,HttpServletResponse response){
//            动态ActionForm实例化
              DynaActionForm testForm =(DynaActionForm)form;
//            参数
              String id =request.getParameter("id");
//            获得test对象
              Test t = testManager.getTest(id);
//            设值
              testForm.set("name",t.getName());
//            存储ID到request
              request.setAttribute("id",id);
              returnmapping.findForward("edit");          
       }
       //更新数据
       public ActionForward save(ActionMappingmapping, ActionForm form,
                     HttpServletRequest request,HttpServletResponse response){
//            动态ActionForm实例化
              DynaActionForm testForm =(DynaActionForm)form;
//            参数
              String id =request.getParameter("id");
//            获得test对象
              Test t = null;
              if(id==null){
                     t = new Test();
              }else{
                     t=testManager.getTest(id);
              }
//            设值
              t.setName((String)testForm.get("name"));
              testManager.save(t);
              returnlist(mapping,form,request,response);
       }
       //delete
       public ActionForward delete(ActionMappingmapping, ActionForm form,
                     HttpServletRequest request,HttpServletResponse response){
              String id =request.getParameter("id");
              testManager.delete(id);
              returnlist(mapping,form,request,response);
       }
       private ActionForward list(ActionMappingmapping, ActionForm form,
                     HttpServletRequest request,HttpServletResponse response) {
              List list = testManager.getAll();
              request.setAttribute("test",list);
              returnmapping.findForward("display");
       }
       public ActionForwardunspecified(ActionMapping mapping, ActionForm form,
                     HttpServletRequest request,HttpServletResponse response){
              return null;
       }
       public ActionForwardexecute(ActionMapping mapping, ActionForm form,
                     HttpServletRequest request,HttpServletResponse response) {
              DynaActionForm testForm =(DynaActionForm) form;// TODO Auto-generated method stub
              return null;
       }
}


这些代码中,我们使用了TestManager类,需要在配置文件中依赖注入之。

10. 编辑JSP页面

新建edit.jsp,input.jsp和display.jsp三个页面。对这三个页面进行修改。

Display.jsp:

<%@ pagelanguage="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
    <%@ tagliburi="http://struts.apache.org/tags-html" prefix="html"%>
    <%@ tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPEhtml PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Inserttitle here</title>
</head>
<body>
All items:
<table>
<tr>
        <th>id</th>
        <th>name</th>
        <th>edit</th>
        <th>delete</th>
</tr>
<c:forEach items="${requestScope['test']}"var="info">
        <tr>
               <td><c:outvalue="${info.id}"></c:out></td>
               <td><c:outvalue="${info.name}"></c:out></td>
               <td><ahref="<c:urlvalue="/test.do?method=edit&id=${info.id}"/>">[E]</a></td>
               <td><ahref="<c:url value="/test.do?method=delete&id=${info.id}"/>">[X]</a></td>
        </tr>
</c:forEach>
</table>
<ahref="input.jsp">Insert</a>
</body>
</html>


Input.jsp

<%@ pagelanguage="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
    <%@ tagliburi="http://struts.apache.org/tags-html" prefix="html"%>
    <%@ tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPEhtml PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Inserttitle here</title>
</head>
<body>
<html:formaction="/test">
name:<html:textproperty="name"></html:text>
<html:errors property="name"/>
<html:hidden property="method"value="save"/>
<html:submit>tijiao</html:submit>
<a href="<c:urlvalue="/test.do?method=list"/>">All Items</a>
</html:form>
</body>
</html>


Edit.jsp

<%@ pagelanguage="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
    <%@ tagliburi="http://struts.apache.org/tags-html" prefix="html"%>
    <%@ tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPEhtml PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Inserttitle here</title>
</head>
<body>
<html:formaction="/test">
name:<html:textproperty="name"></html:text>
<html:errors property="name"/>
<html:hidden property="id"value="${requestScope['id']}"/>
<html:hidden property="method"value="save"/>
<html:submit>tijiao</html:submit>
<a href="<c:urlvalue="/test.do?method=list"/>">fanhui</a>
</html:form>
</body>
</html>


11. 修改Web.xml、struts-config.xml和Spring配置文件

为以上项目建立关联关系,删除hibernater的数据库连接信息。

12. 部署运行项目

参考博文:

1.Struts的简单使用

2.Spring的简单使用

3.Hibernate的简单使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: