1.第一步配置web.xmljavascript
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns=" http://java.sun.com/xml/ns/javaee"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置spring的監聽器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<!-- 開啓監聽 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 配置OpenSessionInViewFilter,必須在struts2監聽以前 -->
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- 配置OpenSessionInViewFilter結束-->
<!-- 配置權限過濾器 -->
<filter>
<filter-name>authFilter</filter-name>
<filter-class>com.litsoft.cctv.twxt.common.auth.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- 配置權限過濾器結束 -->
<!-- 配置struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- sturts2*.jsp配置攔截 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!--struts2 *.action配置攔截 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!--配置struts2結束 -->
<!-- 歡迎頁面 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
css
2.第二步加載spring,struts,hibernate配置文件html
spring配置文件以下java
applicationContext.xmlnode
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置hibernate適配器 -->
<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>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/litsoft/cctv/twxt/common/po/OaUser.hbm.xml</value>
<value>com/litsoft/cctv/twxt/common/po/OaRole.hbm.xml</value>
<value>com/litsoft/cctv/twxt/common/po/OaDept.hbm.xml</value>
</list>
</property>
</bean>
mysql
<!-- 配置聲明式事務 攔截器 -->
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>jquery
<!--aop 管理*.service管理 -->
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="proxyTargetClass" value="true"></property>
<property name="beanNames">
<value>*Service</value>
</property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>web
<!-- 配置baseDao -->
<bean id="baseDao" class="com.litsoft.cctv.twxt.common.dao.impl.BaseDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
spring
<!-- 配置baseService -->
<bean id="baseService" class="com.litsoft.cctv.twxt.common.service.impl.BaseServiceImpl">
<property name="baseDao" ref="baseDao"></property>
</bean>
<bean id="leagueMemberService" class="com.litsoft.cctv.twxt.leaguemembermanage.service.impl.LeagueMemberServerImpl">
<property name="baseDao" ref="baseDao"></property>
</bean>
<!-- 配置用戶管理action -->
<bean name="leaguemembermanage_UserManagerAction" class="com.litsoft.cctv.twxt.leaguemembermanage.ui.action.UserManagerAction" scope="prototype">
<property name="baseService">
<ref bean="baseService"/>
</property>
</bean>
<!-- 配置用戶管理action -->
<bean name="leaguemembermanage_LeagueMemberAction" class="com.litsoft.cctv.twxt.leaguemembermanage.ui.action.LeagueMemberAction" scope="prototype">
<property name="leagueMemberService">
<ref bean="baseService"/>
</property>
</bean>sql
</beans>
數據源
applicationContext-dataSource.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="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/OA_XZXT?useUnicode=true&continueBatchOnError=true&characterEncoding=utf-8</value>
</property>
<property name="removeAbandoned">
<value>true</value>
</property>
<property name="defaultAutoCommit">
<value>true</value>
</property>
<property name="removeAbandonedTimeout">
<value>60</value>
</property>
<property name="validationQuery">
<value>SELECT 1</value>
</property>
<property name="logAbandoned">
<value>true</value>
</property>
<property name="testWhileIdle">
<value>true</value>
</property>
<property name="timeBetweenEvictionRunsMillis">
<value>10000</value>
</property>
<property name="minEvictableIdleTimeMillis">
<value>6000</value>
</property>
<property name="testOnBorrow">
<value>true</value>
</property>
<property name="maxActive">
<value>150</value>
</property>
<property name="maxIdle">
<value>30</value>
</property>
<property name="minIdle">
<value>10</value>
</property>
<property name="initialSize">
<value>10</value>
</property>
</bean>
</beans>
spring配置文件結束
struts2配置文件
採用通配符形式
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<include file="struts-cctvbase.xml"/>
<!-- Add packages here -->
<package name="actions" namespace="/" extends="cctv-base">
<action name="*_*_*" class="com.litsoft.cctv.twxt.{1}.ui.action.{2}" method="{3}">
<result name="input">${input_url}</result>
<result name="forward_url">${forward_url}</result>
<result name="redirect_url" type="redirect">${redirect_url}</result>
</action>
</package>
</struts>
struts-cctvbase.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Add packages here -->
<package name="cctv-base" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="catchException"
class="com.litsoft.cctv.twxt.common.struts.ErrorCatchInterceptor">
</interceptor>
<interceptor-stack name="cctvInterStack">
<interceptor-ref name="catchException"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="cctvInterStack"></default-interceptor-ref>
<global-results>
<result name="ERROR">/common/page/error/errorpage.jsp</result>
</global-results>
</package>
</struts>
struts文件結束
第三步 java操做類
package com.litsoft.cctv.twxt.common.dao;
import java.io.Serializable;
import java.util.List;
import com.litsoft.cctv.twxt.common.po.OaDept;
/**
* 基本操做接口
* @author silin.wang
*
*/
public interface BaseDao {
/**
* 批量插入數據
*
* @param l
* 要插入的數據列表
*
*/
public void batchSave(List l) throws Exception;
/**
* 保存實例的方法
*
* @param obj
* 須要保存的實例
* @throws Exception
* hibernate異常
*/
public void save(Object obj) throws Exception;
/**
* 保存實例並返回id
*
* @param obj
* 須要保存的實例
* @throws Exception
* hibernate異常
*/
public Serializable saveAndReturnId(Object obj) throws Exception;
/**
* 批量更新數據
*
* @param l
* 要更新的數據列表
*
*/
public void batchUpdate(List l) throws Exception;
/**
* 更新實例
*
* @param obj
* 須要更新的實例
*/
public void update(Object obj) throws Exception;
/**
* 插入或更新記錄
*
* @param obj
* po對象
*/
public void saveOrUpdate(Object obj) throws Exception;
/**
* 刪除實例
*
* @param obj
* 須要刪除的實例
*/
public void delete(Object obj) throws Exception;
/**
* 根據ID刪除實例
*
* @param c
* 實例的class
* @param id
* 實例id
*/
public void deleteById(Class clazz, Long id) throws Exception;
/**
* 刪除指定列在指定範圍值內的全部記錄
*
* @param clazz
* 實體對象
* @param pkName
* 主鍵列名
* @param idarray
* 主鍵數組,注意數組長度不能大於5000,不然會報異常
*/
public void deleteByIds(Class clazz, String pkName, Long[] idarray)
throws Exception;
/**
* 根據ID獲得一個實例
*
* @param c
* 實例的class
* @param id
* 實例的id
* @return
*/
public Object getById(Class clazz, Serializable id) throws Exception;
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 可直接執行的HQL語句
* @return
*/
public List queryByHql(String hql) throws Exception;
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 可直接執行的HQL語句
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List queryByHql(String hql, int first, int max)throws Exception;
/**
* 單一對象組合條件查詢結果列表
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @param orders
* 排序條件列表(如:column_name desc;column_name asc)
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List querySingleObject(Class clazz, List<String> property,
List params, List<String> orders, int first, int max)throws Exception;
/**
* 根據輸入hql語句返回查詢結果總數
*
* @param hql
* @return
*/
public int queryByHqlCount(String hql)throws Exception;
/**
* 單一對象組合條件查詢結果總數
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @return
*/
public int querySingleObjectCount(Class clazz, List<String> property,
List params)throws Exception;
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 帶參數的HQL語句,參數數量應與params長度一致
* @param params
* 參數值列表
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List queryByHql(String hql, List params, int first, int max)throws Exception;
/**
* 根據輸入HQL語句返回查詢結果總數
*
* @param hql
* 帶參數的HQL語句,參數數量應與params長度一致
* @param params
* 參數值列表
* @return
*/
public int queryByHqlCount(String hql, List params)throws Exception;
/**
* 根據輸入條件得到單一對象查詢HQL語句
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @param orders
* 排序條件列表(如:column_name desc;column_name asc)
* @return
*/
public String getHql(Class clazz, List<String> property, List<String> orders)throws Exception;
/**
* 查詢某屬性爲指定值的記錄是否存在, 存在返回true 不存在返回false
*
* @param Str
* @return java.lang.Boolean
*/
public boolean existType(Class clazz, String type, String key)throws Exception;
/**
* 獲取指定表的sequence值
*
* @param sequenceName
* sequence名稱
*
* @return sequence id
*/
public Long getSID(String sequenceName)throws Exception;
public List<OaDept> queryOaDept(OaDept dept);
}
DAO實現
package com.litsoft.cctv.twxt.common.dao.impl;
import java.io.Serializable;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.litsoft.cctv.twxt.common.dao.BaseDao;
import com.litsoft.cctv.twxt.common.po.OaDept;
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
static Logger logger=Logger.getLogger(BaseDaoImpl.class);
/**
* 批量插入數據
*
* @param l
* 要插入的數據列表
*
*/
public void batchSave(List l) throws Exception {
try {
for (int i = 0; i < l.size(); i++) {
this.getHibernateTemplate().save(l.get(i));
if ((i + 1) % 20 == 0) {
this.getHibernateTemplate().flush();
}
}
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 保存實例的方法
*
* @param obj
* 須要保存的實例
* @throws Exception
* hibernate異常
*/
public void save(Object obj) throws Exception {
try {
logger.debug("before save=>" + obj);
this.getHibernateTemplate().save(obj);
logger.debug("after save=>" + obj);
//this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 保存實例並返回id
*
* @param obj
* 須要保存的實例
* @throws Exception
* hibernate異常
*/
public Serializable saveAndReturnId(Object obj) throws Exception {
Serializable id = null;
try {
id = this.getHibernateTemplate().save(obj);
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
return id;
}
/**
* 批量更新數據
*
* @param l
* 要更新的數據列表
*
*/
public void batchUpdate(List l) throws Exception {
try {
for (int i = 0; i < l.size(); i++) {
this.getHibernateTemplate().update(l.get(i));
if ((i + 1) % 20 == 0) {
this.getHibernateTemplate().flush();
}
}
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 更新實例
*
* @param obj
* 須要更新的實例
*/
public void update(Object obj) throws Exception {
try {
this.getHibernateTemplate().update(obj);
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 插入或更新記錄
*
* @param obj
* po對象
*/
public void saveOrUpdate(Object obj) throws Exception {
try {
this.getHibernateTemplate().saveOrUpdate(obj);
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 刪除實例
*
* @param obj
* 須要刪除的實例
*/
public void delete(Object obj) throws Exception {
try {
this.getHibernateTemplate().delete(obj);
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 根據ID刪除實例
*
* @param c
* 實例的class
* @param id
* 實例id
*/
public void deleteById(Class clazz, Long id) throws Exception {
try {
Object obj = this.getHibernateTemplate().load(clazz, id);
this.getHibernateTemplate().delete(obj);
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 刪除指定列在指定範圍值內的全部記錄
*
* @param clazz
* 實體對象
* @param pkName
* 主鍵列名
* @param idarray
* 主鍵數組,注意數組長度不能大於5000,不然會報異常
*/
public void deleteByIds(Class clazz, String pkName, Long[] idarray)
throws Exception {
String hql = "delete from " + clazz.getSimpleName() + " where "
+ pkName + " in (:idarray)";
try {
Query q = this.getSession().createQuery(hql);
q.setParameterList("idarray", idarray);
q.executeUpdate();
this.getHibernateTemplate().flush();
} catch (Exception e) {
throw e;
}
}
/**
* 根據ID獲得一個實例
*
* @param c
* 實例的class
* @param id
* 實例的id
* @return
*/
public Object getById(Class clazz, Serializable id) {
Object obj = null;
obj = this.getHibernateTemplate().get(clazz, id);
return obj;
}
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 可直接執行的HQL語句
* @return
*/
public List queryByHql(String hql) {
return this.queryByHql(hql, null, -1, -1);
}
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 可直接執行的HQL語句
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List queryByHql(String hql, int first, int max) {
return this.queryByHql(hql, null, first, max);
}
/**
* 單一對象組合條件查詢結果列表
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @param orders
* 排序條件列表(如:column_name desc;column_name asc)
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List querySingleObject(Class clazz, List<String> property,
List params, List<String> orders, int first, int max) {
return queryByHql(getHql(clazz, property, orders), params, first, max);
}
/**
* 根據輸入hql語句返回查詢結果總數
*
* @param hql
* @return
*/
public int queryByHqlCount(String hql) {
return this.queryByHqlCount(hql, null);
}
/**
* 單一對象組合條件查詢結果總數
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @return
*/
public int querySingleObjectCount(Class clazz, List<String> property,
List params) {
return this.queryByHqlCount(this.getHql(clazz, property, null), params);
}
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 帶參數的HQL語句,參數數量應與params長度一致
* @param params
* 參數值列表
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List queryByHql(String hql, List params, int first, int max) {
// 生成query
logger.debug(hql);
Object obj = null;
Query query = this.getSession().createQuery(hql);
// 循環params
if (params != null) {
int n = params.size();
for (int i = 0; i < n; i++) {
obj = params.get(i);
// 注意,query.setParameter是1序的
logger.debug("params " + i + ":" + obj);
// this.getHql().append(
// " and upper(" + this.getOtherName() + "." + fieldName
// + ") like ? escape '/'");
//
// this.getParams().add(
// "%"
// + CommonTools.getLikeSelect(
// fieldValue.toString()).toUpperCase()
// + "%");
// if (obj instanceof String) {
// obj = StringTool.getLikeSelect((String) obj).toUpperCase();
// System.out.println(obj);
// }
query.setParameter(i, obj);
}
}
// 設置頁
if (-1 != max) {
query.setFirstResult(first);
query.setMaxResults(max);
}
// 獲得結果
List list = query.list();
return list;
}
/**
* 根據輸入HQL語句返回查詢結果總數
*
* @param hql
* 帶參數的HQL語句,參數數量應與params長度一致
* @param params
* 參數值列表
* @return
*/
public int queryByHqlCount(String hql, List params) {
Object obj = null;
String countHql = "select count(*) " + hql;
// 生成query
logger.debug(countHql);
Query query = this.getSession().createQuery(countHql);
// 循環params
if (params != null) {
int n = params.size();
for (int i = 0; i < n; i++) {
obj = params.get(i);
// 注意,query.setParameter是1序的
logger.debug("params " + i + ":" + obj);
// if (obj instanceof String) {
// obj = StringTool.getLikeSelect((String) obj).toUpperCase();
// }
query.setParameter(i, obj);
}
}
// 獲得結果
//System.out.println(query.list().get(0));
return ((Long) query.uniqueResult()).intValue();
}
/**
* 根據輸入條件得到單一對象查詢HQL語句
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @param orders
* 排序條件列表(如:column_name desc;column_name asc)
* @return
*/
public String getHql(Class clazz, List<String> property, List<String> orders) {
String c = clazz.getSimpleName();
// 條件buffer
StringBuffer str = new StringBuffer();
String propertyValue = null;
if (property != null) {
// 首先循環property
int n = property.size();
for (int i = 0; i < n; i++) {
propertyValue = property.get(i);
if (propertyValue.contains("like")) {
str.append(" and upper(");
str.append(c);
str.append(".");
// .replaceFirst("=", ")=")
str.append(propertyValue.replaceFirst(" like", ") like"));
} else {
str.append(" and ");
str.append(c);
str.append(".");
// .replaceFirst("=", ")=")
str.append(propertyValue);
}
}
}
if (orders != null) {
int n = orders.size();
for (int i = 0; i < n; i++) {
if (i == 0)
str.append(" order by ");
else
str.append(",");
str.append(c);
str.append(".");
str.append(orders.get(i));
}
}
// 後面一個c做爲別名
str.insert(0, " from " + c + " " + c + " where 1=1 ");
return str.toString();
}
/**
* 查詢某屬性爲指定值的記錄是否存在, 存在返回true 不存在返回false
*
* @param Str
* @return java.lang.Boolean
*/
public boolean existType(Class clazz, String type, String key) {
String strSql = " from " + clazz.getSimpleName() + " as a where a."
+ type + " = :type";
Query q = this.getSession().createQuery(strSql);
q.setString("type", key);
List list = q.list();
if (list.size() > 0) {
return true;
} else {
return false;
}
}
/**
* 獲取指定表的sequence值
*
* @param sequenceName
* sequence名稱
*
* @return sequence id
*/
public Long getSID(String sequenceName) {
Query query = this.getSession().createSQLQuery("select " + sequenceName
+ ".nextval FROM dual");
return Long.valueOf(query.uniqueResult().toString());
}
@Override
public List<OaDept> queryOaDept(OaDept dept) {
String hql="from OaDept dept where dept.parentid="+dept.getParentid();
List list=this.getHibernateTemplate().find(hql);
return list;
}
}
業務模型接口
package com.litsoft.cctv.twxt.common.service;
import java.io.Serializable;
import java.util.List;
import com.litsoft.cctv.twxt.common.po.OaDept;
/**
* 基本業務接口
* @author silin.wang
*
*/
public interface BaseService {
/**
* 批量插入數據
*
* @param l
* 要插入的數據列表
*
*/
public void batchSave(List l) throws Exception;
/**
* 保存實例的方法
*
* @param obj
* 須要保存的實例
* @throws Exception
* hibernate異常
*/
public void save(Object obj) throws Exception;
/**
* 保存實例並返回id
*
* @param obj
* 須要保存的實例
* @throws Exception
* hibernate異常
*/
public Serializable saveAndReturnId(Object obj) throws Exception;
/**
* 批量更新數據
*
* @param l
* 要更新的數據列表
*
*/
public void batchUpdate(List l) throws Exception;
/**
* 更新實例
*
* @param obj
* 須要更新的實例
*/
public void update(Object obj) throws Exception;
/**
* 插入或更新記錄
*
* @param obj
* po對象
*/
public void saveOrUpdate(Object obj) throws Exception;
/**
* 刪除實例
*
* @param obj
* 須要刪除的實例
*/
public void delete(Object obj) throws Exception;
/**
* 根據ID刪除實例
*
* @param c
* 實例的class
* @param id
* 實例id
*/
public void deleteById(Class clazz, Long id) throws Exception;
/**
* 刪除指定列在指定範圍值內的全部記錄
*
* @param clazz
* 實體對象
* @param pkName
* 主鍵列名
* @param idarray
* 主鍵數組,注意數組長度不能大於5000,不然會報異常
*/
public void deleteByIds(Class clazz, String pkName, Long[] idarray)
throws Exception;
/**
* 根據ID獲得一個實例
*
* @param c
* 實例的class
* @param id
* 實例的id
* @return
*/
public Object getById(Class clazz, Serializable id) throws Exception;
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 可直接執行的HQL語句
* @return
*/
public List queryByHql(String hql) throws Exception;
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 可直接執行的HQL語句
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List queryByHql(String hql, int first, int max)throws Exception;
/**
* 單一對象組合條件查詢結果列表
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @param orders
* 排序條件列表(如:column_name desc;column_name asc)
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List querySingleObject(Class clazz, List<String> property,
List params, List<String> orders, int first, int max)throws Exception;
/**
* 根據輸入hql語句返回查詢結果總數
*
* @param hql
* @return
*/
public int queryByHqlCount(String hql)throws Exception;
/**
* 單一對象組合條件查詢結果總數
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @return
*/
public int querySingleObjectCount(Class clazz, List<String> property,
List params)throws Exception;
/**
* 根據輸入hql語句返回查詢結果
*
* @param hql
* 帶參數的HQL語句,參數數量應與params長度一致
* @param params
* 參數值列表
* @param first
* 起始行
* @param max
* 總行數
* @return
*/
public List queryByHql(String hql, List params, int first, int max)throws Exception;
/**
* 根據輸入HQL語句返回查詢結果總數
*
* @param hql
* 帶參數的HQL語句,參數數量應與params長度一致
* @param params
* 參數值列表
* @return
*/
public int queryByHqlCount(String hql, List params)throws Exception;
/**
* 根據輸入條件得到單一對象查詢HQL語句
*
* @param clazz
* 對象類型
* @param property
* 條件列表(如:column_name=?;column_name like ?)
* @param params
* 條件值列表
* @param orders
* 排序條件列表(如:column_name desc;column_name asc)
* @return
*/
public String getHql(Class clazz, List<String> property, List<String> orders)throws Exception;
/**
* 查詢某屬性爲指定值的記錄是否存在, 存在返回true 不存在返回false
*
* @param Str
* @return java.lang.Boolean
*/
public boolean existType(Class clazz, String type, String key)throws Exception;
/**
* 獲取指定表的sequence值
*
* @param sequenceName
* sequence名稱
*
* @return sequence id
*/
public Long getSID(String sequenceName)throws Exception;
public List<OaDept> queryOaDept(OaDept dept);
}
業務實現
package com.litsoft.cctv.twxt.common.service.impl;
import java.io.Serializable;
import java.util.List;
import com.litsoft.cctv.twxt.common.dao.BaseDao;
import com.litsoft.cctv.twxt.common.po.OaDept;
import com.litsoft.cctv.twxt.common.service.BaseService;
/**
* 基本業務實現
* @author silin.wang
*
*/
public class BaseServiceImpl implements BaseService {
private BaseDao baseDao;
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
public void batchSave(List l) throws Exception {
baseDao.batchSave(l);
}
public void batchUpdate(List l) throws Exception {
baseDao.batchUpdate(l);
}
public void delete(Object obj) throws Exception {
baseDao.delete(obj);
}
public void deleteById(Class clazz, Long id) throws Exception {
baseDao.deleteById(clazz, id);
}
public void deleteByIds(Class clazz, String pkName, Long[] idarray)
throws Exception {
baseDao.deleteByIds(clazz, pkName, idarray);
}
public boolean existType(Class clazz, String type, String key)
throws Exception {
return baseDao.existType(clazz, type, key);
}
public Object getById(Class clazz, Serializable id) throws Exception {
return baseDao.getById(clazz, id);
}
public String getHql(Class clazz, List<String> property, List<String> orders)
throws Exception {
return baseDao.getHql(clazz, property, orders);
}
public Long getSID(String sequenceName) throws Exception {
return baseDao.getSID(sequenceName);
}
public List queryByHql(String hql, int first, int max) throws Exception {
return baseDao.queryByHql(hql, first, max);
}
public List queryByHql(String hql, List params, int first, int max)
throws Exception {
return baseDao.queryByHql(hql, first, max);
}
public List queryByHql(String hql) throws Exception {
return baseDao.queryByHql(hql);
}
public int queryByHqlCount(String hql, List params) throws Exception {
return baseDao.queryByHqlCount(hql, params);
}
public int queryByHqlCount(String hql) throws Exception {
return baseDao.queryByHqlCount(hql);
}
public List querySingleObject(Class clazz, List<String> property,
List params, List<String> orders, int first, int max)
throws Exception {
return baseDao.querySingleObject(clazz, property, params, orders, first, max);
}
public int querySingleObjectCount(Class clazz, List<String> property,
List params) throws Exception {
return baseDao.querySingleObjectCount(clazz, property, params);
}
public void save(Object obj) throws Exception {
baseDao.save(obj);
}
public Serializable saveAndReturnId(Object obj) throws Exception {
return baseDao.saveAndReturnId(obj);
}
public void saveOrUpdate(Object obj) throws Exception {
baseDao.saveOrUpdate(obj);
}
public void update(Object obj) throws Exception {
baseDao.update(obj);
}
@Override
public List<OaDept> queryOaDept(OaDept dept) {
// TODO Auto-generated method stub
return baseDao.queryOaDept(dept);
}
}
繼承重構ActionSupport
package com.litsoft.cctv.twxt.common.struts;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -1470484361342972167L;
protected Log logger = LogFactory.getLog(this.getClass());
protected HttpServletRequest request = ServletActionContext.getRequest();
protected HttpServletResponse response = ServletActionContext.getResponse();
protected HttpSession session = request.getSession();
protected ServletContext application = ServletActionContext
.getServletContext();
protected String input_url = null;
protected String forward_url = null;
protected String redirect_url = null;
private String messageCode;
protected String forward(String url){
this.forward_url = url;
return "forward_url";
}
protected String redirect(String url){
this.redirect_url = url;
return "redirect_url";
}
protected String urlname = null;
protected String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
protected PageInfo page = new PageInfo();
public void showMsg(String succMsg) {
logger.debug("set succMsg in session:" + succMsg + "*");
session.setAttribute("succMsg", succMsg);
}
public PageInfo getPage() {
return page;
}
public void setPage(PageInfo page) {
this.page = page;
}
public String getUrlname() {
return urlname;
}
public void setUrlname(String urlname) {
this.urlname = urlname;
}
public String getInput_url() {
return input_url;
}
public void setInput_url(String input_url) {
this.input_url = input_url;
}
public String getForward_url() {
return forward_url;
}
public void setForward_url(String forward_url) {
this.forward_url = forward_url;
}
public String getRedirect_url() {
return redirect_url;
}
public void setRedirect_url(String redirect_url) {
this.redirect_url = redirect_url;
}
public String getMessageCode() {
return messageCode;
}
public void setMessageCode(String messageCode) {
this.messageCode = messageCode;
}
}
package com.litsoft.cctv.twxt.common.po;
import java.io.Serializable;
import com.litsoft.cctv.twxt.common.util.ObjectToString;
//import org.apache.commons.lang.builder.ToStringBuilder;
public class BaseModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8638327111782386253L;
public String toString() {
// return ToStringBuilder.reflectionToString(this);
// 避免ToStringBuilder引發List對象的嵌套循環調用致使堆棧溢出
return ObjectToString.toStringBuilder(this);
}
}
分頁工具類
package com.litsoft.cctv.twxt.common.struts;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.litsoft.cctv.twxt.common.po.BaseModel;
import com.litsoft.cctv.twxt.common.util.MathTool;
public class PageInfo extends BaseModel {
/**
*
*/
private static final long serialVersionUID = 1314064453549547233L;
protected Log logger = LogFactory.getLog(this.getClass());
private int totalCount = 0; // 總記錄數
private int totalPage = 0;// 總頁數
private int pageIndex = 0;// 當前應顯示頁,默認爲第0頁,以便當初次請求時,返回第一行到maxResult行的數據
private int maxResult = 10;// 每頁顯示數
private int clearPage = 1;// 爲0表示經過分頁控件提交,不清空翻頁記錄,爲1表示新提交請求,相關分頁信息初始化
private int startIndex = 0;// 默認開始記錄數
/**
* 當設置總記錄數時,將自動計算共有多少頁及當前爲第幾頁
*
* @param recordcount
* 記錄總數
*/
public void setTotalCount(int totalCount) {
this.setTotalCount(totalCount, this.maxResult);
}
/**
* 當設置總記錄數時,將自動計算共有多少頁及當前爲第幾頁
*
* @param recordcount
* 記錄總數
* @param recordperpage
* 每頁顯示記錄數
*/
public void setTotalCount(int totalCount, int maxResult) {
// 當設定每頁顯示數時,修改默認的每頁顯示行數(默認爲10)
if (maxResult > 0) {
this.setMaxResult(maxResult);
}
this.totalCount = totalCount;
}
/**
* 獲得分頁的開始記錄位置
*
* @return
*/
public int getStartIndex() {
if (this.totalCount < 0) {
// 當前頁爲0,沒有查詢到記錄
this.startIndex = 0;
return this.startIndex;
}
// 上取整得到總頁數
this.totalPage = MathTool.getDivInt(this.totalCount, this.maxResult);
if (this.clearPage == 1) {// 新的請求,重置起始頁
if (this.totalPage == 0) {
this.pageIndex = 0;
} else {
this.pageIndex = 1;
}
} else {// 翻頁請求,保留當前頁信息
if (this.pageIndex > this.totalPage)
// 當前頁大於totalpage,說明記錄可能已經被刪除,致使總頁數減小,將currpage設置爲當前最大頁
this.pageIndex = this.totalPage;
}
if (this.pageIndex > 0)
this.startIndex = new Integer((this.pageIndex - 1) * this.maxResult)
.intValue();
else
this.startIndex = 0;
return this.startIndex;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getMaxResult() {
return maxResult;
}
public void setMaxResult(int maxResult) {
this.maxResult = maxResult;
}
public int getTotalCount() {
return totalCount;
}
public int getTotalPage() {
return totalPage;
}
public int getClearPage() {
return clearPage;
}
public void setClearPage(int clearPage) {
this.clearPage = clearPage;
}
}
業務控制層模型
package com.litsoft.cctv.twxt.leaguemembermanage.ui.action;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import com.litsoft.cctv.twxt.common.po.OaDept;
import com.litsoft.cctv.twxt.common.service.BaseService;
import com.litsoft.cctv.twxt.common.struts.BaseAction;
import com.litsoft.cctv.twxt.leaguemembermanage.ui.form.UserForm;
public class UserManagerAction extends BaseAction implements Runnable {
private UserForm uForm;
private BaseService baseService;
private Long id;
private static final long serialVersionUID = 1L;
public void setBaseService(BaseService baseService) {
this.baseService = baseService;
}
public UserForm getuForm() {
return uForm;
}
public void setuForm(UserForm uForm) {
this.uForm = uForm;
}
public BaseService getBaseService() {
return baseService;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@SuppressWarnings("unchecked")
public String list()throws Exception{
LinkedList property = new LinkedList();
LinkedList params = new LinkedList();
property.add(uForm);
logger.info(property.size());
page.setTotalCount(baseService.queryByHqlCount("from OaUser"));
LinkedList<String> orders = new LinkedList<String>();
List userList=baseService.queryByHql("from OaUser", page.getStartIndex(), page.getMaxResult());
request.setAttribute("userList", userList);
return "success";
}
@SuppressWarnings("unchecked")
public String query()throws Exception{
List<OaDept> result=new ArrayList<OaDept>();
List<OaDept> deptList=listOaDept(Long.valueOf("0"),result);
String jsonString=this.formatJson(deptList);
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.flush();
out.println(jsonString);
out.close();
return null;
}
@SuppressWarnings("unchecked")
public String query1()throws Exception{
List<OaDept> result=new ArrayList<OaDept>();
List<OaDept> deptList=listOaDept(Long.valueOf("0"),result);
String jsonString=this.formatJson1(deptList);
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.flush();
out.println(jsonString);
out.close();
return null;
}
/**
* 用戶列表信息
* @param id
* @param deptList
* @return
* @throws Exception
*/
public List listOaDept(Long id,List<OaDept> deptList)throws Exception{
OaDept dept=new OaDept();
dept.setParentid(id);
List<OaDept> oaDeptList=baseService.queryOaDept(dept);
for(OaDept result:oaDeptList){
System.out.print(result.getDeptname());
deptList.add(result);
listOaDept(result.getId(),deptList);
}
return deptList;
}
/**
* 轉換爲json對象
* @param deptList
* @return
* @throws Exception
*/
private String formatJson(List<OaDept> deptList)throws Exception{
JSONArray tree = new JSONArray();
for(OaDept dept:deptList){
JSONObject node = new JSONObject();
node.put("id", dept.getId());
node.put("pId", dept.getParentid());
node.put("name",dept.getDeptname());
tree.put(node);
}
return tree.toString();
}
/**
* 轉換爲json對象
* @param deptList
* @return
* @throws Exception
*/
private String formatJson1(List<OaDept> deptList)throws Exception{
JSONArray tree = new JSONArray();
for(OaDept dept:deptList){
JSONObject node = new JSONObject();
node.put("id", dept.getId());
node.put("pid", dept.getParentid());
node.put("name",dept.getDeptname());
tree.put(node);
}
return tree.toString();
}
@Override
public void run() {
}
}
實體bean
package com.litsoft.cctv.twxt.common.po;
/**
* 部門 模型
* @author silin.wang
*
*/
public class OaDept implements java.io.Serializable {
// Fields
private Long id; //主鍵
private String deptname;//部門名稱
private String deptcode; //部門code
private String treepath; //節點path
private Short syscode; //部門級別
private Long parentid; //上級節點
private Short delflag; //刪除標識
// Constructors
/** default constructor */
public OaDept() {
}
/** full constructor */
public OaDept(String deptname, String deptcode, String treepath,
Short syscode, Long parentid, Short delflag) {
this.deptname = deptname;
this.deptcode = deptcode;
this.treepath = treepath;
this.syscode = syscode;
this.parentid = parentid;
this.delflag = delflag;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getDeptname() {
return this.deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDeptcode() {
return this.deptcode;
}
public void setDeptcode(String deptcode) {
this.deptcode = deptcode;
}
public String getTreepath() {
return this.treepath;
}
public void setTreepath(String treepath) {
this.treepath = treepath;
}
public Short getSyscode() {
return this.syscode;
}
public void setSyscode(Short syscode) {
this.syscode = syscode;
}
public Long getParentid() {
return this.parentid;
}
public void setParentid(Long parentid) {
this.parentid = parentid;
}
public Short getDelflag() {
return this.delflag;
}
public void setDelflag(Short delflag) {
this.delflag = delflag;
}
}
ztree.jsp實現ztree.js樹形菜單
<%@ page contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="c" uri="/common/tld/c.tld"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>樹形菜單</title>
<meta content="text/html; charset=UTF-8" http-equiv=Content-Type>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="部門">
<meta http-equiv="description" content="部門管理">
<link rel="stylesheet" type="text/css" href="<%=path%>/common/js/jquery/jqueryZtree3.1/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="<%=path%>/common/js/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="<%=path%>/common/js/jquery/jqueryZtree3.1/js/jquery.ztree.core-3.1.min.js"></script>
<script type="text/javascript" src="<%=path%>/common/js/jquery/jqueryZtree3.1/js/jquery.ztree.excheck-3.1.min.js"></script>
<script type="text/javascript">
var setting = {
data: {
key: {
title: "t"
},
simpleData: {
enable: true
}
},
callback: {
onClick: zTreeOnClick
}
};
var zNodes;
$(document).ready(function(){
refreshTree();
});
function refreshTree() {
$.getJSON('<%=path%>/leaguemembermanage_UserManagerAction_query.action',function(data){
$.each(data,function(entryIndex,entry){ //循壞開始
zNodes=data;
});
// $("#treeDiv").html(tree.toString());
$.fn.zTree.init($("#treeDiv"), setting, zNodes);
});
}
function zTreeOnClick(){
}
</script>
</head>
<body>
<div class="dtree">
<div id="treeDiv">
</div>
</div>
</body>
</html>
dtree實現
<%@ page contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="c" uri="/common/tld/c.tld"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>樹形菜單</title>
<meta content="text/html; charset=UTF-8" http-equiv=Content-Type>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="部門">
<meta http-equiv="description" content="部門管理">
<link href="common/css/style.css" rel="stylesheet" type="text/css">
<link href="./common/js/dtree/dtree.css" rel="StyleSheet" type="text/css" />
<link href="./common/css/litsoft_global_style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="./common/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="./common/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="./common/js/dtree/dtree.js"></script>
<script type="text/javascript" src="./common/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var tree;
$(document).ready(function(){
refreshTree();
});
function refreshTree() {
$.getJSON('<%=path%>/leaguemembermanage_UserManagerAction_query1.action',function(data){
tree = new dTree('tree');
tree.add(0,-1,'團務系統');
$.each(data,function(entryIndex,entry){ //循壞開始
tree.add(entry['id'], entry['pid'], entry['name']);
});
$("#treeDiv").html(tree.toString());
});
}
</script>
</head>
<body>
<div class="dtree">
<p><a href="javascript: tree.openAll();">open all</a> | <a href="javascript: tree.closeAll();">close all</a></p>
<div id="treeDiv">
</div>
</div>
</body>
</html>
若有需完整,請留言,或者發送郵箱454096624@qq.com。初次發表,新手,請勿噴!