Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30467991
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2008-05-19 09:48:30

 

网上有很多关于SSH架构的实例文章,但都显得复杂,我想,入门的朋友,还是希望从最简单的CRUD操作开始,一些复杂的数据库关系,逻辑关系,以后在项目中就能碰到,所以,本文定位于从零开始的一个SSH架构的例子,功能很简单,就是完成一个人员的CRUD操作,麻雀虽小,五脏俱全,希望能对从来没有接触过三者结合开发的朋友带来一点点帮助,这个例子,也算是我的入门实例,从此,开始Struts+Spring+Hibernate之旅

开发工具:MyEclipse5.1+Tomcat+Mysql

开发前准备:数据库安装,tomcat安装,下载jar包这些就不费口水了,直接切入正题吧
CREATE TABLE `people` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) default NULL,
  `location` varchar(100) default NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312 ROW_FORMAT=COMPRESSED;


首先,建立工程和package,以下是我的工程目录
  action
      DeletePeopleAction.java //删除人员action

      EditPeopleAction.java //编辑人员action第一步,读取需要修改的人员资料

      EditPeopleActionDo.java //修改人员action

      ListPeopleAction.javaSave //显示人员列表action

      SavePeopleAction.java //新增人员action

      SearchPeopleAction.java //查找人员action

dao
      IDAO.java //数据库操作接口

      StudentDAOImpl.java //数据库操作实现

domain
      AbstractPeople.java //实体抽象类

      People.hbm.xml //数据库映射

      People.java //实体类

service
      IService.java //服务层接口

      StudentManagerImpl.java //服务层实现

util
     Character.java //字符编码过滤器

     PageSupport.java //分页

applicationContext_hibernate.xml //Spring配置文件(hibernate部分)

applicationContext_service.xml //Spring配置文件(Service部分)


JSP:这几个jsp从名字就能看出功能,不说了
   addStudent.jsp
   editStudent.jsp
   searchList.jsp
   searchStudent.jsp
   studentList.jsp

 

代码:
    

 applicationContext_hibernate.xml
   

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "">

<beans>
<!--
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
       <property name="jndiName">
          <value>java:comp/env/jdbc/StudentManager</value>
       </property>
    </bean>
 -->
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
      <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
      <value>jdbc:mysql://localhost:3306/studentmanager

    </property>
    <property name="username">
      <value>root</value>
    </property>
    <property name="password">
      <value>1234</value>
    </property>
    
 </bean>
 
 <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
   
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.provider_class">
                    org.hibernate.cache.HashtableCacheProvider
                </prop>
            </props>
        </property>
        <!--
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:/domain</value>
            </list>
        </property>-->
        <property name="mappingResources">
           <list>
             <value>domain/People.hbm.xml</value>
           </list>
        </property>
    </bean>
    
    <bean id="StudentDAO" class="dao.StudentDAOImpl">
       <property name="sessionFactory">
         <ref local="sessionFactory"/>
       </property>
    </bean>
</beans>
 

 applicationContext_service.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "">

<beans>

   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory">
       <ref bean="sessionFactory"/>
     </property>
   </bean>
   
   
   <bean id="studentManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
       <property name="transactionManager">
          <ref bean="transactionManager"></ref>
       </property>
      <property name="target">
          <bean class="service.StudentManagerImpl">
            <property name="studentDAO">
                <ref bean="StudentDAO"/>
           </property>
          </bean>
      </property>
      <property name="transactionAttributes">
        <props>
          <prop key="save*">PROPAGATION_REQUIRED</prop>
          <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>
          <prop key="delete*">PROPAGATION_REQUIRED</prop>
          <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
          <prop key="edit*">PROPAGATION_REQUIRED</prop>
          <prop key="search*">PROPAGATION_REQUIRED</prop>
       </props>
     </property>
    <property name="proxyTargetClass">
       <value>true</value>
    </property>
     
   </bean>
   

</beans>
 

 Web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="" xmlns:xsi="" version="2.4" xsi:schemaLocation=" /web-app_2_4.xsd">
  <context-param>
    <param-name>contextConfigLocation</param-name>

    <param-value>
                 /WEB-INF/classes/applicationContext_service.xml,
                 /WEB-INF/classes/applicationContext_hibernate.xml
                                  
    </param-value>
  </context-param>
  
  <resource-ref>
      <description>SqlServer Datasource example</description>
      <res-ref-name>jdbc/StudentManager</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
  
  <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>
            org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
        </filter-class>
        <init-param>
        <param-name>singleSession</param-name>
        <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>

        <listener>
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
     

 
  <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>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>


struts-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "">

<struts-config>
  <data-sources />
  <form-beans>
    <form-bean name="people" type="domain.People"></form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action path="/savePeople" name="people" type="action.SavePeopleAction">
      <forward name="success" path="/listPeople.do"></forward>
    </action>
    
    <action path="/listPeople" name="people" type="action.ListPeopleAction">
      <forward name="success" path="/studentList.jsp"></forward>
    </action>
    
     <action path="/deletePeople" name="people" type="action.DeletePeopleAction">
      <forward name="success" path="/studentList.jsp"></forward>
    </action>
    
     <action path="/editPeople" name="people" type="action.EditPeopleAction">
      <forward name="success" path="/editStudent.jsp"></forward>
    </action>
    
     <action path="/editPeopleDo" name="people" type="action.EditPeopleActionDo">
      <forward name="success" path="/studentList.jsp"></forward>
    </action>
    
     <action path="/searchPeople" name="people" type="action.SearchPeopleAction">
      <forward name="success" path="/searchList.jsp"></forward>
    </action>

  </action-mappings>
  <controller contentType="text/html;charset=gb2312"
        processorClass="util.Character" />
  <message-resources parameter="" />
</struts-config>


 

 DeletePeopleAction.java


/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import service.StudentManagerImpl;
import domain.People;

/** *//**
 * MyEclipse Struts
 * Creation date: 01-17-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */

public class DeletePeopleAction extends ActionSupport ...{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) ...{
       
        
        Integer id=new Integer(request.getParameter("id"));
        StudentManagerImpl manager=(StudentManagerImpl)getWebApplicationContext().getBean("studentManager");
        manager.deletePeople(id);
     
        List studentList=manager.listPeople(0,5,"from People");
   
        request.setAttribute("studentList", studentList);
        request.setAttribute("currentPage", 1);
        return mapping.findForward("success");
    }
}
EditPeopleAction.java
/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import service.StudentManagerImpl;
import domain.People;

/** *//**
 * MyEclipse Struts
 * Creation date: 01-17-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */

public class EditPeopleAction extends ActionSupport ...{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) ...{
       
        String id=request.getParameter("id");
    
        StudentManagerImpl manager=(StudentManagerImpl)getWebApplicationContext().getBean("studentManager");
        People people=(People)manager.getPeople(new Integer(id));
        
        request.setAttribute("id", id);
        request.setAttribute("name", people.getName());
        request.setAttribute("location", people.getLocation());
        
        return mapping.findForward("success");
    }
}
EditPeopleActionDo.java
/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import service.StudentManagerImpl;
import domain.People;

/** *//**
 * MyEclipse Struts
 * Creation date: 01-17-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */

public class EditPeopleActionDo extends ActionSupport ...{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) ...{
       
        People people=(People)form;
        
        StudentManagerImpl manager=(StudentManagerImpl)getWebApplicationContext().getBean("studentManager");
        
        People sPeople=(People)manager.getPeople(new Integer(people.getId()));
        sPeople.setName(people.getName());
        sPeople.setLocation(people.getLocation());
        
        manager.editPeople(sPeople);
        
       
        List studentList=manager.listPeople(0,5,"from People");
        request.setAttribute("studentList", studentList);
        request.setAttribute("currentPage", 1);
        return mapping.findForward("success");
    }
}
ListPeopleAction.java
/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import service.StudentManagerImpl;
import util.PageSupport;

/** *//**
 * MyEclipse Struts
 * Creation date: 01-17-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */

public class ListPeopleAction extends ActionSupport ...{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) ...{
       
        
        String page=request.getParameter("page");

        int firstRow=0;
        int lastRow=0;
        
        StudentManagerImpl manager=(StudentManagerImpl)getWebApplicationContext().getBean("studentManager");
        
        PageSupport sPage=new PageSupport(page);
        sPage.setPagetotal(manager.listPeople().size());
        firstRow=sPage.calcFirstPage();
        lastRow=sPage.calcLastPage();
        
        
        List studentList=manager.listPeople(firstRow-1,lastRow,"from People");
     
        request.setAttribute("studentList", studentList);
        request.setAttribute("currentPage", sPage.getThispage());
        return mapping.findForward("success");
    }
}
SavePeopleAction.java
/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import service.StudentManagerImpl;
import domain.People;

/** *//**
 * MyEclipse Struts
 * Creation date: 01-17-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */

public class SavePeopleAction extends ActionSupport ...{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) ...{
       
        People people=(People)form;
    
        StudentManagerImpl manager=(StudentManagerImpl)getWebApplicationContext().getBean("studentManager");
        manager.savePeople(people);
        
        
        return mapping.findForward("success");
    }
}
SearchPeopleAction.java
/**//*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */

package action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import service.StudentManagerImpl;
import util.PageSupport;
import domain.People;

/** *//**
 * MyEclipse Struts
 * Creation date: 01-17-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */

public class SearchPeopleAction extends ActionSupport ...{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) ...{
       
        People people=(People)form;
        String page=request.getParameter("page");

        int firstRow=0;
        int lastRow=0;
        
        String name=people.getName();
        String location=people.getLocation();
        String hql="from People where name="+name+" and location="+location;
        
        StudentManagerImpl manager=(StudentManagerImpl)getWebApplicationContext().getBean("studentManager");
        
        PageSupport sPage=new PageSupport(page);
        sPage.setPagetotal(manager.searchPeople(hql).size());
        firstRow=sPage.calcFirstPage();
        lastRow=sPage.calcLastPage();
        
        
        
        List studentList=manager.searchPeople(firstRow-1, lastRow, hql);
        
        
        request.setAttribute("studentList", studentList);
        request.setAttribute("currentPage", sPage.getThispage());
        
        return mapping.findForward("success");
    }
}

阅读(1685) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~