SSH 增删改查及分页查询

一、框架结构

二、导入jar 包

Class.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>
	<class name="cn.bdqn.web.po.Parants" table="`parants`">
		<id name="id" type="int">
			<column name="`id`"></column>
			<generator class="native"></generator>
		</id>
		<property name="name" type="string" column="`name`"></property>
		
		<set name="setPerson" table="`par_per`" inverse="true">
			<key column="bid"></key>
			<many-to-many class="cn.bdqn.web.po.Person" column="sid"/>
		</set>
	</class>
</hibernate-mapping>

 编写web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSH2</display-name>
  <welcome-file-list>
   	 	<welcome-file>list.jsp</welcome-file>
  	</welcome-file-list>
 <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- struts -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

三、编写Hibernate配置文件连接数据库 hibernate.cfg.xml

<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/myemps</property>
		<property name="connection.username">root</property>
		<property name="connection.password">970307</property>
		<!-- 辅助参数 -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<property name ="current_session_context_class">thread</property>
		<!-- 映射文件 -->
		<mapping resource="cn/bdqn/web/po/Person.hbm.xml"/>
</session-factory>

</hibernate-configuration>

四、编写Spring配置文件 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/context
	 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 导入外部的properties文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
	<!-- session factory -->
	<bean id="sessionfactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 指定hibernate的配置文件位置 -->
        <property name="configLocation" value="classpath:hibernate1.cfg.xml"></property>
		<!-- 配置c3p0数据库连接池 -->
        <property name="dataSource">
            <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <!-- 数据连接信息 -->
                <property name="jdbcUrl" value="${jdbcUrl}"></property>
                <property name="driverClass" value="${driverClass}"></property>
                <property name="user" value="${user}"></property>
                <property name="password" value="${password}"></property>
                <!-- 其他配置 -->
                <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
                <property name="initialPoolSize" value="3"></property>
                <!--连接池中保留的最小连接数。Default: 3 -->
                <property name="minPoolSize" value="3"></property>
                <!--连接池中保留的最大连接数。Default: 15 -->
                <property name="maxPoolSize" value="5"></property>
                <!-- 连接的最大空闲时间,超时的连接将被丢弃;单位(秒) -->
                <property name="maxIdleTime" value="60"></property>
                <!-- 没有连接可用时,等待连接的时间;单位(毫秒) -->
                <property name="checkoutTimeout" value="2000"></property>
            </bean>
        </property>
	</bean>
	
	<import resource="spring-dao.xml"/>
	<import resource="spring-action.xml"/>
	
	
	<!-- 事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionfactory"></property>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<tx:attributes>
			<tx:method name="get*"/>
			<tx:method name="find*"/>
			<tx:method name="save*"/>
			<tx:method name="delete*"/>
			<tx:method name="update*"/>
			<tx:method name="add*"/>
			<tx:method name="*"/>
		</tx:attributes>
    </tx:advice>
	
	
	
	<aop:config>
		<aop:pointcut expression="execution(public * cn.bdqn.web.biz ..*(..))" id="serviceMethod"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
	</aop:config>
</beans>

--spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="PersonDaoImpl" class="cn.bdqn.web.daoImpl.PersonDaoImpl">
		<property name="sessionFactory" ref="sessionfactory"></property>
	</bean>
	<bean id="PersonBiz" class="cn.bdqn.web.biz.PersonBiz">
		<property name="pdi" ref="PersonDaoImpl"></property>
	</bean>
</beans>

----spring-action.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	 <!--action 注入配置	-->
	<bean id="PersonAction" class="cn.bdqn.web.action.PersonAction">
		<property name="personBiz" ref="PersonBiz"></property>
	</bean>
</beans>

五、dao

public interface iBaseDao<T> {
	//增
	public void save(T intance);
	//改
	public void update(T intance);
	//删
	public void delete(T intance);
	//根据ID查
	public T get(int id);
	//根据hql语句查询
	public List<T> findHQL(String hql, Object... value);
}

---daoImpl

public class iBaseDaoImpl<T> extends HibernateDaoSupport implements iBaseDao<T> {
	//当BaseDaoImpl被继承时,使用该代码可以获得T的类型
	private Class<T> entityClass;
		
	public iBaseDaoImpl(){
		entityClass = (Class<T>)((ParameterizedType)getClass()
				.getGenericSuperclass())
				.getActualTypeArguments()[0];
	}
	//增
	public void save(T intance) {
		getHibernateTemplate().save(intance);
	}
	//改
	public void update(T intance) {
		getHibernateTemplate().update(intance);
	}
	//删
	public void delete(T intance) {
		getHibernateTemplate().delete(intance);
	}
	//根据ID查
	public T get(int id) {
		T t=getHibernateTemplate().get(entityClass, id);
		return t;
	}
	//根据HQL语句查
	public List<T> findHQL(String hql, Object... value) {
		return getHibernateTemplate().find(hql, value);
	}
	//记录数
	public int getCount(String hql,Object...value){
		List<T> list = getHibernateTemplate().find(hql,value);
		return list.size();		
	}
	//分页查询
	public List<T> getPageList(final String hql, final int num,final int size,final Object...value) {
		return getHibernateTemplate().execute(new HibernateCallback() {
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException{
				Query query=session.createQuery(hql);
				if (value != null) {
					for (int i = 0; i < value.length; i++) {
						query.setParameter(i, value[i]);
					}
				}
				if (num > 0 && size > 0) {
					query.setMaxResults(size);
					query.setFirstResult((num-1) * size);
				}
				return (List<T>)query.list();
			}
			
		});
	}
}

Page 类

public class Page {
	private int pageNow;//所在的页数

	private int pageSize;//页面尺寸

	private int pageCount;//总页数

	private int rowCount;//总条数
	
	private List<Standard> list;//数据列表
	
	public Page(){};
	public Page(int pageNow,int rowCount,int pageSize,List<Standard> list){
		this.pageNow=pageNow;
		this.rowCount=rowCount;
		this.pageSize=pageSize;
		this.list=list;
		setRowCount(rowCount);
	}
	public List<Standard> getList() {
		return list;
	}
	public void setList(List<Standard> list) {
		this.list = list;
	}
	public int getPageNow() {
		return pageNow;
	}

	public void setPageNow(int pageNow) {
		this.pageNow = pageNow;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public long getRowCount() {
		return rowCount;
	}

	public void setRowCount(int rowCount) {		
		this.rowCount = rowCount;
		if(rowCount != 0){
			pageCount=(rowCount % pageSize==0)?(rowCount/pageSize):(rowCount/pageSize)+1;
		}else{
			rowCount = 0;
		}
	}	
}

---PersonImpl

public class standardImpl extends iBaseDaoImpl<Standard>{
	public void sSave(Standard standard){
		super.save(standard);
	}
	public void sDelete(Standard standard){
		super.delete(standard);
	}
	public void sUpdate(Standard standard){
		super.update(standard);
	}
	public Standard sGet(int id){
		return get(id);		
	}
	public int sGetCount(String name){
		String hql="from Standard s where s.zhname like ? ";
		String hql1="from Standard";
		if(StringUtils.isNotBlank(name)){
			return getCount(hql,"%"+name+"%");
		}else{
			return getCount(hql1);
		}
		
	} 
	public List<Standard> sFindHql(String name,int num,int size){
		String hql="from Standard s where s.zhname like ?";	
		String hql1="from Standard";
		if(StringUtils.isNotBlank(name)){
			return getPageList(hql,num,size,"%"+name+"%");
		}else{		
			return getPageList(hql1,num,size);
		}
	}
}

  --daoBiz

public interface daoBiz {
	//增
	public void bSave(Standard s);
	//改
	public void bUpdate(Standard s);
	//删
	public void bDelete(Standard s);
	//根据ID查
	public Standard bGet(int id);
	//总记录数
	public int bGetCount(String name);
	//分页查询
	public List<Standard> bFindHql(String name,int num, int size);
}

---personBiz

public class standardBiz implements daoBiz {

	private standardImpl sdi;
	
	public standardImpl getSdi() {
		return sdi;
	}

	public void setSdi(standardImpl sdi) {
		this.sdi = sdi;
	}

	@Override
	public void bSave(Standard s) {
		// TODO Auto-generated method stub
		sdi.sSave(s);
	}

	@Override
	public void bUpdate(Standard s) {
		// TODO Auto-generated method stub
		sdi.sUpdate(s);
	}

	@Override
	public void bDelete(Standard s) {
		// TODO Auto-generated method stub
		sdi.sDelete(s);
	}

	@Override
	public Standard bGet(int id) {
		// TODO Auto-generated method stub
		return sdi.sGet(id);
	}

	@Override
	public int bGetCount(String name) {
		// TODO Auto-generated method stub
		return sdi.sGetCount(name);
	}
	@Override
	public List<Standard> bFindHql(String name,int num, int size) {
		// TODO Auto-generated method stub
		return sdi.sFindHql(name,num,size);
	}

}

--PersonAction

private static final long serialVersionUID = 1L;
	private Standard standard;
	private daoBiz dbz;
	private List<Standard> list;
	private String id;
	private String name;
	private Page page;
	private int pageNow=1;//当前页面
	private int pageSize=3;//页面大小
	public Standard getStandard() {
		return standard;
	}
	public void setStandard(Standard standard) {
		this.standard = standard;
	}
	public daoBiz getDbz() {
		return dbz;
	}
	public void setDbz(daoBiz dbz) {
		this.dbz = dbz;
	}
	public List<Standard> getList() {
		return list;
	}
	public void setList(List<Standard> list) {
		this.list = list;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public int getPageNow() {
		return pageNow;
	}
	public void setPageNow(int pageNow) {
		this.pageNow = pageNow;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	
	public String addView(){
		return "success";
	}
	public String addOper(){
		dbz.bSave(standard);
		return "success";
	}
	
	public String delete(){
		standard=dbz.bGet(Integer.parseInt(id));
		if(standard !=null){
			dbz.bDelete(standard);
		}
		return "success";
	}
	public String updateView(){
		standard=dbz.bGet(Integer.parseInt(id));
		return "success";
	}
	public String updateOper(){
		dbz.bUpdate(standard);
		return "success";
	}
	
	public String view(){
		standard=dbz.bGet(Integer.parseInt(id));
		return "success";
	}
	public String list(){
		list=dbz.bFindHql(name,pageNow,pageSize);
		int count=dbz.bGetCount(name);
		page=new Page(pageNow,count,pageSize,list);
		return "success";
	}
}

六、编写Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<constant name="struts.objectFactory.spring.autoWire" value="type"></constant>
	<package name="test" namespace="/" extends="struts-default">
		<action name="addOper" class="standardAction" method="addOper">
			<result type="chain">list</result>
		</action>
		
		<action name="addView" class="standardAction" method="addView">
			<result>/jsp/add.jsp</result>
		</action>
		
		<action name="delete" class="standardAction" method="delete">
			<result type="chain">list</result>
		</action>
		
		<action name="updateView" class="standardAction" method="updateView">
			<result>/jsp/update.jsp</result>
		</action>
		
		<action name="updateOper" class="standardAction" method="updateOper">
			<result type="chain">list</result>
		</action>
		
		<action name="view" class="standardAction" method="view">
			<result>/jsp/view.jsp</result>
		</action>
		<action name="list" class="standardAction" method="list">
			<result name="success">/jsp/list.jsp</result>
		</action>
	</package>
  
</struts>

七、编写Jsp页面

    ---add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="addOper" method="post">
		请输入添加的名字:<input name="person.name"/>
		<button type="submit" >提交</button>
	</form>
</body>
</html>

    --update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
      <%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<s:form action="updateOper" method="post">
		<s:textfield  label="ID" name="person.id" value="%{person.id}" ></s:textfield>
		<s:textfield  label="NAME" name="person.name" value="%{person.name}" ></s:textfield>
		<s:submit value="修改"></s:submit>
	</s:form>
</body>
</html>

--查看页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<s:property value="list.size()"/><br/>
	<s:iterator	var="itert" value="list">
		ID:<s:property value="#itert.id"/><br/>
		NAME:<s:property value="#itert.name"/><br/>
	</s:iterator><br/>
</body>
</html>

--总页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
        function del(){
            if(confirm("Are you sure?")){
                return true;
            }
            return false;
        }
        function find(){
        	window.location="list?name="+document.getElementById("n").value;
        }
    </script>
<body>

	请输入待查询的名字:<s:textfield id="n" name="Pname"></s:textfield><input type="button" value="查询" onclick="find()"/>
	<table border="1" width="100%" align="center">
		<tr>
			<th width="5%">ID</th>
			<th width="20%">标准号</th>
            <th width="20%">中文名称</th>
            <th width="10%">版本</th>
            <th width="15%">发布日期</th>
            <th width="15%">实施日期</th>>
            <th width="15%">操作</th>
		</tr>
		
		<s:iterator	var="itert" value="page.list">
		<tr>
			<td><s:property value="#itert.id"/></td>
			<td><s:property value="#itert.std_num"/></td>
			<td><s:property value="#itert.zhname"/></td>
			<td><s:property value="#itert.version"/></td>
			<td><s:date name="#itert.releas_date" format="yyyy-MM-dd"/></td>
			<td><s:date name="#itert.impl_date" format="yyyy-MM-dd"/></td>
			<td><s:a href="delete?id=%{#itert.id}" onclick="return del()">删除</s:a>
			<s:a href="updateView?id=%{#itert.id}">修改</s:a>
			<s:a href="view?id=%{#itert.id}">查看</s:a><br/></td>
		</tr>
		</s:iterator>
			<s:a href="addView.action">添加</s:a>
	</table>
	当前是第<s:property value="page.pageNow"/>页,共<s:property value="page.pageCount"/>页
	<s:if test="%{page.pageNow>1}">
		<s:a href="list?pageNow=1">首页</s:a>
		<s:a href="list?pageNow=%{page.pageNow-1}">上一页</s:a>
	</s:if>
	
	<s:if test="%{page.pageNow<page.pageCount}">		
		<s:a href="list?pageNow=%{page.pageNow+1}">下一页</s:a>
		<s:a href="list?pageNow=%{page.pageCount}">末页</s:a>
	</s:if>
	
</body>
</html>

猜你喜欢

转载自my.oschina.net/u/3569028/blog/1036509
今日推荐