`
sungang_1120
  • 浏览: 310949 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
收藏列表
标题 标签 来源
ListUtils java
package cn.cd.sg.collection.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.Factory;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.list.FixedSizeList;
import org.apache.commons.collections.list.LazyList;
import org.apache.commons.collections.list.PredicatedList;
import org.apache.commons.collections.list.SynchronizedList;
import org.apache.commons.collections.list.TransformedList;
import org.apache.commons.collections.list.TypedList;
import org.apache.commons.collections.list.UnmodifiableList;

/**
* 描述:lIST  集合工具类
* 项目名称:utils   
* 类名称:ListUtils   
* 创建人:孙刚   
* 创建时间:2014-1-22 上午09:26:48   
* 修改人1:xxx     
* 修改时间1:xxxx-xx-xx 
* 修改备注:   
* @version  1.0
 */
public class ListUtils {
	
	@SuppressWarnings("unchecked")
	public static final List EMPTY_LIST;
	
	
	static{
		EMPTY_LIST = Collections.EMPTY_LIST;
	}
	
	public ListUtils() {}
	
	
	/**
	* 描述  : (求两个  List交集)
	* 方法名: intersection
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:29:25
	* @param list1
	* @param list2
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List intersection(List list1, List list2){
		
		ArrayList result = new ArrayList();
		Iterator iterator = list2.iterator();
		do {
			if(!iterator.hasNext()){
				 break;
			}
			Object o = iterator.next();
			
			if(list1.contains(o)){
				result.add(o);
			}
		} while (true);
		
		return result;
	}
	
	/**
	* 描述  : (删除  list1中 包含  list2中的元素)
	* 方法名: subtract
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:30:01
	* @param list1
	* @param list2
	* @return  
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List subtract(List list1, List list2){
		
		ArrayList result = new ArrayList(list1);
		for(Iterator iterator = list2.iterator(); 
		iterator.hasNext(); 
		result.remove(iterator.next()));
		
		return result;
	}
	/**
	* 描述  : (获取两个list中的交集)
	* 方法名: sum
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:43:55
	* @param list1
	* @param list2
	* @return  
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List sum(List list1, List list2){
		return subtract(union(list1, list2), intersection(list1, list2));
	}
	/**
	* 描述  : (获取两个list中的并集)
	* 方法名: union
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:31:42
	* @param list1
	* @param list2
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List union(List list1, List list2){
		ArrayList result = new ArrayList(list1);
		result.addAll(list2);
		return result;
	}
	/**
	* 描述  : (比较两个 集合是否相等  含顺序  一样)
	* 方法名: isEqualList
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:33:01
	* @param list1
	* @param list2
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean isEqualList(List list1, List list2){
		if(list1 == list2){
			return true;
		}
		if(list1 == null || list2 == null || list1.size() != list2.size()){
			return false;
		}
		Iterator it1 = list1.iterator();
		Iterator it2 = list2.iterator();
		Object obj1 = null;
		Object obj2 = null;
		while(it1.hasNext() && it2.hasNext()){
			obj1 = it1.next();
			obj2 = it2.next();
			if(obj1 != null ? !obj1.equals(obj2) : obj2 != null){
				return false;
			}
		}
		return !it1.hasNext() && !it2.hasNext();
	}
	/**
	* 描述  : (计算 一个 list的 hashCode值)
	* 方法名: hashCodeForList
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:36:11
	* @param list
	* @return  
	* @return :int
	 */
	@SuppressWarnings("unchecked")
	public static int hashCodeForList(List list){
		
		if(list == null){
			return 0;
		}
		int hashCode = 1;
		Iterator it = list.iterator();
		Object obj = null;
		while(it.hasNext()){
			obj = it.next();
			 hashCode = 31 * hashCode + (obj != null ? obj.hashCode() : 0);
		}
		return hashCode;
	}
	
	/**
	* 描述  : (获取两个集合中的  交集)
	* 方法名: retainAll
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:38:07
	* @param collection
	* @param retain
	* @return  
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List retainAll(List list1, List retain){
		 
		 List list = new ArrayList(Math.min(list1.size(), retain.size()));
		 Iterator iter = list1.iterator();
		 do {
			 if(!iter.hasNext()){
				 break;
			 }
			 Object obj = iter.next();
			 if(retain.contains(obj)){
				 list.add(obj);
			 }
		} while (true);
		 
		 return list;
	 }
	 /**
	 * 描述  : (从 list1中  删除list2 预期相同的元素)
	 * 方法名: removeAll
	 * 创建人:孙刚   
	 * 创建时间:2014-1-22 上午09:38:11
	 * @param collection
	 * @param remove
	 * @return  
	 * @return :List
	  */
	 @SuppressWarnings("unchecked")
	public static List removeAll(List list1, List remove){
		 List list = new ArrayList();
		 Iterator iter = list1.iterator();
		 do {
			 if(!iter.hasNext()){
				 break;
			 }
			 Object obj = iter.next();
			 if(!remove.contains(obj)){
				 list.add(obj);
			 }
		} while (true);
		 
		 return list;
	 }
	 /**
	 * 描述  : (将当前list转换成 同步的SynchronizedList)
	 * 方法名: synchronizedList
	 * 创建人:孙刚   
	 * 创建时间:2014-1-22 上午09:40:48
	 * @param list
	 * @return  
	 * @return :List
	  */
	 @SuppressWarnings("unchecked")
	public static List synchronizedList(List list){
		 return SynchronizedList.decorate(list);
	}
	
	 /**
	 * 描述  : ()
	 * 方法名: unmodifiableList
	 * 创建人:孙刚   
	 * 创建时间:2014-1-22 上午09:41:19
	 * @param list
	 * @return  
	 * @return :List
	  */
	@SuppressWarnings("unchecked")
	public static List unmodifiableList(List list){
		return UnmodifiableList.decorate(list);
	}
	/**
	* 描述  : ()
	* 方法名: predicatedList
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:41:47
	* @param list
	* @param predicate
	* @return  
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List predicatedList(List list, Predicate predicate){
		return PredicatedList.decorate(list, predicate);
	}
	
	/**
	* 描述  : (这里用一句话描述这个方法的作用)
	* 方法名: typedList
	* 创建人:孙刚   
	* 创建时间:2014-1-22 上午09:42:33
	* @param list
	* @param type
	* @return  
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List typedList(List list, Class type){
		return TypedList.decorate(list, type);
	}
	
	@SuppressWarnings("unchecked")
	public static List transformedList(List list, Transformer transformer){
		return TransformedList.decorate(list, transformer);
	}
	
	@SuppressWarnings("unchecked")
	public static List lazyList(List list, Factory factory){
		return LazyList.decorate(list, factory);
	}
	
	@SuppressWarnings("unchecked")
	public static List fixedSizeList(List list){
		return FixedSizeList.decorate(list);
	}
	
	/**
	 * @Description: (计算一个 Double泛型 List 中最大值)
	 * @方法名: calculationMax</p>
	 * @param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeMax(List sampleList) {

		DecimalFormat df = new DecimalFormat("#.##");

		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}

		double maxDevation = 0d;
		int totalCount = sampleList.size();

		if (totalCount >= 1) {
			double max = Double.parseDouble(df.format(sampleList.get(0))
					.toString());
			for (int i = 0; i < totalCount; i++) {
				double temp = Double.parseDouble(df.format(sampleList.get(i))
						.toString());
				if (temp > max) {
					max = temp;
				}
			}
			maxDevation = max;
		}
		return maxDevation;
	}

	/**
	 * @Description: (计算一个Double泛型 List的最小值)
	 * @方法名: calculationMin</p>
	 *@param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeMin(List sampleList) {
		DecimalFormat df = new DecimalFormat("#.##");
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}
		double minDevation = 0d;
		int totalCount = sampleList.size();
		if (totalCount >= 1) {
			double min = Double.parseDouble(df.format(sampleList.get(0))
					.toString());
			for (int i = 0; i < totalCount; i++) {
				double temp = Double.parseDouble(df.format(sampleList.get(i))
						.toString());
				if (min > temp) {
					min = temp;
				}
			}
			minDevation = min;
		}
		return minDevation;
	}

	/**
	 * @Description: (计算一个Double泛型 List的平均值)
	 * @方法名: calculationAvg</p>
	 * @param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeAvg(List sampleList) {
		DecimalFormat df = new DecimalFormat("#.##");
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}
		double temp = 0d;
		double sum = 0d;
		int totalCount = sampleList.size();
		for (int i = 0; i < totalCount; i++) {
			sum += Double.parseDouble(df.format(sampleList.get(i)));
		}
		if (sum != 0) {
			temp = sum / totalCount;
		}
		
		return temp;
	}

	/**
	 * @Description: (计算一个Double泛型 List的总和)
	 * @方法名: calculationDoubleListTypeSum</p>
	 * @param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeSum(List sampleList) {
		DecimalFormat df = new DecimalFormat("#.##");
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}
		double sum = 0d;
		int totalCount = sampleList.size();
		for (int i = 0; i < totalCount; i++) {
			sum += Double.parseDouble(df.format(sampleList.get(i)));
		}
		
		
		return sum;
	}
}
CollectionUtils java
package cn.cd.sg.collection.utils;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;


public class CollectionUtils {
	
	
	/**
	* 描述  : (判断一个集合是否为null  为null时返回 true)
	* 方法名: isEmpty
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:35:08
	* @param collection
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean isEmpty(Collection collection) {
		return (collection == null || collection.isEmpty());
	}
	@SuppressWarnings("unchecked")
	public static boolean isEmpty(List list) {
		return (list == null || list.isEmpty());
	}
	@SuppressWarnings("unchecked")
	public static boolean isEmpty(Set set) {
		return (set == null || set.isEmpty());
	}
	@SuppressWarnings({ "unchecked", "null" })
	public static boolean isEmpty(Map map){
		if (null == map && map.size() < 0 ) {
			return true;
		}
		return false;
	}
	/**
	* 描述  : (判断一个对象数组是否为null)
	* 方法名: isEmpty
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:35:44
	* @param array
	* @return  
	* @return :boolean
	 */
	public static boolean isEmpty(Object[] array) {
		return (array == null || array.length == 0);
	}
	
	
	/**
	* @Description: 判断一个Map是否为null
	* @方法名: isEmpty
	* <p>@param : @param map
	* @return boolean    返回类型
	* @throws
	 */
	@SuppressWarnings("unchecked")
	public static boolean isNotEmpty(Map map){
		if (null != map && map.size() > 0 ) {
			return true;
		}
		return false;
	}
	/**
	* @Description: 判断一个集合是否为null
	* @方法名: 
	* @param : @param 
	* @return boolean    返回类型
	* @throws
	 */
	@SuppressWarnings("unchecked")
	public static boolean isNotEmpty(Collection	collection){
		if (collection != null && collection.size() > 0) {
			return true;
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	public static boolean isNotEmpty(List list){
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public static boolean isNotEmpty(Set set){
		if (set != null && set.size() > 0) {
			return true;
		}
		return false;
	}
	
	/**
	* 描述  : 将数组转换成List
	* 方法名: arrayToList
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:42:31
	* @param source
	* @return  
	* @return :List
	 */
	@SuppressWarnings("unchecked")
	public static List arrayToList(Object source) {
		return Arrays.asList(toObjectArray(source));
	}
	/**
	* 描述  : (将数组合并成集合)
	* 方法名: mergeArrayIntoCollection
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:45:04
	* @param array
	* @param collection  
	* @return :void
	 */
	@SuppressWarnings("unchecked")
	public static void mergeArrayIntoCollection(Object array, Collection collection) {
		if (collection == null) {
			throw new IllegalArgumentException("Collection must not be null");
		}
		Object[] arr = toObjectArray(array);
		for (Object elem : arr) {
			collection.add(elem);
		}
	}
	/**
	* 描述  : (Propertiess 转换成 Map)
	* 方法名: mergePropertiesIntoMap
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:49:44
	* @param props
	* @param map  
	* @return :void
	 */
	@SuppressWarnings("unchecked")
	public static void mergePropertiesIntoMap(Properties props, Map map) {
		if (map == null) {
			throw new IllegalArgumentException("Map must not be null");
		}
		if (props != null) {
			for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {
				String key = (String) en.nextElement();
				Object value = props.getProperty(key);
				if (value == null) {
					value = props.get(key);
				}
				map.put(key, value);
			}
		}
	}
	/**
	 * 
	* 描述  : (判断一个迭代器 是否包含某个元素)
	* 方法名: contains
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:57:49
	* @param iterator
	* @param element
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean contains(Iterator iterator, Object element) {
		if (iterator != null) {
			while (iterator.hasNext()) {
				Object candidate = iterator.next();
				if (nullSafeEquals(candidate, element)) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	* 描述  : (判断一个Enumeration 是否包含 一个元素对元素)
	* 方法名: contains
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:00:24
	* @param enumeration
	* @param element
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean contains(Enumeration enumeration, Object element) {
		if (enumeration != null) {
			while (enumeration.hasMoreElements()) {
				Object candidate = enumeration.nextElement();
				if (nullSafeEquals(candidate, element)) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	* 描述  : (验证给定集合 是否包含某元素)
	* 方法名: containsInstance
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:00:48
	* @param collection
	* @param element
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean containsInstance(Collection collection, Object element) {
		if (collection != null) {
			for (Object candidate : collection) {
				if (candidate == element) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	* 描述  : (判断一个集合是否 包含另一个集合)
	* 方法名: containsAny
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:05:18
	* @param source
	* @param candidates
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean containsAny(Collection source, Collection candidates) {
		if (isEmpty(source) || isEmpty(candidates)) {
			return false;
		}
		for (Object candidate : candidates) {
			if (source.contains(candidate)) {
				return true;
			}
		}
		return false;
	}
	/**
	* 描述  : (两个集合 判断是否包含 并返回第一个匹配的  不包含返回 null)
	* 方法名: findFirstMatch
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:10:00
	* @param source
	* @param candidates
	* @return  
	* @return :Object
	 */
	@SuppressWarnings("unchecked")
	public static Object findFirstMatch(Collection source, Collection candidates) {
		if (isEmpty(source) || isEmpty(candidates)) {
			return null;
		}
		for (Object candidate : candidates) {
			if (source.contains(candidate)) {
				return candidate;
			}
		}
		return null;
	}
	
	/**
	* 描述  : (查找集合中   指定类型的value值)
	* 方法名: findValueOfType
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:15:31
	* @param <T>
	* @param collection
	* @param type
	* @return  
	* @return :T
	 */
	@SuppressWarnings("unchecked")
	public static <T> T findValueOfType(Collection<?> collection, Class<T> type) {
		if (isEmpty(collection)) {
			return null;
		}
		T value = null;
		for (Object element : collection) {
			if (type == null || type.isInstance(element)) {
				if (value != null) {
					return null;
				}
				value = (T) element;
			}
		}
		return value;
	}
	
	public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
		if (isEmpty(collection) || isEmpty(types)) {
			return null;
		}
		for (Class<?> type : types) {
			Object value = findValueOfType(collection, type);
			if (value != null) {
				return value;
			}
		}
		return null;
	}
	
	
	/**
	* 描述  : (判断一个集合中是否只包含一种类型)
	* 方法名: hasUniqueObject
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:21:05
	* @param collection
	* @return  
	* @return :boolean
	 */
	@SuppressWarnings("unchecked")
	public static boolean hasUniqueObject(Collection collection) {
		if (isEmpty(collection)) {
			return false;
		}
		boolean hasCandidate = false;
		Object candidate = null;
		for (Object elem : collection) {
			if (!hasCandidate) {
				hasCandidate = true;
				candidate = elem;
			}
			else if (candidate != elem) {
				return false;
			}
		}
		return true;
	}
	
	/**
	* 描述  : (获取集合中 元素类型)
	* 方法名: findCommonElementType
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:23:58
	* @param collection
	* @return  
	* @return :Class<?>
	 */
	@SuppressWarnings("unchecked")
	public static Class<?> findCommonElementType(Collection collection) {
		if (isEmpty(collection)) {
			return null;
		}
		Class<?> candidate = null;
		for (Object val : collection) {
			if (val != null) {
				if (candidate == null) {
					candidate = val.getClass();
				}
				else if (candidate != val.getClass()) {
					return null;
				}
			}
		}
		return candidate;
	}
	
	/**
	* 描述  : (讲一个  数组转换成  对象数组  source必须是数组类型)
	* 方法名: toObjectArray
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午04:28:41
	* @param source
	* @return  
	* @return :Object[]
	 */
	@SuppressWarnings("unchecked")
	public static Object[] toObjectArray(Object source) {
		if (source instanceof Object[]) {
			return (Object[]) source;
		}
		if (source == null) {
			return new Object[0];
		}
		if (!source.getClass().isArray()) {
			throw new IllegalArgumentException("Source is not an array: " + source);
		}
		int length = Array.getLength(source);
		if (length == 0) {
			return new Object[0];
		}
		Class wrapperType = Array.get(source, 0).getClass();
		Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
		for (int i = 0; i < length; i++) {
			newArray[i] = Array.get(source, i);
		}
		return newArray;
	}
	
	
	private static boolean nullSafeEquals(Object o1, Object o2) {
		if (o1 == o2) {
			return true;
		}
		if (o1 == null || o2 == null) {
			return false;
		}
		if (o1.equals(o2)) {
			return true;
		}
		if (o1.getClass().isArray() && o2.getClass().isArray()) {
			if (o1 instanceof Object[] && o2 instanceof Object[]) {
				return Arrays.equals((Object[]) o1, (Object[]) o2);
			}
			if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
				return Arrays.equals((boolean[]) o1, (boolean[]) o2);
			}
			if (o1 instanceof byte[] && o2 instanceof byte[]) {
				return Arrays.equals((byte[]) o1, (byte[]) o2);
			}
			if (o1 instanceof char[] && o2 instanceof char[]) {
				return Arrays.equals((char[]) o1, (char[]) o2);
			}
			if (o1 instanceof double[] && o2 instanceof double[]) {
				return Arrays.equals((double[]) o1, (double[]) o2);
			}
			if (o1 instanceof float[] && o2 instanceof float[]) {
				return Arrays.equals((float[]) o1, (float[]) o2);
			}
			if (o1 instanceof int[] && o2 instanceof int[]) {
				return Arrays.equals((int[]) o1, (int[]) o2);
			}
			if (o1 instanceof long[] && o2 instanceof long[]) {
				return Arrays.equals((long[]) o1, (long[]) o2);
			}
			if (o1 instanceof short[] && o2 instanceof short[]) {
				return Arrays.equals((short[]) o1, (short[]) o2);
			}
		}
		return false;
	}
	
	
	
	public static <E> Iterator<E> toIterator(Enumeration<E> enumeration) {
		return new EnumerationIterator<E>(enumeration);
	}
	
	/**
	 * Iterator wrapping an Enumeration.
	 */
	private static class EnumerationIterator<E> implements Iterator<E> {

		private Enumeration<E> enumeration;

		public EnumerationIterator(Enumeration<E> enumeration) {
			this.enumeration = enumeration;
		}

		public boolean hasNext() {
			return this.enumeration.hasMoreElements();
		}

		public E next() {
			return this.enumeration.nextElement();
		}

		public void remove() throws UnsupportedOperationException {
			throw new UnsupportedOperationException("Not supported");
		}
	}

}
DataCalculateUtils java
package cn.cd.sg.calculate.utils;


import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

/**
 * @Description: 数据计算使用 项目名称:
 * utils 类名称:DataCalculateUtils 
 * 创建时间:2014-1-14
 * 下午01:45:28 
 * 修改人1:xxx 
 * 修改时间1:xxxx-xx-xx 
 * 修改备注:
 * @version 1.0
 */
public class DataCalculateUtils {

	/** 精度 */
	@SuppressWarnings("unused")
	private static final int DEF_DIV_SCALE = 2;
	/**
	 * double类型保留两位小数的格式化对象
	 */
	public static DecimalFormat df = new DecimalFormat("#.##");// 保留2位小数
	
	/**
	* @Description: 讲一个DOuble数据 保留两位小数
	* @方法名: doubleFormat</p>
	* <p>@param : @param douData
	* <p>@param : @return    设定文件</p>
	* @return Double    返回类型</p>
	* @throws
	 */
	public static Double doubleFormat(Double douData){
		return Double.parseDouble(df.format(douData));
	}
	
	/**
	 * @Description: (计算一个 Double泛型 List 中最大值)
	 * @方法名: calculationMax</p>
	 * @param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeMax(List sampleList) {
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}

		double maxDevation = 0d;
		int totalCount = sampleList.size();

		if (totalCount >= 1) {
			double max = Double.parseDouble(df.format(sampleList.get(0))
					.toString());
			for (int i = 0; i < totalCount; i++) {
				double temp = Double.parseDouble(df.format(sampleList.get(i))
						.toString());
				if (temp > max) {
					max = temp;
				}
			}
			maxDevation = max;
		}
		return maxDevation;
	}
	
	/**
	 * @Description: (计算一个Double泛型 List的最小值)
	 * @方法名: calculationMin</p>
	 *@param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeMin(List sampleList) {
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}
		double minDevation = 0d;
		int totalCount = sampleList.size();
		if (totalCount >= 1) {
			double min = Double.parseDouble(df.format(sampleList.get(0))
					.toString());
			for (int i = 0; i < totalCount; i++) {
				double temp = Double.parseDouble(df.format(sampleList.get(i))
						.toString());
				if (min > temp) {
					min = temp;
				}
			}
			minDevation = min;
		}
		return minDevation;
	}
	
	/**
	 * @Description: (计算一个Double泛型 List的平均值)
	 * @方法名: calculationAvg</p>
	 * @param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeAvg(List sampleList) {
		DecimalFormat df = new DecimalFormat("#.##");
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}
		double temp = 0d;
		double sum = 0d;
		int totalCount = sampleList.size();
		for (int i = 0; i < totalCount; i++) {
			sum += Double.parseDouble(df.format(sampleList.get(i)));
		}

		temp = sum / totalCount;

		return temp;
	}
	
	/**
	 * @Description: (计算一个Double泛型 List的总和)
	 * @方法名: calculationDoubleListTypeSum</p>
	 * @param : @param sampleList
	 * @return Double 返回类型</p>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Double calculationDoubleListTypeSum(List sampleList) {
		DecimalFormat df = new DecimalFormat("#.##");
		if (null == sampleList) {
			throw new NullPointerException("list is not null");
		}
		double sum = 0d;
		int totalCount = sampleList.size();
		for (int i = 0; i < totalCount; i++) {
			sum += Double.parseDouble(df.format(sampleList.get(i)));
		}
		return sum;
	}
	
	/**
	 * 加,BigDecimal用
	 * 
	 * @param v1
	 * @param v2
	 * @return result
	 */
	public static BigDecimal add(Object v1, Object v2) {
		BigDecimal result = null;
		BigDecimal b1 = new BigDecimal(v1.toString());
		BigDecimal b2 = new BigDecimal(v2.toString());
		result = b1.add(b2);
		return result;
	}

	/**
	 * 减,BigDecimal用
	 * 
	 * @param v1
	 * @param v2
	 * @return result
	 */
	public static BigDecimal sub(Object v1, Object v2) {
		BigDecimal result = null;
		BigDecimal b1 = new BigDecimal(v1.toString());
		BigDecimal b2 = new BigDecimal(v2.toString());
		result = b1.subtract(b2);
		return result;
	}

	/**
	 * 乘,BigDecimal用
	 * 
	 * @param v1
	 * @param v2
	 * @return result
	 */
	public static BigDecimal mul(Object v1, Object v2) {
		BigDecimal result = null;
		BigDecimal b1 = new BigDecimal(v1.toString());
		BigDecimal b2 = new BigDecimal(v2.toString());
		result = b1.multiply(b2);
		return result;
	}

	/**
	 * 除,BigDecimal用
	 * 
	 * @param v1
	 * @param v2
	 * @return result
	 */
	public static BigDecimal div(Object v1, Object v2) {
		BigDecimal result = null;
		BigDecimal b1 = new BigDecimal(v1.toString());
		BigDecimal b2 = new BigDecimal(v2.toString());
		result = b1.divide(b2);
		return result;
	}

	/**
	 * 
	 * @param v1
	 * @param v2
	 * @param scale
	 * @return result
	 */
	public static BigDecimal div(Object v1, Object v2, int scale) {
		BigDecimal result = null;
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(v1.toString());
		BigDecimal b2 = new BigDecimal(v2.toString());
		result = b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP);
		return result;
	}
	/**
	 * 
	 * @param v1
	 * @param v2
	 * @param scale
	 * @return result
	 */
	public static BigDecimal round(BigDecimal v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal one = new BigDecimal("1");
		return v.divide(one, scale, BigDecimal.ROUND_HALF_UP);
	}
}
ArrayUtils java
package cn.cd.sg.array.utils;

import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import cn.cd.sg.validate.utils.Validate;

@SuppressWarnings("unchecked")
public class ArrayUtils {

	public static final Object EMPTY_OBJECT_ARRAY[] = new Object[0];
	public static final Class EMPTY_CLASS_ARRAY[] = new Class[0];
	public static final String EMPTY_STRING_ARRAY[] = new String[0];
	public static final long EMPTY_LONG_ARRAY[] = new long[0];
	public static final Long EMPTY_LONG_OBJECT_ARRAY[] = new Long[0];
	public static final int EMPTY_INT_ARRAY[] = new int[0];
	public static final Integer EMPTY_INTEGER_OBJECT_ARRAY[] = new Integer[0];
	public static final short EMPTY_SHORT_ARRAY[] = new short[0];
	public static final Short EMPTY_SHORT_OBJECT_ARRAY[] = new Short[0];
	public static final byte EMPTY_BYTE_ARRAY[] = new byte[0];
	public static final Byte EMPTY_BYTE_OBJECT_ARRAY[] = new Byte[0];
	public static final double EMPTY_DOUBLE_ARRAY[] = new double[0];
	public static final Double EMPTY_DOUBLE_OBJECT_ARRAY[] = new Double[0];
	public static final float EMPTY_FLOAT_ARRAY[] = new float[0];
	public static final Float EMPTY_FLOAT_OBJECT_ARRAY[] = new Float[0];
	public static final boolean EMPTY_BOOLEAN_ARRAY[] = new boolean[0];
	public static final Boolean EMPTY_BOOLEAN_OBJECT_ARRAY[] = new Boolean[0];
	public static final char EMPTY_CHAR_ARRAY[] = new char[0];
	public static final Character EMPTY_CHARACTER_OBJECT_ARRAY[] = new Character[0];
	public static final int INDEX_NOT_FOUND = -1;

	/**
	 * 描述 : () 
	 * 方法名: toString 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午10:41:23
	 * @param array
	 * @return :String
	 */
	public static String toString(Object array) {

		return toString(array, "{}");
	}

	/**
	 * 描述 : (打印数组) 
	 * 方法名: toString 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午10:41:41
	 * @param array
	 * @param stringIfNull
	 * @return :String
	 */
	public static String toString(Object array, String stringIfNull) {
		if (array == null) {
			return stringIfNull;
		} else {
			return (new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE))
					.append(array).toString();
		}
	}

	/**
	 * 描述 : () 
	 * 方法名: hashCode 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午10:42:37
	 * 
	 * @param array
	 * @return :int
	 */
	public static int hashCode(Object array) {
		return (new HashCodeBuilder()).append(array).toHashCode();
	}

	/**
	 * 描述 : (判断数组内容是否相等) 
	 * 方法名: isEquals 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午10:43:19
	 * @param array1
	 * @param array2
	 * @return :boolean
	 */
	public static boolean isEquals(Object array1, Object array2) {
		return (new EqualsBuilder()).append(array1, array2).isEquals();
	}

	/**
	 * 描述 : () 
	 * 方法名: toMap 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午10:43:44
	 * @param array
	 * @return :Map
	 */
	public static Map toMap(Object array[]) {
		Validate.notNull(array, "array is not null");
		Map map = new HashMap((int) ((double) array.length * 1.5D));
		for (int i = 0; i < array.length; i++) {
			Object object = array[i];
			if (object instanceof Entry) {
				Entry entry = (Entry) object;
				map.put(entry.getKey(), entry.getValue());
				continue;
			}
			if (object instanceof Object[]) {
				Object entry[] = (Object[]) (Object[]) object;
				if (entry.length < 2) {
					throw new IllegalArgumentException("Array element " + i
							+ ", '" + object + "', has a length less than 2");
				}
				map.put(entry[0], entry[1]);
			} else {
				throw new IllegalArgumentException("Array element " + i + ", '"
						+ object
						+ "', is neither of type Map.Entry nor an Array");
			}
		}
		return map;
	}

	/**
	 * 描述 : (复制) 
	 * 方法名: clone 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午10:48:01
	 * @param array
	 * @return :Object[]
	 */
	public static Object[] clone(Object array[]) {
		if (array == null) {
			return null;
		} else {
			return (Object[]) (Object[]) array.clone();
		}
	}

	
	public static long[] clone(long array[]) {
		if (array == null) {
			return null;
		} else {
			return (long[]) (long[]) array.clone();
		}
	}


	public static int[] clone(int array[]) {
		if (array == null) {
			return null;
		} else {
			return (int[]) (int[]) array.clone();
		}
	}


	public static short[] clone(short array[]) {
		if (array == null) {
			return null;
		} else {
			return (short[]) (short[]) array.clone();
		}
	}


	public static char[] clone(char array[]) {
		if (array == null) {
			return null;
		} else {
			return (char[]) (char[]) array.clone();
		}
	}


	public static byte[] clone(byte array[]) {
		if (array == null) {
			return null;
		} else {
			return (byte[]) (byte[]) array.clone();
		}
	}


	public static double[] clone(double array[]) {
		if (array == null) {
			return null;
		} else {
			return (double[]) (double[]) array.clone();
		}
	}


	public static float[] clone(float array[]) {
		if (array == null) {
			return null;
		} else {
			return (float[]) (float[]) array.clone();
		}
	}


	public static boolean[] clone(boolean array[]) {
		if (array == null) {
			return null;
		} else {
			return (boolean[]) (boolean[]) array.clone();
		}
	}


	public static Object[] nullToEmpty(Object array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_OBJECT_ARRAY;
		} else {
			return array;
		}
	}


	public static String[] nullToEmpty(String array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_STRING_ARRAY;
		} else {
			return array;
		}
	}


	public static long[] nullToEmpty(long array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_LONG_ARRAY;
		} else {
			return array;
		}
	}


	public static int[] nullToEmpty(int array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_INT_ARRAY;
		} else {
			return array;
		}
	}


	public static short[] nullToEmpty(short array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_SHORT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static char[] nullToEmpty(char array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_CHAR_ARRAY;
		} else {
			return array;
		}
	}

	
	public static byte[] nullToEmpty(byte array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_BYTE_ARRAY;
		} else {
			return array;
		}
	}

	
	public static double[] nullToEmpty(double array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_DOUBLE_ARRAY;
		} else {
			return array;
		}
	}

	
	public static float[] nullToEmpty(float array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_FLOAT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static boolean[] nullToEmpty(boolean array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_BOOLEAN_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Long[] nullToEmpty(Long array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_LONG_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Integer[] nullToEmpty(Integer array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_INTEGER_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Short[] nullToEmpty(Short array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_SHORT_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Character[] nullToEmpty(Character array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_CHARACTER_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Byte[] nullToEmpty(Byte array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_BYTE_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Double[] nullToEmpty(Double array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_DOUBLE_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Float[] nullToEmpty(Float array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_FLOAT_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Boolean[] nullToEmpty(Boolean array[]) {
		if (array == null || array.length == 0) {
			return EMPTY_BOOLEAN_OBJECT_ARRAY;
		} else {
			return array;
		}
	}

	
	public static Object[] subarray(Object array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		Class type = ((Object) (array)).getClass().getComponentType();
		if (newSize <= 0) {
			return (Object[]) (Object[]) Array.newInstance(type, 0);
		} else {
			Object subarray[] = (Object[]) (Object[]) Array.newInstance(type,
					newSize);
			System.arraycopy(((Object) (array)), startIndexInclusive,
					((Object) (subarray)), 0, newSize);
			return subarray;
		}
	}

	
	public static long[] subarray(long array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_LONG_ARRAY;
		} else {
			long subarray[] = new long[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}

	public static int[] subarray(int array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_INT_ARRAY;
		} else {
			int subarray[] = new int[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}

	
	public static short[] subarray(short array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_SHORT_ARRAY;
		} else {
			short subarray[] = new short[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}

	
	public static char[] subarray(char array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_CHAR_ARRAY;
		} else {
			char subarray[] = new char[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}

	
	public static byte[] subarray(byte array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_BYTE_ARRAY;
		} else {
			byte subarray[] = new byte[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}
	
	public static double[] subarray(double array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_DOUBLE_ARRAY;
		} else {
			double subarray[] = new double[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}
	
	public static float[] subarray(float array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_FLOAT_ARRAY;
		} else {
			float subarray[] = new float[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}

	public static boolean[] subarray(boolean array[], int startIndexInclusive,
			int endIndexExclusive) {
		if (array == null) {
			return null;
		}
		if (startIndexInclusive < 0) {
			startIndexInclusive = 0;
		}
		if (endIndexExclusive > array.length) {
			endIndexExclusive = array.length;
		}
		int newSize = endIndexExclusive - startIndexInclusive;
		if (newSize <= 0) {
			return EMPTY_BOOLEAN_ARRAY;
		} else {
			boolean subarray[] = new boolean[newSize];
			System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
			return subarray;
		}
	}

	/**
	 * 描述 : (判断两个数组是否长度相等) 
	 * 方法名: isSameLength 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午11:09:51
	 * @param array1
	 * @param array2
	 * @return :boolean
	 */
	public static boolean isSameLength(Object array1[], Object array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}


	public static boolean isSameLength(long array1[], long array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(int array1[], int array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(short array1[], short array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(char array1[], char array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(byte array1[], byte array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(double array1[], double array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(float array1[], float array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	public static boolean isSameLength(boolean array1[], boolean array2[]) {
		return (array1 != null || array2 == null || array2.length <= 0)
				&& (array2 != null || array1 == null || array1.length <= 0)
				&& (array1 == null || array2 == null || array1.length == array2.length);
	}

	/**
	 * 描述 : (获取一个数组的长度) 
	 * 方法名: getLength 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午11:13:44
	 * @param array
	 * @return :int
	 */
	public static int getLength(Object array) {
		
		if (array == null) {
			return 0;
		} else {
			return Array.getLength(array);
		}
	}

	/**
	 * 描述 : (判断两个数组是否是相等的类型) 
	 * 方法名: isSameType 
	 * 创建人:孙刚
	 * 创建时间:2014-1-22 上午11:14:37
	 * @param array1
	 * @param array2
	 * @return :boolean
	 */
	public static boolean isSameType(Object array1, Object array2) {
		if (array1 == null || array2 == null) {
			throw new IllegalArgumentException("The Array must not be null");
		} else {
			return array1.getClass().getName().equals(
					array2.getClass().getName());
		}
	}

	/**
	 * 描述 : (反转数组内容) 
	 * 方法名: reverse 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午11:15:21
	 * @param array
	 * @return :void
	 */
	public static void reverse(Object array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			Object tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}


	public static void reverse(long array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			long tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}

	public static void reverse(int array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			int tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}
	
	
	public static void reverse(short array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			short tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}

	public static void reverse(char array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			char tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}

	public static void reverse(byte array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			byte tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}

	public static void reverse(double array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			double tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}
	
	public static void reverse(float array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			float tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}

	public static void reverse(boolean array[]) {
		if (array == null) {
			return;
		}
		int i = 0;
		for (int j = array.length - 1; j > i; i++) {
			boolean tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
		}
	}

	/**
	 * 描述 : (获取指定内容所在数组下标位置,找不到返回 -1) 
	 * 方法名: indexOf 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午11:19:37
	 * @param array
	 * @param objectToFind
	 * @return :int
	 */
	public static int indexOf(Object array[], Object objectToFind) {
		return indexOf(array, objectToFind, 0);
	}

	public static int indexOf(Object array[], Object objectToFind,
			int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		if (objectToFind == null) {
			for (int i = startIndex; i < array.length; i++) {
				if (array[i] == null) {
					return i;
				}
			}
		} else {
			for (int i = startIndex; i < array.length; i++) {
				if (objectToFind.equals(array[i])) {
					return i;
				}
			}
		}
		return -1;
	}

	/**
	 * 描述 : (获取指定元素在数组中 最后一次出现的位置) 
	 * 方法名: lastIndexOf 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午11:22:48
	 * @param array
	 * @param objectToFind
	 * @return :int
	 */
	public static int lastIndexOf(Object array[], Object objectToFind) {
		return lastIndexOf(array, objectToFind, 2147483647);
	}

	public static int lastIndexOf(Object array[], Object objectToFind,
			int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		if (objectToFind == null) {
			for (int i = startIndex; i >= 0; i--) {
				if (array[i] == null) {
					return i;
				}
			}
		} else {
			for (int i = startIndex; i >= 0; i--) {
				if (objectToFind.equals(array[i])) {
					return i;
				}
			}
		}
		return -1;
	}

	/**
	 * 描述 : (判断一个数组中是否包含此元素) 
	 * 方法名: contains 
	 * 创建人:孙刚 
	 * 创建时间:2014-1-22 上午11:40:01
	 * @param array
	 * @param objectToFind
	 * @return :boolean
	 */
	public static boolean contains(Object array[], Object objectToFind) {
		return indexOf(array, objectToFind) != -1;
	}

	
	public static int indexOf(long array[], long valueToFind) {
		return indexOf(array, valueToFind, 0);
	}

	
	public static int indexOf(long array[], long valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}

	
	public static int lastIndexOf(long array[], long valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}

	
	public static int lastIndexOf(long array[], long valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i]) {
				return i;
			}
		}

		return -1;
	}

	
	public static boolean contains(long array[], long valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}

	
	public static int indexOf(int array[], int valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	
	public static int indexOf(int array[], int valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static int lastIndexOf(int array[], int valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(int array[], int valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static boolean contains(int array[], int valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	public static int indexOf(short array[], short valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	public static int indexOf(short array[], short valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static int lastIndexOf(short array[], short valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(short array[], short valueToFind,
			int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static boolean contains(short array[], short valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	public static int indexOf(char array[], char valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	public static int indexOf(char array[], char valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static int lastIndexOf(char array[], char valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(char array[], char valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static boolean contains(char array[], char valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	public static int indexOf(byte array[], byte valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	public static int indexOf(byte array[], byte valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static int lastIndexOf(byte array[], byte valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(byte array[], byte valueToFind, int startIndex) {
		if (array == null) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static boolean contains(byte array[], byte valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	public static int indexOf(double array[], double valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	public static int indexOf(double array[], double valueToFind,
			double tolerance) {
		return indexOf(array, valueToFind, 0, tolerance);
	}
	
	public static int indexOf(double array[], double valueToFind, int startIndex) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i]) {
				return i;
			}
		}
		return -1;
	}
	
	public static int indexOf(double array[], double valueToFind,
			int startIndex, double tolerance) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		double min = valueToFind - tolerance;
		double max = valueToFind + tolerance;
		for (int i = startIndex; i < array.length; i++) {
			if (array[i] >= min && array[i] <= max)
				return i;
		}
		return -1;
	}
	
	public static int lastIndexOf(double array[], double valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(double array[], double valueToFind,
			double tolerance) {
		return lastIndexOf(array, valueToFind, 2147483647, tolerance);
	}
	
	public static int lastIndexOf(double array[], double valueToFind,
			int startIndex) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i])
				return i;
		}
		return -1;
	}
	
	public static int lastIndexOf(double array[], double valueToFind,
			int startIndex, double tolerance) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		double min = valueToFind - tolerance;
		double max = valueToFind + tolerance;
		for (int i = startIndex; i >= 0; i--) {
			if (array[i] >= min && array[i] <= max)
				return i;
		}
		return -1;
	}
	
	public static boolean contains(double array[], double valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	public static boolean contains(double array[], double valueToFind,
			double tolerance) {
		return indexOf(array, valueToFind, 0, tolerance) != -1;
	}
	
	public static int indexOf(float array[], float valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	public static int indexOf(float array[], float valueToFind, int startIndex) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i])
				return i;
		}
		return -1;
	}
	
	public static int lastIndexOf(float array[], float valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(float array[], float valueToFind,
			int startIndex) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i])
				return i;
		}
		return -1;
	}
	
	public static boolean contains(float array[], float valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	public static int indexOf(boolean array[], boolean valueToFind) {
		return indexOf(array, valueToFind, 0);
	}
	
	public static int indexOf(boolean array[], boolean valueToFind,
			int startIndex) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		for (int i = startIndex; i < array.length; i++) {
			if (valueToFind == array[i])
				return i;
		}
		return -1;
	}
	
	public static int lastIndexOf(boolean array[], boolean valueToFind) {
		return lastIndexOf(array, valueToFind, 2147483647);
	}
	
	public static int lastIndexOf(boolean array[], boolean valueToFind,
			int startIndex) {
		if (isEmpty(array)) {
			return -1;
		}
		if (startIndex < 0) {
			return -1;
		}
		if (startIndex >= array.length) {
			startIndex = array.length - 1;
		}
		for (int i = startIndex; i >= 0; i--) {
			if (valueToFind == array[i])
				return i;
		}
		return -1;
	}
	
	public static boolean contains(boolean array[], boolean valueToFind) {
		return indexOf(array, valueToFind) != -1;
	}
	
	
	public static char[] toPrimitive(Character array[]) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return EMPTY_CHAR_ARRAY;
		}
		char result[] = new char[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = array[i].charValue();
		}
		return result;
	}
	
	public static char[] toPrimitive(Character array[], char valueForNull) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return EMPTY_CHAR_ARRAY;
		}
		char result[] = new char[array.length];
		for (int i = 0; i < array.length; i++) {
			Character b = array[i];
			result[i] = b != null ? b.charValue() : valueForNull;
		}
		return result;
	}
	
	public static Character[] toObject(char array[]) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return EMPTY_CHARACTER_OBJECT_ARRAY;
		}
		Character result[] = new Character[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = new Character(array[i]);
		}
		return result;
	}
	
	public static long[] toPrimitive(Long array[]) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return EMPTY_LONG_ARRAY;
		}
		long result[] = new long[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = array[i].longValue();
		}
		return result;
	}
	
	public static long[] toPrimitive(Long array[], long valueForNull) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return EMPTY_LONG_ARRAY;
		}
		long result[] = new long[array.length];
		for (int i = 0; i < array.length; i++) {
			Long b = array[i];
			result[i] = b != null ? b.longValue() : valueForNull;
		}
		return result;
	}
	
	public static Long[] toObject(long array[]) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return EMPTY_LONG_OBJECT_ARRAY;
		}
		Long result[] = new Long[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = new Long(array[i]);
		}
		return result;
	}
	
	public static int[] toPrimitive(Integer array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0) {{
			return EMPTY_INT_ARRAY;
		}
		}
		int result[] = new int[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i].intValue();
		}
		return result;
	}

	public static int[] toPrimitive(Integer array[], int valueForNull) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_INT_ARRAY;
		}
		int result[] = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			Integer b = array[i];
			result[i] = b != null ? b.intValue() : valueForNull;
		}
		return result;
	}
	/**
	* 描述  : (将一个基本类型数组  装换成对应的包装类的类型)
	* 方法名: toObject
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:14:53
	* @param array
	* @return  
	* @return :Integer[]
	 */
	public static Integer[] toObject(int array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_INTEGER_OBJECT_ARRAY;
		}
		Integer result[] = new Integer[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = new Integer(array[i]);
		}
		return result;
	}
	
	public static short[] toPrimitive(Short array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_SHORT_ARRAY;
		}
		short result[] = new short[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i].shortValue();
		}
		return result;
	}
	
	public static short[] toPrimitive(Short array[], short valueForNull) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_SHORT_ARRAY;
		}
		short result[] = new short[array.length];
		for (int i = 0; i < array.length; i++) {
			Short b = array[i];
			result[i] = b != null ? b.shortValue() : valueForNull;
		}
		return result;
	}
	
	public static Short[] toObject(short array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_SHORT_OBJECT_ARRAY;
		}
		Short result[] = new Short[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = new Short(array[i]);
		}
		return result;
	}
	
	public static byte[] toPrimitive(Byte array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_BYTE_ARRAY;
		}
		byte result[] = new byte[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i].byteValue();
		}

		return result;
	}
	
	public static byte[] toPrimitive(Byte array[], byte valueForNull) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_BYTE_ARRAY;
		}
		byte result[] = new byte[array.length];
		for (int i = 0; i < array.length; i++) {
			Byte b = array[i];
			result[i] = b != null ? b.byteValue() : valueForNull;
		}
		return result;
	}
	
	public static Byte[] toObject(byte array[]) {

		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_BYTE_OBJECT_ARRAY;
		}

		Byte result[] = new Byte[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = new Byte(array[i]);
		}

		return result;
	}
	
	public static double[] toPrimitive(Double array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_DOUBLE_ARRAY;
		}
		double result[] = new double[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i].doubleValue();
		}

		return result;
	}
	
	public static double[] toPrimitive(Double array[], double valueForNull) {

		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_DOUBLE_ARRAY;
		}
		double result[] = new double[array.length];
		for (int i = 0; i < array.length; i++) {
			Double b = array[i];
			result[i] = b != null ? b.doubleValue() : valueForNull;
		}
		return result;
	}
	
	public static Double[] toObject(double array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_DOUBLE_OBJECT_ARRAY;
		}

		Double result[] = new Double[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = new Double(array[i]);
		}

		return result;
	}

	public static float[] toPrimitive(Float array[]) {

		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_FLOAT_ARRAY;
		}

		float result[] = new float[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i].floatValue();
		}

		return result;
	}
	
	public static float[] toPrimitive(Float array[], float valueForNull) {

		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_FLOAT_ARRAY;
		}
		float result[] = new float[array.length];
		for (int i = 0; i < array.length; i++) {
			Float b = array[i];
			result[i] = b != null ? b.floatValue() : valueForNull;
		}
		return result;
	}
	
	public static Float[] toObject(float array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_FLOAT_OBJECT_ARRAY;
		}
		Float result[] = new Float[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = new Float(array[i]);
		}

		return result;
	}
	
	public static boolean[] toPrimitive(Boolean array[]) {
		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_BOOLEAN_ARRAY;
		}
		boolean result[] = new boolean[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i].booleanValue();
		}

		return result;
	}
	
	public static boolean[] toPrimitive(Boolean array[], boolean valueForNull) {

		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_BOOLEAN_ARRAY;
		}

		boolean result[] = new boolean[array.length];
		for (int i = 0; i < array.length; i++) {
			Boolean b = array[i];
			result[i] = b != null ? b.booleanValue() : valueForNull;
		}
		return result;
	}
	
	public static Boolean[] toObject(boolean array[]) {

		if (array == null){
			return null;
		}
		if (array.length == 0){
			return EMPTY_BOOLEAN_OBJECT_ARRAY;
		}

		Boolean result[] = new Boolean[array.length];
		for (int i = 0; i < array.length; i++){
			result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;
		}

		return result;
	}
	/**
	* 描述  : (判断一个数组是否为 null  为null  时返回 true)
	* 方法名: isEmpty
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:17:47
	* @param array
	* @return  
	* @return :boolean
	 */
	public static boolean isEmpty(Object array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(long array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(int array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(short array[]) {
		return array == null || array.length == 0;
	}	
	
	public static boolean isEmpty(char array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(byte array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(double array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(float array[]) {
		return array == null || array.length == 0;
	}
	
	public static boolean isEmpty(boolean array[]) {
		return array == null || array.length == 0;
	}
	/**
	* 描述  : (判断一个数组不为null  不为 null时  返回 true)
	* 方法名: isNotEmpty
	* 创建人:孙刚   
	* 创建时间:2014-2-8 下午03:18:23
	* @param array
	* @return  
	* @return :boolean
	 */
	public static boolean isNotEmpty(Object array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(long array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(int array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(short array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(char array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(byte array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(double array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(float array[]) {
		return array != null && array.length != 0;
	}
	
	public static boolean isNotEmpty(boolean array[]) {
		return array != null && array.length != 0;
	}
	/**
	* 描述  : (将两个数组 合并为一个数组)
	* 方法名: addAll
	* 创建人:孙刚   
	* 创建时间:2014-1-22 下午02:36:32
	* @param array1
	* @param array2
	* @return  
	* @return :Object[]
	 */
	public static Object[] addAll(Object array1[], Object array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null){
			return clone(array1);
		}

		Object joinedArray[] = (Object[]) (Object[]) Array.newInstance(
				((Object) (array1)).getClass().getComponentType(),
				array1.length + array2.length);

		System.arraycopy(((Object) (array1)), 0, ((Object) (joinedArray)), 0,array1.length);

		try {
			System.arraycopy(((Object) (array2)), 0, ((Object) (joinedArray)),
					array1.length, array2.length);
		} catch (ArrayStoreException ase) {

			Class type1 = ((Object) (array1)).getClass().getComponentType();
			Class type2 = ((Object) (array2)).getClass().getComponentType();
			if (!type1.isAssignableFrom(type2)){
				throw new IllegalArgumentException("Cannot store "
						+ type2.getName() + " in an array of "
						+ type1.getName());
			}else{
				throw ase;
			}
		}
		return joinedArray;
	}
	
	public static boolean[] addAll(boolean array1[], boolean array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			boolean joinedArray[] = new boolean[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	
	public static char[] addAll(char array1[], char array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			char joinedArray[] = new char[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,
					array2.length);
			return joinedArray;
		}
	}
	
	public static byte[] addAll(byte array1[], byte array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			byte joinedArray[] = new byte[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	
	public static short[] addAll(short array1[], short array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			short joinedArray[] = new short[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	
	public static int[] addAll(int array1[], int array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			int joinedArray[] = new int[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	
	public static long[] addAll(long array1[], long array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			long joinedArray[] = new long[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	
	public static float[] addAll(float array1[], float array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			float joinedArray[] = new float[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	
	public static double[] addAll(double array1[], double array2[]) {

		if (array1 == null){
			return clone(array2);
		}
		if (array2 == null) {
			return clone(array1);
		} else {
			double joinedArray[] = new double[array1.length + array2.length];
			System.arraycopy(array1, 0, joinedArray, 0, array1.length);
			System.arraycopy(array2, 0, joinedArray, array1.length,array2.length);
			return joinedArray;
		}
	}
	/**
	* 描述  : (将某个元素  放入到指定的数组中)
	* 方法名: add
	* 创建人:孙刚   
	* 创建时间:2014-1-22 下午02:37:22
	* @param array
	* @param element
	* @return  
	* @return :Object[]
	 */
	public static Object[] add(Object array[], Object element) {
		Class type;
		if (array != null){
			type = ((Object) (array)).getClass();
		}else if (element != null){
			type = element.getClass();
		}else{
			type = java.lang.Object.class;
		}
		Object newArray[] = (Object[]) (Object[]) copyArrayGrow1(((Object) (array)), type);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	public static boolean[] add(boolean array[], boolean element) {
		boolean newArray[] = (boolean[]) (boolean[]) copyArrayGrow1(array,Boolean.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	public static byte[] add(byte array[], byte element) {
		byte newArray[] = (byte[]) (byte[]) copyArrayGrow1(array, Byte.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}	
	
	public static char[] add(char array[], char element) {
		char newArray[] = (char[]) (char[]) copyArrayGrow1(array,Character.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	public static double[] add(double array[], double element) {
		double newArray[] = (double[]) (double[]) copyArrayGrow1(array,Double.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	public static float[] add(float array[], float element) {
		float newArray[] = (float[]) (float[]) copyArrayGrow1(array, Float.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}	
	
	public static int[] add(int array[], int element) {
		int newArray[] = (int[]) (int[]) copyArrayGrow1(array, Integer.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	public static long[] add(long array[], long element) {
		long newArray[] = (long[]) (long[]) copyArrayGrow1(array, Long.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	public static short[] add(short array[], short element) {
		short newArray[] = (short[]) (short[]) copyArrayGrow1(array, Short.TYPE);
		newArray[newArray.length - 1] = element;
		return newArray;
	}
	
	private static Object copyArrayGrow1(Object array,
			Class newArrayComponentType) {

		if (array != null) {
			int arrayLength = Array.getLength(array);
			Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
			System.arraycopy(array, 0, newArray, 0, arrayLength);
			return newArray;
		} else {
			return Array.newInstance(newArrayComponentType, 1);
		}
	}
	
	public static Object[] add(Object array[], int index, Object element) {
		Class clss = null;
		if (array != null){
			clss = ((Object) (array)).getClass().getComponentType();
		}else if (element != null){
			clss = element.getClass();
		}else{
			return (new Object[] { null });
		}
		return (Object[]) (Object[]) add(((Object) (array)), index, element,clss);
	}
	
	public static boolean[] add(boolean array[], int index, boolean element) {
		return (boolean[]) (boolean[]) add(array, index, BooleanUtils.toBooleanObject(element), Boolean.TYPE);
	}
	
	public static char[] add(char array[], int index, char element) {
		return (char[]) (char[]) add(array, index, new Character(element),Character.TYPE);
	}
	
	public static byte[] add(byte array[], int index, byte element) {
		return (byte[]) (byte[]) add(array, index, new Byte(element), Byte.TYPE);
	}
	
	public static short[] add(short array[], int index, short element) {
		return (short[]) (short[]) add(array, index, new Short(element),Short.TYPE);
	}
	
	public static int[] add(int array[], int index, int element) {
		return (int[]) (int[]) add(array, index, new Integer(element),Integer.TYPE);
	}
	
	public static long[] add(long array[], int index, long element) {
		return (long[]) (long[]) add(array, index, new Long(element), Long.TYPE);
	}
	
	public static float[] add(float array[], int index, float element) {
		return (float[]) (float[]) add(array, index, new Float(element),Float.TYPE);
	}
	
	public static double[] add(double array[], int index, double element) {
		return (double[]) (double[]) add(array, index, new Double(element),Double.TYPE);
	}
	
	private static Object add(Object array, int index, Object element,
			Class clss) {
		if (array == null){
			if (index != 0) {
				throw new IndexOutOfBoundsException("Index: " + index
						+ ", Length: 0");
			} else {
				Object joinedArray = Array.newInstance(clss, 1);
				Array.set(joinedArray, 0, element);
				return joinedArray;
			}
		}
		int length = Array.getLength(array);
		if (index > length || index < 0){
			throw new IndexOutOfBoundsException("Index: " + index
					+ ", Length: " + length);
		}
		Object result = Array.newInstance(clss, length + 1);
		System.arraycopy(array, 0, result, 0, index);
		Array.set(result, index, element);
		if (index < length){
			System.arraycopy(array, index, result, index + 1, length - index);
		}

		return result;
	}
	/**
	* 描述  : (删除一个数组  中指定下标位置的元素)
	* 方法名: remove
	* 创建人:孙刚   
	* 创建时间:2014-1-22 下午02:39:43
	* @param array
	* @param index
	* @return  
	* @return :Object[]
	 */
	public static Object[] remove(Object array[], int index) {
		return (Object[]) (Object[]) remove(((Object) (array)), index);
	}
	/**
	* 描述  : (删除一个数组  中指定的元素)
	* 方法名: removeElement
	* 创建人:孙刚   
	* 创建时间:2014-1-22 下午02:39:50
	* @param array
	* @param element
	* @return  
	* @return :Object[]
	 */
	public static Object[] removeElement(Object array[], Object element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	public static boolean[] remove(boolean array[], int index) {
		return (boolean[]) (boolean[]) remove(array, index);
	}
	
	public static boolean[] removeElement(boolean array[], boolean element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	public static byte[] remove(byte array[], int index) {
		return (byte[]) (byte[]) remove(array, index);
	}
	
	public static byte[] removeElement(byte array[], byte element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	public static char[] remove(char array[], int index) {
		return (char[]) (char[]) remove(array, index);
	}

	public static char[] removeElement(char array[], char element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}

	public static double[] remove(double array[], int index) {
		return (double[]) (double[]) remove(array, index);
	}
	
	public static double[] removeElement(double array[], double element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}

	public static float[] remove(float array[], int index) {
		return (float[]) (float[]) remove(array, index);
	}
	
	
	public static float[] removeElement(float array[], float element) {

		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	public static int[] remove(int array[], int index) {
		return (int[]) (int[]) remove(array, index);
	}
	
	public static int[] removeElement(int array[], int element) {

		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	public static long[] remove(long array[], int index) {
		return (long[]) (long[]) remove(array, index);
	}
	
	public static long[] removeElement(long array[], long element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	public static short[] remove(short array[], int index) {
		return (short[]) (short[]) remove(array, index);
	}	
	
	public static short[] removeElement(short array[], short element) {
		int index = indexOf(array, element);
		if (index == -1){
			return clone(array);
		}else{
			return remove(array, index);
		}
	}
	
	private static Object remove(Object array, int index) {

		int length = getLength(array);
		if (index < 0 || index >= length){
			throw new IndexOutOfBoundsException("Index: " + index
					+ ", Length: " + length);
		}
		Object result = Array.newInstance(array.getClass().getComponentType(),
				length - 1);
		System.arraycopy(array, 0, result, 0, index);
		if (index < length - 1){
			System.arraycopy(array, index + 1, result, index, length - index - 1);
		}
		return result;
	}
}
JS验证工具 js
function winOpen (strURL,strName,width,height)
{
    theWindow = window.open (strURL,strName,"width="+width+" height="+height+" scrollbars=yes left="+(1024-width)/2+" top="+(768-height)/2);	
    if (theWindow.opener == null) theWindow.opener = window;
    if (window.focus) theWindow.focus();
}
//验证邮件
function verifyEmailAddress(strEmail){
  var myReg = /^[_a-zA-Z0-9_-_._-]+@([_a-zA-Z0-9_-]+\.)+[a-zA-Z]{2,3}$/;
  return myReg.test(strEmail);
}
/*****************************************************************
****                     判断是否为日期数据  (lhm)       例子:itIsDate("2009-10-7" , "-")    *****
*****************************************************************/
function itIsDate(DateString , Dilimeter) 
{ 
  if (DateString==null) return false; 
  if (Dilimeter=='' || Dilimeter==null) 
   Dilimeter = '-'; 
  var tempy=''; 
  var tempm=''; 
  var tempd=''; 
  var tempArray; 
  if (DateString.length<8 && DateString.length>10) 
    return false;    
  tempArray = DateString.split(Dilimeter); 
  if (tempArray.length!=3) 
   return false; 
  if (tempArray[0].length==4) 
  { 
   tempy = tempArray[0]; 
   tempd = tempArray[2]; 
  } 
  else 
  { 
   tempy = tempArray[2]; 
   tempd = tempArray[1]; 
  } 
  tempm = tempArray[1]; 
  var tDateString = tempy + '/'+tempm + '/'+tempd+' 8:0:0';//加八小时是因为我们处于东八区 
  var tempDate = new Date(tDateString); 
  if (isNaN(tempDate)) 
   return false; 
 if (((tempDate.getUTCFullYear()).toString()==tempy) && (tempDate.getMonth()==parseInt(tempm)-1) && (tempDate.getDate()==parseInt(tempd))) 
  { 
   return true; 
  } 
  else 
  { 
   return false; 
  } 
} 

/*****************************************************************
****                   求字符串的字节长度     (lhm)          *****
*****************************************************************/
function byteLength(paraString) 
{
 var strValue =new String(paraString);
 var strLength = strValue.length;
 var numLength =0;
  for (globle_i =0 ; globle_i<strLength;globle_i++){
    var ASCIIValue =strValue.charCodeAt(globle_i);
    if ( ASCIIValue > 0 && ASCIIValue < 127 )  
      numLength = numLength + 1 
    else
     numLength = numLength + 2
  }
  return numLength;
}

/*****************************************************************
****                     去除空格     (lhm)                 *****
*****************************************************************/
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
	
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
		
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");}
String.prototype.ltrim = function() {return this.replace(/^\s+/,"");}
String.prototype.rtrim = function() {return this.replace(/\s+$/,"");}
/*****************************************************************
****               复选框的全选与取消     (LHM)              *****
*****************************************************************/
function CheckAll(form){
	var length = form.itemId.length;
	var tocheck = form.chkall.checked;
	if (length)
		for (var i=0; i<length; i++){ 
			if (form.itemId[i].disabled != true){
				form.itemId[i].checked = tocheck;
			} 			
		}
	else {
		if (form.itemId.disabled !=true){
			form.itemId.checked = tocheck;
		}
	}
}

/*****************************************************************
****                     删除处理     (LHM)                  *****
*****************************************************************/
function del_btn (form,strMsg,actionurl){
  	var result = false;
  	var length = form.itemId.length;	
	if (form.itemId.checked) { //只有一条记录时执行此语句
		result = true;	
	}  		
	for (var i=0; i<length; i++){ 
		if (form.itemId[i].checked){
		  result = true;
		  break;
		}		 		
	}
    if (!result){
		alert ("没有选择任何项目!");
		return false;
    }else{
		if (confirm('\n'+strMsg)){
			form.action = actionurl;
			return true;
		}
	    return false;
	} 	
}

/*****************************************************************
****                    转化字符串     (LHM)                 *****
*****************************************************************/
function conversion_code(paraString)
{
	strResult = "";
	j=0;
	for (i=0;i<paraString.length;i++){ 
		Char = String1.charAt(i);
		if (Char=="'"){
		    strResult = strResult + paraString.substring(j,i)+"\\"+"\'";
		    j=i+1;
		 } 
	return strResult;
	}
}

/*****************************************************************
****                 数字输入控制处理     (LHM)              *****
*****************************************************************/
function InputIntNumberCheck(){
	//为支持IE 或 Netscape
	var theEvent=window.event || arguments.callee.caller.arguments[0]; 
	var elm ;
	var ver = navigator.appVersion;
	if (ver.indexOf("MSIE") != -1){  // IE
		if ( !((theEvent.keyCode >=48)&&(theEvent.keyCode<=57))){
			theEvent.keyCode=0;
		}
	}else{ // Netscape
		if ( !((theEvent.which >=48)&&(theEvent.which<=57))){
			theEvent.stopPropagation();
			theEvent.preventDefault();
		}
	}
	//
}

/*****************************************************************
****          有小数点数字输入控制处理     (LHM)             *****
*****************************************************************/
function InputLongNumberCheck(){
	if ( !((window.event.keyCode >=48)&&(window.event.keyCode<=57) || window.event.keyCode ==46)){
		window.event.keyCode=0;
	}

	var theEvent=window.event || arguments.callee.caller.arguments[0]; 
	var elm ;
	var ver = navigator.appVersion;
	if (ver.indexOf("MSIE") != -1){  // IE
		if (!((theEvent.keyCode>=48)&&(theEvent.keyCode<=57) || theEvent.keyCode ==46)){
			theEvent.keyCode=0;
		}
	}else{ // Netscape
		if ( !((theEvent.which >=48)&&(theEvent.which<=57) || theEvent.which ==46)){
			theEvent.stopPropagation();
			theEvent.preventDefault();
		}
	}
}

/*****************************************************************
****                        换页处理                         *****
*****************************************************************/
function toWhichPage(objform, whichPage){
    objform.whichPage.value = whichPage;
    objform.submit();
}

/*************************liuxch   *******************************
****                        获取cookie内容                   *****
*****************************************************************/
function getCookie( name ){
	var nameOfCookie = name + "=";
	var x = 0;
	while ( x <= document.cookie.length ){
		var y = (x+nameOfCookie.length);
		if ( document.cookie.substring( x, y ) == nameOfCookie ) {
			if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
			endOfCookie = document.cookie.length;
			return unescape( document.cookie.substring( y, endOfCookie ) );
		}
		x = document.cookie.indexOf( " ", x ) + 1;	
		if ( x == 0 ) break;
	}
	return "";
}

/*****************************************************************
****                    设置cookie内容、过期时间              *****
*****************************************************************/
function setCookie( name, value, expiredays ) { 
	var todayDate = new Date(); 
	todayDate.setDate( todayDate.getDate() + expiredays ); 
	document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";" 
} 
/*****************************************************************
****                      检查输入字符    (lhm)              *****
'//		 islegality:输入的字符是否为给定的字符
'//返回值:bool
*****************************************************************/
function islegality(checkstrpass){
var checkokpass="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for (i=0; i<checkstrpass.length; i++) {
       ch=checkstrpass.charAt(i);
       for (j=0;j<checkokpass.length; j++){
        if (ch==checkokpass.charAt(j))
        break;
        }
      if (j==checkokpass.length){
	  return false; //函有特别字符时返回false
      break;
        }
  }
   return true;
}
/**
* 检查输入是否中文
*/
function ck_chinese(value_) {
  return escape(value_).indexOf("%u")!=-1 
}
纯JS面向对象表单验证 js
function Formfield(name, label){
	this.name = name;
	this.label = label;
}
function verifyForm(objForm){
	
	tinyMCE.triggerSave();//手动把iframe的值赋给textarea表单元素( 这个是根据自己使用的编辑器来定)
	
	var list  = new Array(
			new Formfield("name", "产品名称"),
			new Formfield("productTypeId", "产品类型"),
			new Formfield("baseprice", "产品底价"),
			new Formfield("marketprice", "产品市场价"),
			new Formfield("sellprice", "产品销售价"),
			new Formfield("description", "产品描述"),
			new Formfield("stylename", "产品图片的样式"),
			new Formfield("imagefile", "产品图片")
	);
	
	for(var i = 0; i < list.length; i++){
		
		var objfield = eval("objForm."+ list[i].name);
		
		if(trim(objfield.value)==""){
			
			alert(list[i].label+ "不能为空");
			
			if(objfield.type!="hidden" && objfield.focus()) objfield.focus();
			return false;
		}
	}
	
	
	var imagefile = objForm.imagefile.value;
	var ext = imagefile.substring(imagefile.length-3).toLowerCase();
	
	if (ext != "jpg" && ext != "gif" && ext != "bmp" && ext != "png"){
		
		alert("只允许上传gif、jpg、bmp、png!");
		
		return false; 
	}
    return true;
}
function SureSubmit(objForm){
	if (verifyForm(objForm)) 
		objForm.submit();
}


 <input type="button" name="Add" value=" 确 认 " class="frm_btn" onClick="javascript:SureSubmit(this.form)">
通过反射验证上传文件格式 java
package cn.itcast.web.formbean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class BaseForm extends ActionForm {
	private static Properties properties = new Properties();
	static{
		try {
			properties.load(BaseForm.class.getClassLoader().getResourceAsStream("arrowuploadfiletype.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 获取当前页 **/
	private int page;
	/** 设置是否进行查找 **/
	private String query;

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}
	public int getPage() {
		return page<1? 1 : page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	/**
	 * 验证上传文件类型是否属于图片格式
	 * @return
	 */
	public static boolean validateImageFileType(FormFile formfile){
		if(formfile!=null && formfile.getFileSize()>0){
			List<String> arrowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");
			List<String> arrowExtension = Arrays.asList("gif","jpg","bmp","png");
			String ext = getExt(formfile);
			return arrowType.contains(formfile.getContentType().toLowerCase()) && arrowExtension.contains(ext);
		}
		return true;
	}
	
	public static String getExt(FormFile formfile){
		return formfile.getFileName().substring(formfile.getFileName().lastIndexOf('.')+1).toLowerCase();
	}
	/**
	 * 验证上传文件是否属于图片/flash动画/word文件/exe文件/pdf文件/TxT文件/xls文件/ppt文件
	 * @param formfile
	 * @return
	 */
	public static boolean validateFileType(FormFile formfile){
		if(formfile!=null && formfile.getFileSize()>0){
			String ext = formfile.getFileName().substring(formfile.getFileName().lastIndexOf('.')+1).toLowerCase();
			List<String> arrowType = new ArrayList<String>();
			for(Object key : properties.keySet()){
				String value = (String)properties.get(key);
				String[] values = value.split(",");
				for(String v : values){
					arrowType.add(v.trim());
				}
			}
			return arrowType.contains(formfile.getContentType().toLowerCase()) && properties.keySet().contains(ext);
		}
		return true;
	}
	
	/**
	 * 保存文件
	 * @param savedir 存放目录
	 * @param fileName 文件名称
	 * @param data 保存的内容
	 * @return 保存的文件
	 * @throws Exception
	 */
	public static File saveFile(File savedir, String fileName, byte[] data) throws Exception{
		if(!savedir.exists()) savedir.mkdirs();//如果目录不存在就创建
		File file = new File(savedir, fileName);
		FileOutputStream fileoutstream = new FileOutputStream(file);
		fileoutstream.write(data);
		fileoutstream.close();
		return file;
	}
	/*
	public boolean validateFileType(String propertyName) throws Exception{
		PropertyDescriptor[] propertydesc = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
		boolean exsit = false;
		for(PropertyDescriptor property : propertydesc){
			if(property.getName().equals(propertyName)){
				exsit = true;
				Method method = property.getReadMethod();
				if(method!=null){
					FormFile formfile = (FormFile) method.invoke(this);
					if(formfile!=null && formfile.getFileSize()>0){
						List<String> arrowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpeg","image/pjpeg");
						return arrowType.contains(formfile.getContentType().toLowerCase());
					}
				}else{
					new RuntimeException(propertyName+"属性的getter方法不存在");
				}
			}
		}
		if(!exsit) new RuntimeException(propertyName+"属性不存在");
		return true;
	}*/
}





gif=image/gif
jpg=image/jpg,image/jpeg,image/pjpeg
bmp=image/bmp
png=image/png
swf=application/x-shockwave-flash
doc=application/msword
txt=text/plain
xls=application/vnd.ms-excel
ppt=application/vnd.ms-powerpoint
pdf=application/pdf
exe=application/octet-stream
巴巴运动网(之 用户批量启用 禁用) java
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/page/share/taglib.jsp" %>
<html>
<head>
<title>注册用户列表</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="/css/vip.css" type="text/css">
<script language="JavaScript">
<!--
	//到指定的分页页面
	function topage(currentPage){
		var form = document.forms[0];
		form.currentPage.value = currentPage;
		form.submit();
	}
	
	function allSelect(){
		var form = document.forms[0];
		var state = form.allselectbox.checked;
		var length = form.ids.length;
		if(length){
			for(var i=0;i<length;i++){
				form.ids[i].checked=state;
			}
		}else{
			form.ids.checked=state;
		}
	}
	function _action(methodName){
		if(selectItem()){
			var form = document.forms[0];
			form.action='/user/userAction!'+methodName+".action";
			form.submit();
		}else{
			alert("请选择要操作的记录");
		}
	}
	function selectItem(){
		var form = document.forms[0];
		var length = form.ids.length;
		if(length){
			for(var i=0;i<length;i++){
				if(form.ids[i].checked) return true;
			}
		}else{
			return form.ids.checked;
		}
		return false;
	}
//-->
</script>
<SCRIPT language=JavaScript src="/js/FoshanRen.js"></SCRIPT>
</head>

<body bgcolor="#FFFFFF" text="#000000" marginwidth="0" marginheight="0">
<form action="/user/userAction!getUserList.action" method="post">
<input type="hidden" name="currentPage" value="">
<!-- 用户条件查询 -->
<input type="hidden" name="query" value="">
<input type="hidden" name="realname" value="">
<input type="hidden" name="buyer.email" value="">
<input type="hidden" name="buyer.username" value="">

  <table width="98%" border="0" cellspacing="1" cellpadding="2" align="center">
    <tr ><td colspan="7" bgcolor="6f8ac4" align="right">
    	<%@ include file="/WEB-INF/page/share/fenye.jsp" %>
   </td></tr>
    <tr>
      <td width="8%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">选择</font></div></td>
      <td width="20%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">用户名</font></div></td>
      <td width="15%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">真实姓名</font></div></td>
	  <td width="10%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">性别</font></div></td>
	  <td width="22%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">电子邮箱</font></div></td>
	  <td width="20%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">注册时间</font></div></td>
	  <td width="7%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">状态</font></div></td>
    </tr>
<!---------------------------LOOP START------------------------------>
<c:forEach items="${pageView.results}" var="entry">
    <tr>
      <td bgcolor="f5f5f5"> <div align="center"><input type="checkbox" name="ids" value="${entry.id}"></div></td>
      <td bgcolor="f5f5f5"> <div align="center">${entry.username}</div></td>
      <td bgcolor="f5f5f5"> <div align="center">${entry.realname }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"> ${entry.gender.name }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"> ${entry.email }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"> ${entry.create_time }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"><c:if test="${entry.visible}">可用</c:if><c:if test="${!entry.visible}">禁用</c:if></div></td>
	</tr>
</c:forEach>
    <!----------------------LOOP END------------------------------->
    <tr>
      <td bgcolor="f5f5f5" colspan="7" align="center"><table width="100%" border="0" cellspacing="1" cellpadding="3">
          <tr> 
            <td width="10%"><input type="checkbox" onclick="javascript:allSelect()" name="allselectbox">全选</td>
              <td width="85%">
<input type="button" value=" 禁 用 " class="frm_btn" onclick="javascript:_action('delete')">  
<input type="button" value=" 启 用 " class="frm_btn" onclick="javascript:_action('enable')">
            </td>
          </tr>
        </table></td>
    </tr>
  </table>
</form>
</body>
</html>





package com.sg.service;

import java.io.Serializable;

import com.sg.base.DAO;
import com.sg.bean.Buyer;


public interface IBuyerService extends DAO<Buyer> {
	
	/**
	 * 批量删除
	 */
	public void delete(Serializable... ids);
	/**
	 * 
	 * @param ids
	 */
	public void enable(Serializable... ids);
}







package com.sg.service.impl;

import java.io.Serializable;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sg.bean.Buyer;
import com.sg.dao.impl.DaoSupport;
import com.sg.service.IBuyerService;
import com.sg.utils.MD5;

@Service
@Transactional
// 事务
public class BuyerServiceImpl extends DaoSupport<Buyer> implements
		IBuyerService {

	
	@Override
	public void delete(Serializable... ids) {
		setVisible(false, ids);
	}

	@Override
	public void enable(Serializable... ids) {
		setVisible(true, ids);
	}

	private void setVisible(boolean visible, Serializable... ids) {
		if (ids != null && ids.length > 0) {
			StringBuffer jpql = new StringBuffer();
			for (int i = 0; i < ids.length; i++) {
				jpql.append('?').append(i + 2).append(',');
			}
			jpql.deleteCharAt(jpql.length() - 1);
			String sqlString = "update Buyer b set b.visible=?1 where b.id in("
					+ jpql.toString() + ")";
			Query query = manager.createQuery(sqlString);
			query.setParameter(1, visible);
			for (int i = 0; i < ids.length; i++) {
				query.setParameter(i + 2, ids[i]);
			}
			query.executeUpdate();
		}
	}
}



package com.sg.action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.sg.base.BaseAction;
import com.sg.bean.Buyer;
import com.sg.service.IBuyerService;
import com.sg.utils.Pager;
import com.sg.utils.PagerView;
import com.sg.utils.StrutsUtils;

public class BuyerAction extends BaseAction {

	@Resource
	private IBuyerService buyerService;

	private Buyer buyer;
	
	private Integer[] ids;

	
	/**
	 * 禁用用户
	 * @return
	 */
	public String delete(){
		//因为String 已经是被序列化之后的  
		buyerService.delete((Serializable[])ids);
		StrutsUtils.getRequest().setAttribute("message", "禁用帐号成功");
		StrutsUtils.getRequest().setAttribute("urladdress", "/user/userAction!getUserList.action");
		return "message";
	}
	/**
	 * 开启用户
	 * @return
	 */
	public String enable(){
		//因为String 已经是被序列化之后的  
		buyerService.enable((Serializable[])ids);
		StrutsUtils.getRequest().setAttribute("message", "禁用开启成功");
		StrutsUtils.getRequest().setAttribute("urladdress", "/user/userAction!getUserList.action");
		return "message";
	}

	public Buyer getBuyer() {
		return buyer;
	}

	public void setBuyer(Buyer buyer) {
		this.buyer = buyer;
	}

	public Integer[] getIds() {
		return ids;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	
}


仿百度的分页查询方式(接 JPA通用DAO设计(分页)示例) java
当前页:第1页 | 总记录数:101条 | 每页显示:5条 | 总页数:21页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 下一页 尾页 >


package com.sg.utils;

import java.util.List;
/**
 * 分页查询
 * @author Administrator
 *
 * @param <T>
 */
public class Pager<T> {
	/**
	 * 记录集
	 */
	private List<T> resultList;
	/**
	 * 总记录数
	 */
	private long resultTotal;
	
	
	public List<T> getResultList() {
		return resultList;
	}
	public void setResultList(List<T> resultList) {
		this.resultList = resultList;
	}
	public long getResultTotal() {
		return resultTotal;
	}
	public void setResultTotal(long resultTotal) {
		this.resultTotal = resultTotal;
	}
}







package com.sg.utils;

import java.util.List;

public class PagerView<T> {
	/** 分页数据 **/
	private List<T> results;
	/** 页码开始索引和结束索引 **/
	private PagerIndex pagerIndex;
	/** 总页数 **/
	private long totalPage = 1;
	/** 每页显示记录数 **/
	private int maxResult;
	/** 当前页 **/
	private int currentPage;
	/** 总记录数 **/
	private long totalRecord;
	/** 页码数量 **/
	private int pageCode = 10;

	/** 要获取记录的开始索引 **/
	public int getFirstResult() {
		return (this.currentPage - 1) * this.maxResult;
	}

	public int getPageCode() {
		return pageCode;
	}

	public void setPageCode(int pageCode) {
		this.pageCode = pageCode;
	}

	public PagerView(int maxResult, int currentPage) {
		this.maxResult = maxResult;
		this.currentPage = currentPage;
	}

	public void setQueryResult(Pager<T> pager) {
		if (null != pager) {
			setResults(pager.getResultList());
			setTotalRecord(pager.getResultTotal());
		}
		
	}

	public long getTotalRecord() {
		return totalRecord;
	}

	public void setTotalRecord(long totalRecord) {
		this.totalRecord = totalRecord;
		setTotalPage(this.totalRecord % this.maxResult == 0 ? this.totalRecord
				/ this.maxResult : this.totalRecord / this.maxResult + 1);
	}

	public List<T> getResults() {
		return results;
	}

	public void setResults(List<T> results) {
		this.results = results;
	}

	
	public PagerIndex getPagerIndex() {
		return pagerIndex;
	}

	public void setPagerIndex(PagerIndex pagerIndex) {
		this.pagerIndex = pagerIndex;
	}

	public void setMaxResult(int maxResult) {
		this.maxResult = maxResult;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public long getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(long totalPage) {
		this.totalPage = totalPage;
		this.pagerIndex = PagerIndex.getPageIndex(pageCode, currentPage,
				totalPage);
	}

	public int getMaxResult() {
		return maxResult;
	}

	public int getCurrentPage() {
		return currentPage;
	}
}





package com.sg.utils;

public class PagerIndex {
	private long startIndex;
	private long endIndex;

	public PagerIndex(long startIndex, long endIndex) {
		this.startIndex = startIndex;
		this.endIndex = endIndex;
	}

	public static PagerIndex getPageIndex(long viewpagecount, int currentPage,
			long totalpage) {
		long startpage = currentPage
				- (viewpagecount % 2 == 0 ? viewpagecount / 2 - 1
						: viewpagecount / 2);
		long endpage = currentPage + viewpagecount / 2;
		if (startpage < 1) {
			startpage = 1;
			if (totalpage >= viewpagecount)
				endpage = viewpagecount;
			else
				endpage = totalpage;
		}
		if (endpage > totalpage) {
			endpage = totalpage;
			if ((endpage - viewpagecount) > 0)
				startpage = endpage - viewpagecount + 1;
			else
				startpage = 1;
		}
		return new PagerIndex(startpage, endpage);
	}

	public long getStartIndex() {
		return startIndex;
	}

	public void setStartIndex(long startIndex) {
		this.startIndex = startIndex;
	}

	public long getEndIndex() {
		return endIndex;
	}

	public void setEndIndex(long endIndex) {
		this.endIndex = endIndex;
	}

}



使用示例:


package com.sg.base;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {
	/**
	 * 当前页
	 */
	private int currentPage = 1;
	/**
	 * 每页显示数量
	 */
	private int maxResult = 5;
	/**
	 * 判断是否是条件查询
	 */
	private String query;
	

	public int getMaxResult() {
		return maxResult;
	}

	public void setMaxResult(int maxResult) {
		this.maxResult = maxResult;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}
}




/**
	 * 获取用户列表
	 * 
	 * @return
	 */
	public String getUserList() {
		HttpServletRequest request = StrutsUtils.getRequest();
		int currentPage = super.getCurrentPage();
		currentPage = -1 == currentPage || 0 == currentPage ? 1 : currentPage;
		PagerView<Buyer> pagerView = new PagerView<Buyer>(super.getMaxResult(),
				currentPage);
		LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
		orderBy.put("create_time", "desc");
		//判断是否是条件查询
		
		Pager<Buyer> pager = buyerService.getResultForPager(
				pagerView.getFirstResult(), pagerView.getMaxResult(), orderBy);
		pagerView.setQueryResult(pager);
		request.setAttribute("pageView", pagerView);
		return "userList";
}






jsp  展示:

<body bgcolor="#FFFFFF" text="#000000" marginwidth="0" marginheight="0">
<form action="/user/userAction!getUserList.action" method="post">
<input type="hidden" name="currentPage" value="">
<html:hidden property="query"/>
<html:hidden property="realname"/>
<html:hidden property="email"/>
<html:hidden property="username"/>
<input name="method" type="hidden">
  <table width="98%" border="0" cellspacing="1" cellpadding="2" align="center">
    <tr ><td colspan="7" bgcolor="6f8ac4" align="right">
    	<%@ include file="/WEB-INF/page/share/fenye.jsp" %>
   </td></tr>
    <tr>
      <td width="8%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">选择</font></div></td>
      <td width="20%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">用户名</font></div></td>
      <td width="15%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">真实姓名</font></div></td>
	  <td width="10%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">性别</font></div></td>
	  <td width="22%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">电子邮箱</font></div></td>
	  <td width="20%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">注册时间</font></div></td>
	  <td width="7%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">状态</font></div></td>
    </tr>
<!---------------------------LOOP START------------------------------>
<c:forEach items="${pageView.results}" var="entry">
    <tr>
      <td bgcolor="f5f5f5"> <div align="center"><input type="checkbox" name="usernames" value="${entry.username}"></div></td>
      <td bgcolor="f5f5f5"> <div align="center">${entry.username}</div></td>
      <td bgcolor="f5f5f5"> <div align="center">${entry.realname }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"> ${entry.gender.name }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"> ${entry.email }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"> ${entry.create_time }</div></td>
	  <td bgcolor="f5f5f5"> <div align="center"><c:if test="${entry.visible}">可用</c:if><c:if test="${!entry.visible}">禁用</c:if></div></td>
	</tr>
</c:forEach>
    <!----------------------LOOP END------------------------------->
    <tr>
      <td bgcolor="f5f5f5" colspan="7" align="center"><table width="100%" border="0" cellspacing="1" cellpadding="3">
          <tr> 
            <td width="10%"><input type="checkbox" onclick="javascript:allSelect()" name="allselectbox">全选</td>
              <td width="85%">
<input type="button" value=" 禁 用 " class="frm_btn" onclick="javascript:_action('delete')">  
<input type="button" value=" 启 用 " class="frm_btn" onclick="javascript:_action('enable')">
            </td>
          </tr>
        </table></td>
    </tr>
  </table>
</form>
</body>



分页jsp显示:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/page/share/taglib.jsp" %>
<font color="#FFFFFF"> 
	当前页:第${pageView.currentPage}页 |
	总记录数:${pageView.totalRecord}条 | 
	每页显示:${pageView.maxResult}条 |
	总页数:${pageView.totalPage}页
</font>

<c:if test="${pageView.currentPage > 1 }">
		<a href="javascript:topage('1')">< 首页</a>
		<a href="javascript:topage('${ pageView.currentPage - 1}')">上一页</a>
</c:if>
<c:forEach begin="${pageView.pagerIndex.startIndex}" end="${pageView.pagerIndex.endIndex}" var="wp">
	
	
	<c:if test="${pageView.currentPage==wp}">
		<b><font color="#FFFFFF">[${wp}]</font> </b>
	</c:if>
	
	
	<c:if test="${pageView.currentPage!=wp}">
		<a href="javascript:topage('${wp}')" class="a03">[${wp}]</a>
	</c:if>
	
</c:forEach>
<c:if test="${pageView.currentPage < pageView.totalPage }">
	<a href="javascript:topage('${ pageView.currentPage + 1}')">下一页</a>
	<a href="javascript:topage('${pageView.totalPage }')">尾页 ></a>
</c:if>
纯JS Ajax提交 js
function send_request(callback, urladdress, isReturnData){      
        var xmlhttp = getXMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            	if (xmlhttp.readyState == 4) {//readystate 为4即数据传输结束
 				    try{
				    	if(xmlhttp.status == 200){
							if(isReturnData && isReturnData==true){
								callback(xmlhttp.responseText);
							}
						}else{
							callback("抱歉,没找到此页面:"+ urladdress +"");
						}
			        } catch(e){
			        	callback("抱歉,发送请求失败,请重试 " + e);
			        }
			   }
        };
        //get代表提交方式
        //true代表是异步请求
        xmlhttp.open("GET", urladdress, true);
        xmlhttp.send(null);
}




function getXMLHttpRequest() {
        var xmlhttp = null;
		if (window.XMLHttpRequest) {
			try {
				xmlhttp = new XMLHttpRequest();
				xmlhttp.overrideMimeType("text/html;charset=UTF-8");//设定以UTF-8编码识别数据
			} catch (e) {}
		} else if (window.ActiveXObject) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				try {
					xmlhttp = new ActiveXObject("Msxml2.XMLHttp");
				} catch (e) {
					try {
						xmlhttp = new ActiveXObject("Msxml3.XMLHttp");
					} catch (e) {}
				}
			}
		}
        return xmlhttp;
}



实例:

function checkUsername(){
		var form = document.forms[0];
		var username = form.username.value;
		var viewobj = document.getElementById("checkResult");
		viewobj.innerHTML = "正在检测中...";
                //true是否接收返回数据
		send_request(function(value){viewobj.innerHTML=value},
		'<html:rewrite action="/user/reg"/>?method=isUserExsit&username='+ username, true);
}
JPA通用DAO设计(分页)示例 java
package com.sg.base;

import java.io.Serializable;
import java.util.LinkedHashMap;

import com.sg.utils.Pager;


/**
 * 实体操作通用接口
 * 
 * @author Administrator
 * 
 * @param <T>
 */
public interface DAO<T> {
	/**
	 * 保存实体
	 * 
	 * @param entity
	 */
	void save(T entity);

	/**
	 * 更新实体
	 * 
	 * @param entity
	 */
	void update(T entity);

	/**
	 * 删除实体
	 * 
	 * @param id
	 */
	void delete(Serializable id);

	/**
	 * 查找实体
	 * 
	 * @param id
	 * @return
	 */
	T find(Serializable id);
	/**
	 * 查找实体
	 * @param username
	 * @return
	 */
	T find(String username);

	/**
	 * 获取总记录数
	 * 
	 * @return
	 */
	long getCount();
	
	/**
	 * 分页查询
	 * @param firstResult当前页 
	 * @param maxResult每页显示多少条
	 * @param where 是否有where条件(格式 )name = ?1 无需在家 where关键字
	 * @param params 参数 new Object[]{"张三"}
	 * @param orderBy 排序 格式 key为 xxx value为desc/asc  map.put("create_date","desc")
	 * @return
	 */
	Pager<T> getResultForPager(int firstResult,int maxResult,String where,Object[] params,LinkedHashMap<String, String> orderBy);
	/**
	 * 分页查询
	 * @param firstResult 当前页
	 * @param maxResult 每页显示多少条
	 * @param where 是否有where条件
	 * @param params参数
	 * @return
	 */
	Pager<T> getResultForPager(int firstResult,int maxResult,String where,Object[] params);
	/**
	 *  分页查询
	 * @param firstResult
	 * @param maxResult
	 * @param orderBy
	 * @return
	 */
	Pager<T> getResultForPager(int firstResult,int maxResult,LinkedHashMap<String, String> orderBy);
	/**
	 *  分页查询
	 * @param firstResult
	 * @param maxResult
	 * @return
	 */
	Pager<T> getResultForPager(int firstResult,int maxResult);
}







package com.sg.dao.impl;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.sg.base.DAO;
import com.sg.utils.Pager;

public abstract class DaoSupport<T> implements DAO<T> {

	@PersistenceContext
	protected EntityManager manager;
	/**
	 * 实体类
	 */
	protected Class<T> entityClass = getEntityClass();

	/**
	 * 得到运行时类第一个泛型实体对象Class
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Class<T> getEntityClass() {
		// 获取父类泛型类
		Type type = getClass().getGenericSuperclass();
		// 判断是否是一个泛型类
		if (type instanceof ParameterizedType) {
			// 转换成泛型类
			ParameterizedType pType = (ParameterizedType) type;
			// 得到所有泛型类型
			// Type[] types = pType.getActualTypeArguments();

			// 得到第一个泛型Class对象
			return (Class<T>) pType.getActualTypeArguments()[0];
		}
		return null;
	}

	@Override
	public void save(T entity) {
		manager.persist(entity);
	}

	@Override
	public void update(T entity) {
		manager.merge(entity);
	}

	@Override
	public void delete(Serializable id) {
		manager.remove(manager.getReference(entityClass, id));
	}

	@Override
	public T find(Serializable id) {
		return manager.find(entityClass, id);
	}

	@Override
	public T find(String username) {
		String sqlString = "select o from " + this.getEntityName(entityClass) + " o where o.username = ?1";
		Query query = manager.createQuery(sqlString);
		query.setParameter(1, username);
		return (T) query.getSingleResult();
	}

	@Override
	public long getCount() {
		String sqlString = "select count(o) from " + this.getEntityName(this.entityClass)+ " o";
		Long count = (Long) manager.createQuery(sqlString).getSingleResult();
		return count;
	}

	/**
	 * 得到运行时类泛型实体名字
	 * 
	 * @return
	 */
	public <E> String getEntityName(Class<E> entityClass) {
		String entityName = this.entityClass.getSimpleName();
		Entity entity = this.entityClass.getAnnotation(Entity.class);
		// 判断
		if (null != entity.name() && !"".equals(entity.name())) {
			entityName = entity.name();
		}
		return entityName;
	}

	@Override
	public Pager<T> getResultForPager(int firstResult, int maxResult) {
		return getResultForPager(firstResult, maxResult, null, null, null);
	}

	@Override
	public Pager<T> getResultForPager(int firstResult, int maxResult,
			LinkedHashMap<String, String> orderBy) {
		return getResultForPager(firstResult, maxResult, null, null, orderBy);
	}

	@Override
	public Pager<T> getResultForPager(int firstResult, int maxResult,
			String where, Object[] params) {
		return getResultForPager(firstResult, maxResult, where, params, null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<T> getResultForPager(int firstResult, int maxResult,
			String where, Object[] params, LinkedHashMap<String, String> orderBy) {
		
		String sqlString = "";

		Pager pager = new Pager<T>();
		
		
		String entityname = getEntityName(this.entityClass);
		where = where == null || "".equals(where.trim()) ? "" : "where "+ where;
		sqlString = "select o from "+ entityname + " o " + where + buildOrderBy(orderBy);
		Query query = manager.createQuery(sqlString);
		setQueryParams(query, params);
		if (firstResult != -1 && maxResult != -1){
			query.setFirstResult(firstResult).setMaxResults(maxResult);
		}
		//设置查询结果集
		pager.setResultList(query.getResultList());
		
		sqlString = "select count("+ getCountField(this.entityClass) + ") from " + entityname+ " o " + where;
		query = manager.createQuery(sqlString);
		setQueryParams(query, params);
		//设置查询总数
		pager.setResultTotal((Long) query.getSingleResult());
		return pager;
	}

	/**
	 * 设置查询参数
	 * 
	 * @param query
	 * @param params
	 */
	private static void setQueryParams(Query query, Object[] params){
		if(params!=null && params.length>0){
			for(int i=0; i<params.length; i++){
				query.setParameter(i+1, params[i]);
			}
		}
	}

	/**
	 * 构建排序语句
	 * 
	 * @param orderBy
	 *            {xxx desc,xxx,asc} 排序属性 key为属性 value为asc/desc
	 * @return
	 */
	private static String buildOrderBy(LinkedHashMap<String, String> orderBy) {
		StringBuffer buffer = new StringBuffer();
		if (null != orderBy && !orderBy.isEmpty()) {
			buffer.append(" order by ");
			for (Map.Entry<String, String> entry : orderBy.entrySet()) {
				buffer.append(" o.").append(entry.getKey()).append(" ")
						.append(entry.getValue()).append(",");
			}
			// 删除最后一个 ,
			buffer.deleteCharAt(buffer.length() - 1);
		}
		return buffer.toString();
	}

	/**
	 * 获取统计属性,该方法是为了解决hibernate解析联合主键select count(o) from Xxx
	 * o语句BUG而增加,hibernate对此jpql解析后的sql为select
	 * count(field1,field2,...),显示使用count()统计多个字段是错误的
	 * 
	 * @param <E>
	 * @param clazz
	 * @return
	 */
	private static <E> String getCountField(Class<E> clazz) {
		String out = "o";
		try {
			PropertyDescriptor[] propertyDescriptors = Introspector
					.getBeanInfo(clazz).getPropertyDescriptors();
			for (PropertyDescriptor propertydesc : propertyDescriptors) {
				Method method = propertydesc.getReadMethod();
				if (method != null
						&& method.isAnnotationPresent(EmbeddedId.class)) {
					PropertyDescriptor[] ps = Introspector.getBeanInfo(
							propertydesc.getPropertyType())
							.getPropertyDescriptors();
					out = "o."
							+ propertydesc.getName()
							+ "."
							+ (!ps[1].getName().equals("class") ? ps[1]
									.getName() : ps[0].getName());
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out;
	}
}










package com.sg.base;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {
	/**
	 * 当前页
	 */
	private int currentPage = 1;
	/**
	 * 每页显示数量
	 */
	private int maxResult = 15;
	/**
	 * 判断是否是条件查询
	 */
	private String query;
	

	public int getMaxResult() {
		return maxResult;
	}

	public void setMaxResult(int maxResult) {
		this.maxResult = maxResult;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}
}




package com.sg.bean;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


/**
 * 用户实体
 * 
 * @author
 * 
 */
@Entity
public class Buyer implements Serializable {
	/**
	 * 主键ID
	 */
	private int id;
	/**
	 * 用户名
	 */
	private String username;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 真实姓名
	 */
	private String realname;
	/**
	 * 邮箱
	 */
	private String email;
	/**
	 * 性别 
	 */
	private Gender gender = Gender.MAN;
	/**
	 * 用户联系信息
	 */
	private ContactInfo contactInfo;
	/**
	 * 是否启用 默认 可用
	 */
	private boolean visible = true;
	/**
	 * 创建时间
	 */
	private Date create_time = new Date();

	@Id
	@GeneratedValue
	@Column(length = 20)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Column(length = 100, nullable = false)
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Column(length = 100, nullable = false)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Column(length = 50)
	public String getRealname() {
		return realname;
	}

	public void setRealname(String realname) {
		this.realname = realname;
	}

	@Column(length = 100, nullable = false)
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Enumerated(EnumType.STRING)
	@Column(length = 5, nullable = false)
	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}


	@OneToOne(cascade = CascadeType.ALL)
	//外键名称
	@JoinColumn(name="contant_id")
	public ContactInfo getContactInfo() {
		return contactInfo;
	}

	public void setContactInfo(ContactInfo contactInfo) {
		this.contactInfo = contactInfo;
	}

	@Column(length = 10, nullable = false)
	public boolean isVisible() {
		return visible;
	}

	public void setVisible(boolean visible) {
		this.visible = visible;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable = false)
	public Date getCreate_time() {
		return create_time;
	}

	public void setCreate_time(Date create_time) {
		this.create_time = create_time;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((username == null) ? 0 : username.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Buyer other = (Buyer) obj;
		if (username == null) {
			if (other.username != null)
				return false;
		} else if (!username.equals(other.username))
			return false;
		return true;
	}
}



package com.sg.service;

import com.sg.base.DAO;
import com.sg.bean.Buyer;


public interface IBuyerService extends DAO<Buyer> {

	/**
	 * 验证用户名是否存在
	 * 
	 * @param username
	 * @return
	 */
	boolean exsit(String username);
	/**
	 * 登录验证
	 * @param username
	 * @param password
	 * @return
	 */
	boolean validate(String username,String password);
}



package com.sg.service.impl;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sg.bean.Buyer;
import com.sg.dao.impl.DaoSupport;
import com.sg.service.IBuyerService;
import com.sg.utils.MD5;


@Service
@Transactional
// 事务
public class BuyerServiceImpl extends DaoSupport<Buyer> implements
		IBuyerService {

	@Override
	public boolean exsit(String username) {
		Query query = manager
				.createQuery("select count(o) from Buyer o where o.username = ?1");
		// 设置参数
		query.setParameter(1, username);

		long count = (Long) query.getSingleResult();
		return count > 0;
	}

	@Override
	public void save(Buyer entity) {
		entity.setPassword(MD5.MD5Encode(entity.getPassword()));
		super.save(entity);
	}

	@Override
	public boolean validate(String username, String password) {
		Query query = manager
				.createQuery("select count(o) from Buyer o where o.username = ?1 and o.password = ?2");
		long result = (Long) query.setParameter(1, username)
				.setParameter(2, MD5.MD5Encode(password)).getSingleResult();
		return result > 0;
	}
}



package com.sg.action;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.sg.base.BaseAction;
import com.sg.bean.Buyer;
import com.sg.service.IBuyerService;
import com.sg.utils.Pager;
import com.sg.utils.PagerView;
import com.sg.utils.StrutsUtils;

public class BuyerAction extends BaseAction {

	@Resource
	private IBuyerService buyerService;

	private Buyer buyer;

	/**
	 * 跳转注册页面
	 * 
	 */
	public String regUI() {
		return "regUI";
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	public String reg() {
		HttpServletRequest request = StrutsUtils.getRequest();
		if (buyerService.exsit(buyer.getUsername().trim())) {
			request.setAttribute("error", "该用户已经存在!");
			return "regUI";
		} else {
			buyerService.save(buyer);
			request.setAttribute("message", "用户注册成功!");
			request.setAttribute("urladdress", "/");
		}

		return "message";
	}

	/**
	 * 验证用户名是否已经存在
	 * 
	 * @throws Exception
	 * @return
	 */
	public String isUserExsit() throws Exception {
		HttpServletRequest request = StrutsUtils.getRequest();
		request.setAttribute("exsit",
				buyerService.exsit(buyer.getUsername().trim()));
		return "checkResult";
	}

	/**
	 * 登陆跳转
	 * 
	 * @return
	 */
	public String loginSkip() {
		return "loginSkip";
	}

	/**
	 * 登陆
	 * 
	 * @return
	 */
	public String login() {
		HttpServletRequest request = StrutsUtils.getRequest();
		if (null != buyer.getUsername() && !"".equals(buyer.getUsername())
				&& null != buyer.getPassword()
				&& !"".equals(buyer.getPassword())) {
			// 验证登陆信息是否正确
			if (buyerService.validate(buyer.getUsername(), buyer.getPassword())) {
				request.getSession().setAttribute("user",
						buyerService.find(buyer.getUsername()));
				request.setAttribute("message", "用戶登陆成功!");
				request.setAttribute("urladdress", "/");
				return "message";
			} else {
				request.setAttribute("message", "用戶名或密码不正确!");
				return "loginSkip";
			}
		}
		return null;
	}

	/**
	 * 获取用户列表
	 * 
	 * @return
	 */
	public String getUserList() {
		HttpServletRequest request = StrutsUtils.getRequest();
		int currentPage = super.getCurrentPage();
		currentPage = -1 == currentPage || 0 == currentPage ? 1 : currentPage;
		PagerView<Buyer> pagerView = new PagerView<Buyer>(super.getMaxResult(),
				currentPage);
		LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
		orderBy.put("create_time", "desc");
		Pager<Buyer> pager = null;
		// 判断是否是条件查询
		if ("true".equals(super.getQuery())) {
			StringBuffer buffer = new StringBuffer();
			List<Object> params = new ArrayList<Object>();
			if (null != buyer.getUsername() && !"".equals(buyer.getUsername())) {
				params.add("%" + buyer.getUsername() + "%");
				buffer.append(" username like ?").append(params.size());
			}
			if (null != buyer.getRealname() && !"".equals(buyer.getRealname())) {
				if (!params.isEmpty()) {
					buffer.append(" and ");
				}
				params.add("%" + buyer.getRealname() + "%");
				buffer.append(" realname like ?").append(params.size());
			}
			if (null != buyer.getEmail() && !"".equals(buyer.getEmail())) {
				if (!params.isEmpty()) {
					buffer.append(" and ");
				}
				params.add("%" + buyer.getEmail() + "%");
				buffer.append(" email like ?").append(params.size());
			}
			
			pager = buyerService.getResultForPager(pagerView.getFirstResult(),
					pagerView.getMaxResult(), buffer.toString(),
					params.toArray(), orderBy);

		} else {
			pager = buyerService.getResultForPager(pagerView.getFirstResult(),
					pagerView.getMaxResult(), orderBy);
		}

		pagerView.setQueryResult(pager);
		request.setAttribute("pageView", pagerView);
		return "userList";
	}

	/**
	 * 用户查询跳转
	 * 
	 * @return
	 */
	public String querySkip() {
		return "querySkip";
	}

	public Buyer getBuyer() {
		return buyer;
	}

	public void setBuyer(Buyer buyer) {
		this.buyer = buyer;
	}
}



GenericsUtils java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
 * 泛型工具类
 
 */
public class GenericsUtils {
	/**  
     * 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>  
     *  
     * @param clazz clazz 需要反射的类,该类必须继承范型父类
     * @param index 泛型参数所在索引,从0开始.  
     * @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */  
    @SuppressWarnings("unchecked")
	public static Class getSuperClassGenricType(Class clazz, int index) {    
        Type genType = clazz.getGenericSuperclass();//得到泛型父类  
        //如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class   
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;   
        }  
        //返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型   
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();                   
        if (index >= params.length || index < 0) { 
        	 throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
        }      
        if (!(params[index] instanceof Class)) {
            return Object.class;   
        }   
        return (Class) params[index];
    }
	/**  
     * 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>  
     *  
     * @param clazz clazz 需要反射的类,该类必须继承泛型父类
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */  
    @SuppressWarnings("unchecked")
	public static Class getSuperClassGenricType(Class clazz) {
    	return getSuperClassGenricType(clazz,0);
    }
	/**  
     * 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
     *  
     * @param Method method 方法
     * @param int index 泛型参数所在索引,从0开始.
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */ 
    @SuppressWarnings("unchecked")
	public static Class getMethodGenericReturnType(Method method, int index) {
    	Type returnType = method.getGenericReturnType();
    	if(returnType instanceof ParameterizedType){
    	    ParameterizedType type = (ParameterizedType) returnType;
    	    Type[] typeArguments = type.getActualTypeArguments();
            if (index >= typeArguments.length || index < 0) { 
            	 throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
            } 
    	    return (Class)typeArguments[index];
    	}
    	return Object.class;
    }
	/**  
     * 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
     *  
     * @param Method method 方法
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */ 
    @SuppressWarnings("unchecked")
	public static Class getMethodGenericReturnType(Method method) {
    	return getMethodGenericReturnType(method, 0);
    }
    
	/**  
     * 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
     *  
     * @param Method method 方法
     * @param int index 第几个输入参数
     * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
     */ 
    @SuppressWarnings("unchecked")
	public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
    	List<Class> results = new ArrayList<Class>();
    	Type[] genericParameterTypes = method.getGenericParameterTypes();
    	if (index >= genericParameterTypes.length ||index < 0) {
             throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
        } 
    	Type genericParameterType = genericParameterTypes[index];
    	if(genericParameterType instanceof ParameterizedType){
    	     ParameterizedType aType = (ParameterizedType) genericParameterType;
    	     Type[] parameterArgTypes = aType.getActualTypeArguments();
    	     for(Type parameterArgType : parameterArgTypes){
    	         Class parameterArgClass = (Class) parameterArgType;
    	         results.add(parameterArgClass);
    	     }
    	     return results;
    	}
    	return results;
    }
	/**  
     * 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
     *  
     * @param Method method 方法
     * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
     */ 
    @SuppressWarnings("unchecked")
	public static List<Class> getMethodGenericParameterTypes(Method method) {
    	return getMethodGenericParameterTypes(method, 0);
    }
	/**  
     * 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
     *  
     * @param Field field 字段
     * @param int index 泛型参数所在索引,从0开始.
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */ 
    @SuppressWarnings("unchecked")
	public static Class getFieldGenericType(Field field, int index) {
    	Type genericFieldType = field.getGenericType();
    	
    	if(genericFieldType instanceof ParameterizedType){
    	    ParameterizedType aType = (ParameterizedType) genericFieldType;
    	    Type[] fieldArgTypes = aType.getActualTypeArguments();
    	    if (index >= fieldArgTypes.length || index < 0) { 
    	    	throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
            } 
    	    return (Class)fieldArgTypes[index];
    	}
    	return Object.class;
    }
	/**  
     * 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
     *  
     * @param Field field 字段
     * @param int index 泛型参数所在索引,从0开始.
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */ 
    @SuppressWarnings("unchecked")
	public static Class getFieldGenericType(Field field) {
    	return getFieldGenericType(field, 0);
    }
}
SSH通用Dao设计 java
package com.erp.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;


public interface PublicDao<T>
{
	/**
	 * @return  
	* @Title: save 
	* @Description: TODO:保存一个对象
	* @param @param o
	* @param @return    设定文件 
	* @return Serializable    返回类型 
	* @throws 
	*/
	public Serializable save(T o);

	/** 
	* @Title: delete 
	* @Description: TODO:删除一个对象
	* @param @param o    设定文件 
	* @return void    返回类型 
	* @throws 
	*/
	public void delete(T o);

	/** 
	* @Title: update 
	* @Description: TODO:更新一个对象
	* @param @param o    设定文件 
	* @return void    返回类型 
	* @throws 
	*/
	public void update(T o);

	/** 
	* @Title: saveOrUpdate 
	* @Description: TODO:保存或更新对象
	* @param @param o    设定文件 
	* @return void    返回类型 
	* @throws 
	*/
	public void saveOrUpdate(T o);

	/** 
	* @Title: find 
	* @Description: TODO:查询
	* @param @param hql
	* @param @return    设定文件 
	* @return List<T>    返回类型 
	* @throws 
	*/
	public List<T> find(String hql);

	/** 
	* @Title: get 
	* @Description: TODO:获得一个对象
	* @param @param c
	* @param @param id
	* @param @return    设定文件 
	* @return T    返回类型 
	* @throws 
	*/
	public T get(Class<T> c, Serializable id);

	/** 
	* @Title: count 
	* @Description: TODO:select count(*) from 类
	* @param @param hql
	* @param @return    设定文件 
	* @return Long    返回类型 
	* @throws 
	*/
	public Long count(String hql);

	/** 
	* @Title: executeHql 
	* @Description: TODO:执行HQL语句
	* @param @param hql
	* @param @return    设定文件 响应数目
	* @return Integer    返回类型 
	* @throws 
	*/
	public Integer executeHql(String hql);

	/** 
	* @Title: find 
	* @Description: TODO:查询集合
	* @param @param hql
	* @param @param params
	* @param @return    设定文件 
	* @return List<T>    返回类型 
	* @throws 
	*/
	List<T> find(String hql, Map<String, Object> params);

	/** 
	* @Title: find 
	* @Description: TODO:查询分页集合
	* @param @param hql
	* @param @param params
	* @param @param page
	* @param @param rows
	* @param @return    设定文件 
	* @return List<T>    返回类型 
	* @throws 
	*/
	List<T> find(String hql, Map<String, Object> params, Integer page,
			Integer rows);

	/** 
	* @Title: get 
	* @Description: TODO:根据参数查询实体类
	* @param @param hql
	* @param @param param
	* @param @return    设定文件 
	* @return T    返回类型 
	* @throws 
	*/
	T get(String hql, Map<String, Object> param);

	/** 
	* @Title: count 
	* @Description: TODO:根据参数查询集合条数
	* @param @param hql
	* @param @param params
	* @param @return    设定文件 
	* @return Long    返回类型 
	* @throws 
	*/
	Long count(String hql, Map<String, Object> params);

	/** 
	* @Title: executeHql 
	* @Description: TODO:批量执行HQL (更新) 响应数目
	* @param @param hql
	* @param @param params
	* @param @return    设定文件 
	* @return Integer    返回类型 
	* @throws 
	*/
	Integer executeHql(String hql, Map<String, Object> params);

	@SuppressWarnings("rawtypes")
	List findBySQL(String sql );

	void deleteToUpdate(T o );

}




package com.erp.daoImpl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.erp.dao.PublicDao;
import com.erp.util.Constants;

@SuppressWarnings("unchecked")
@Repository("publicDao")
public class PublicDaoImpl<T> implements PublicDao<T> {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	//注册监听器
	/*@PostConstruct
	public void registerListeners() {
	    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
	    registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(new PostInsert());
	    registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(new PostUpdate());
	}*/

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public Serializable save(T o) {
		Serializable serializable = this.getCurrentSession().save(o);
		Constants.getLogs(this.getCurrentSession(), o, Constants.LOGS_INSERT, Constants.LOGS_INSERT_TEXT, Constants.LOGS_INSERT_NAME);
		return serializable;
	}

	public void delete(T o) {
		this.getCurrentSession().delete(o);
	}

	public void update(T o) {
		this.getCurrentSession().update(o);
		Constants.getLogs(this.getCurrentSession(), o, Constants.LOGS_UPDATE, Constants.LOGS_UPDATE_TEXT, Constants.LOGS_UPDATE_NAME);
	}
	
	public void deleteToUpdate(T o) {
		this.getCurrentSession().update(o);
		Constants.getLogs(this.getCurrentSession(), o, Constants.LOGS_DELETE, Constants.LOGS_DELETE_TEXT, Constants.LOGS_DELETE_NAME);
	}

	public void saveOrUpdate(T o) {
		this.getCurrentSession().saveOrUpdate(o);
	}

	public List<T> find(String hql) {
		return this.getCurrentSession().createQuery(hql).list();
	}
	
	@SuppressWarnings("rawtypes")
	public List findBySQL(String sql) {
		return this.getCurrentSession().createSQLQuery(sql).list();
	}
	
	public List<T> find(String hql, Map<String, Object> params) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		return q.list();
	}
	
	public List<T> find(String hql, Map<String, Object> params, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}


	public T get(Class<T> c, Serializable id) {
		return (T) this.getCurrentSession().get(c, id);
	}
	
	public T get(String hql, Map<String, Object>  param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public Long count(String hql) {
		return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
	}
	
	public Long count(String hql, Map<String, Object> params) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		return (Long) q.uniqueResult();
	}
	

	public Integer executeHql(String hql) {
		return this.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	public Integer executeHql(String hql, Map<String, Object> params) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		return q.executeUpdate();
	}
}






public interface CstContactService
{

	List<CustomerContact> findCustomerContactList(Integer customerId );

}





public class CstContactServiceImpl implements CstContactService
{
     private PublicDao<CustomerContact> publicDao;
	@Autowired
	public void setPublicDao(PublicDao<CustomerContact> publicDao )
	{
		this.publicDao = publicDao;
	}
	
	public List<CustomerContact> findCustomerContactList(Integer customerId)
	{
		if (null==customerId||"".equals(customerId))
		{
			return new ArrayList<CustomerContact>();
		}else {
			String hql="from CustomerContact t where t.status='A' and t.customerId="+customerId;
			return publicDao.find(hql);
		}
	}

}
测试线程并发 java
package com.sg.thread.study;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest22 {
	public static void main(String ss[]) {
		List<String> testList = new CopyOnWriteArrayList<String>();
		ExecutorService threadPool = Executors.newFixedThreadPool(20);
		// ExecutorService threadPool = Executors.newCachedThreadPool();
		CountDownLatch countDownLatch = new CountDownLatch(5);
		//long start = System.currentTimeMillis();
		for (int k = 1; k <= 5; k++) {
			threadPool.execute(new TestRunable(countDownLatch, k, testList));
		}
		//System.out.println(System.currentTimeMillis() - start);

		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		threadPool.shutdown();
		// System.out.println(testList);
		// System.out.println(testList.size());
		System.out.println("最后执行结束");
	}
}






package com.sg.thread.study;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class TestRunable implements Runnable {
	CountDownLatch countDownLatch;
	int k;
	List<String> testList;

	public TestRunable(CountDownLatch countDownLatch, int k,
			List<String> testList) {
		this.countDownLatch = countDownLatch;
		this.k = k;
		this.testList = testList;
	}

	@Override
	public void run() {
		for (int i = 1; i <= 6; i++) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("线程:" + k + "; 执行到:" + i);
			// testList.add(new Random().nextInt()+"");
		}
		countDownLatch.countDown();

	}

}





package com.sg.thread.study;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//一个CountDouwnLatch实例是不能重复使用的,也就是说它是一次性的,锁一经被打开就不能再关闭使用了,如果想重复使用,请考虑使用CyclicBarrier

public class CountDownLatchTest {
	// 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
	public static void main(String[] args) {
		 // 开始的倒数锁 
        final CountDownLatch begin = new CountDownLatch(1);  
     // 结束的倒数锁 
        final CountDownLatch end = new CountDownLatch(10); 
        
        // 十名选手 同时进行
        final ExecutorService exec = Executors.newFixedThreadPool(10); 
        
        
        for (int index = 0; index < 10; index++) {
        	final int NO = index + 1;  
        	exec.execute(new Runnable() {
				
				@Override
				public void run() {
					try {  
                        // 如果当前计数为零,则此方法立即返回。
                        // 等待
                        begin.await();  
                        Thread.sleep((long) (Math.random() * 10000));  
                        System.out.println("No." + NO + " arrived");  
                    } catch (InterruptedException e) {  
                    } finally {  
                        // 每个选手到达终点时,end就减一
                        end.countDown();
                    }  
				}
			});
        }
        
        System.out.println("Game Start");  
        // begin减一,开始游戏
        begin.countDown();  
        // 等待end变为0,即所有选手到达终点
        try {
			end.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}  
        System.out.println("Game Over");  
        exec.shutdown();  
	}
}
SpringMVC+hibernate配置 java
web.xml


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
	  </welcome-file-list>
	
	<context-param>
  		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:config/log4j.properties</param-value>
	</context-param>
	
		  <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
	  <context-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/applicationContext.xml</param-value>
			<load-on-startup>1</load-on-startup>
	  </context-param>
	  
	  <listener>
		<listener-class>
				org.springframework.web.context.ContextLoaderListener
			</listener-class>
	  </listener>
  
	<listener>
   	 <listener-class>
				org.springframework.web.util.Log4jConfigListener
			</listener-class>
	  </listener>
	  
	  <!-- Spring MVC  核心配置 -->
	<servlet>
			<servlet-name>springmvc</servlet-name>
			<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
			<init-param>
				<param-name>contextConfigLocation</param-name>
				<param-value>classpath:config/springmvc-servlet.xml</param-value>
			</init-param>
	 </servlet>
	  <servlet-mapping>
			<servlet-name>springmvc</servlet-name>
			<url-pattern>*.do</url-pattern>
	  </servlet-mapping>
	  
	   <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>
		 </filter>
		  <filter-mapping>
			<filter-name>encodingFilter</filter-name>
			<url-pattern>/*</url-pattern>
		  </filter-mapping>
</web-app>



springmvc-servlet.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" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
						http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
						http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<!-- 对web包中的所有累进行扫描,以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="com.sg"/>
	<!-- 启动springMVC 的注解功能,完成请求和注解POJO的映射 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
			<!-- @ResponseBody 标注方法,该方法返回 Java对象(支持复杂对象)
				MappingJacksonHttpMessageConverter 会将对象转换为 JSON 输出
			 -->
				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
			</list>
		</property>
	</bean>
	<!-- 视图解释类 -->
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<!-- 前缀 -->
		<property name="prefix" value="/WEB-INF/view/"/>
		<!-- 后缀 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 文件上传表单的视图解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="defaultEncoding" value="UTF-8"/>
          <property name="maxUploadSize" value="2048003222"/>
    </bean>      
</beans>


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:aop="http://www.springframework.org/schema/aop" 
 xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:tx="http://www.springframework.org/schema/tx"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="   
         http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
   		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
   
   
   <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   		<property name="location">
   			<value>classpath:config/jdbc-config.properties</value>
   		</property>
   </bean>
   	
   	<!--配置 数据源 -->
   	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
   		<property name="driverClassName" value="${jdbc.driverClassName}" />
	    <property name="url" value="${jdbc.url}" /> 	
	 	<property name="username" value="${jdbc.username}" />
	    <property name="password" value="${jdbc.password}" />
	    <property name="initialSize" value="5" />
		<property name="maxActive" value="30" />
		<property name="maxIdle" value="30" />
		<property name="maxWait" value="3000" />
		<property name="defaultAutoCommit" value="true" />
   	</bean>
   	
   	<!-- 定义Hibernate sessionFactory 和Hibernate映射文件,所有的Hibernate映射文件统一在这里定义 -->
   	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 
   		<property name="dataSource" ref="dataSource"/>
   		
   		<property name="hibernateProperties">
   			<props>
   				<prop key="hibernate.dialect">
   					${dataSource.oracle.dialect}
   				</prop>
   				<prop key="show_sql">
   					${dataSource.show_sql}
   				</prop>
   				<prop key="hibernate.hbm2ddl.auto">
   					${dataSource.hbm2ddl.auto}
   				</prop>
   				<prop key="hibernate.format_sql">
   					${dataSource.format_sql}
   				</prop>
   			</props>
   		</property>
   		
   		<!-- 扫描实体类,也就是平时所说的model -->
   		<property name="packagesToScan" value="com.sg.*"/>
   	</bean>
   	
   	<!--注入 配置 Spring的HIbernate模版类 -->
   	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
   		<property name="sessionFactory" ref="sessionFactory"></property>
   	</bean>
   	
   	<!-- 配置一个JdbcTemplate实例 -->
   	<bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">   
     	<property name="dataSource" ref="dataSource"/>  
	</bean> 
	
   	
	<!-- 配置事务管理 --> 	
 	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="dataSource" ref="dataSource"/> 		
		<property name="sessionFactory" ref="sessionFactory"></property>
 	</bean>
 	<tx:annotation-driven transaction-manager="transactionManager"/>
 	
 	<aop:config>
 		<aop:pointcut id="businessService" expression="execution(public * com.sg.serviceImpl.*.*(..))"/>
		<aop:advisor advice-ref="transactionManager" pointcut-ref="businessService"/>
 	</aop:config>
 	
 	<tx:advice id="txAdvice" transaction-manager="transactionManager">
 		<tx:attributes>
 			<!-- get,select开头的方法不需要在事务中运行 。 
			有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的--> 
 			<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
 			<tx:method name="select*" read-only="true" propagation="NOT_SUPPORTED"/>
 			<!-- 其他方法在实务中运行 --> 
 			<tx:method name="*"/>
 		</tx:attributes>
 	</tx:advice>
   </beans>



log4j.properties

log4j.rootLogger = INFO, stdout, console, DEBUG, infoLog

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %5p %2x %c{1}:%L |  %m%n
 
log4j.appender.infoLog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.infoLog.File = ../goodsManager/goodsManager.log
log4j.appender.infoLog.Append = true
log4j.appender.infoLog.layout = org.apache.log4j.PatternLayout
log4j.appender.infoLog.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %5p %2x %c{1}:%L |  %m%n

log4j.logger.com.ibatis=DEBUG , stdout
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG , stdout
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG , stdout
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG , stdout
log4j.logger.java.sql.Connection=DEBUG , stdout
log4j.logger.java.sql.Statement=DEBUG , stdout
log4j.logger.java.sql.PreparedStatement=DEBUG , stdout
log4j.logger.java.sql.ResultSet=DEBUG, stdout
log4j.logger.com=info, infoLog
log4j.logger.java.lang.System = info, infoLog
log4j.appender.org.springframework=info, infoLog
shiro +hibernate4+struts2+spring+easyui+fusioncharts + druid配置 java
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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>erp2</display-name>
  
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>test.jsp</welcome-file>
	</welcome-file-list>
  
	
	 <context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>erp2</param-value>
	</context-param>
	 
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:config/spring.xml,classpath:config/applicationContext.xml</param-value>
  </context-param>
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:config/log4j.xml</param-value>
  </context-param>
  
  <!--shiroFilter 过滤器-->
  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  
  
  <!--验证码-->
  <servlet>
    <servlet-name>kaptcha</servlet-name>
    <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
    <init-param>
      <description> Border around kaptcha. Legal values are yes or no. </description>
      <param-name>kaptcha.border</param-name>
      <param-value>no</param-value>
    </init-param>
    <init-param>
      <description>Color of the border. Legal values are r,g,b (and optional alpha) or white,black,blue. </description>
      <param-name>kaptcha.border.color</param-name>
      <param-value>red</param-value>
    </init-param>
    <init-param>
      <description>Thickness of the border around kaptcha. Legal values are > 0. </description>
      <param-name>kaptcha.border.thickness</param-name>
      <param-value>5</param-value>
    </init-param>
    <init-param>
      <description>Width in pixels of the kaptcha image. </description>
      <param-name>kaptcha.image.width</param-name>
      <param-value>85</param-value>
    </init-param>
    <init-param>
      <description>Height in pixels of the kaptcha image. </description>
      <param-name>kaptcha.image.height</param-name>
      <param-value>35</param-value>
    </init-param>
    <init-param>
      <description>The image producer. </description>
      <param-name>kaptcha.producer.impl</param-name>
      <param-value>com.google.code.kaptcha.impl.DefaultKaptcha </param-value>
    </init-param>
    <init-param>
      <description>The text producer. </description>
      <param-name>kaptcha.textproducer.impl</param-name>
      <param-value>com.google.code.kaptcha.text.impl.DefaultTextCreator</param-value>
    </init-param>
    <init-param>
      <description>The characters that will create the kaptcha. </description>
      <param-name>kaptcha.textproducer.char.string</param-name>
      <param-value>abcde2345678gfynmnpwx </param-value>
    </init-param>
    <init-param>
      <description>The number of characters to display. </description>
      <param-name>kaptcha.textproducer.char.length</param-name>
      <param-value>5</param-value>
    </init-param>
    <init-param>
      <description>A list of comma separated font names.</description>
      <param-name>kaptcha.textproducer.font.names</param-name>
      <param-value>Arial, Courier</param-value>
    </init-param>
    <init-param>
      <description>The size of the font to use. </description>
      <param-name>kaptcha.textproducer.font.size</param-name>
      <param-value>23</param-value>
    </init-param>
    <init-param>
      <description>The color to use for the font. Legal values are r,g,b. </description>
      <param-name>kaptcha.textproducer.font.color</param-name>
      <param-value>black</param-value>
    </init-param>
    <init-param>
      <description>The noise producer. </description>
      <param-name>kaptcha.noise.impl</param-name>
      <param-value>com.google.code.kaptcha.impl.NoNoise </param-value>
    </init-param>
    <init-param>
      <description>The noise color. Legal values are r,g,b. </description>
      <param-name>kaptcha.noise.color</param-name>
      <param-value>black</param-value>
    </init-param>
    <init-param>
      <description>The obscurificator implementation. </description>
      <param-name>kaptcha.obscurificator.impl</param-name>
      <param-value>com.google.code.kaptcha.impl.ShadowGimpy</param-value>
    </init-param>
    <init-param>
      <description>The background implementation. </description>
      <param-name>kaptcha.background.impl</param-name>
      <param-value>com.google.code.kaptcha.impl.DefaultBackground</param-value>
    </init-param>
    <init-param>
      <description>Ending background color. Legal values are r,g,b. </description>
      <param-name>kaptcha.background.clear.to</param-name>
      <param-value>white</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>kaptcha</servlet-name>
    <url-pattern>/Kaptcha.jpg</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <display-name>FCExporter</display-name>
    <servlet-name>FCExporter</servlet-name>
    <servlet-class>com.fusioncharts.exporter.servlet.FCExporter</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>FCExporter</servlet-name>
    <url-pattern>/FCExporter</url-pattern>
  </servlet-mapping>
  
  
  <!--log4jRefreshInterval 每隔多长时间扫描改日志文件,这样当此日志文件改动时不需要重启web服务-->
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>60000</param-value>
  </context-param>
  <!--Log4jConfigListener监听器-->
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  
  
  
  
	<!--druid-->
  <filter>
    <filter-name>druidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
      <param-name>exclusions</param-name>
      <param-value>/css/*,/js/*,*.js,*.css,/druid*,/attached/*,*.jsp</param-value>
    </init-param>
    <init-param>
      <param-name>principalSessionName</param-name>
      <param-value>sessionInfo</param-value>
    </init-param>
  </filter>
  
  <filter-mapping>
    <filter-name>druidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
    
  <!--druid 监控-->
  <servlet>
    <servlet-name>druidStatView</servlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>druidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
  </servlet-mapping>
  
  
  <!--openSessionInViewFilter过滤器-->
  <filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    <init-param>
      <param-name>singleSession</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>openSessionInViewFilter</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>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>
  
  
  
  <!--CharacterEncodingFilter Spring字符集编码过滤器-->
  <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>
  
  
  
  
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!--启动Web容器时,自动装配ApplicationContext的配置信息-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--注册IntrospectorCleanupListener监听器以解决struts等框架可能产生的内存泄露问题 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  
  <!--session 监听-->
  <listener>
    <listener-class>com.erp.listener.SessionListenerHandler</listener-class>
  </listener>
  
  
  <!--session 过期时间-->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  
 <!--错误页面提示-->
  <error-page>
    <error-code>404</error-code>
    <location>/error/404.jsp</location>
  </error-page>
  
  <error-page>
    <error-code>500</error-code>
    <location>/error/500.jsp</location>
  </error-page>
</web-app>



spring.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" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	">
	
	<!-- 引入属性文件 -->
	<context:property-placeholder location="classpath:config/jdbc-config.properties" />

	<!-- 自动扫描dao和service包(自动注入) -->
	<context:component-scan base-package="com.erp.daoImpl,com.erp.serviceImpl" />
</beans>



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" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	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/util
	http://www.springframework.org/schema/util/spring-util-3.0.xsd
	http://www.springframework.org/schema/cache
	http://www.springframework.org/schema/cache/spring-cache.xsd
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	">
	

	<!-- JNDI方式配置数据源 -->
	<!-- 
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="${jndiName}"></property>
	</bean>
	 -->

	<!-- 数据源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="url" value="${jdbc_url}" />
		<property name="username" value="${jdbc_username}" />
		<property name="password" value="${jdbc_password}" />

		<!-- 初始化连接大小 -->
		<property name="initialSize" value="0" />
		<!-- 连接池最大使用连接数量 -->
		<property name="maxActive" value="20" />
		<!-- 连接池最大空闲 -->
<!-- 		<property name="maxIdle" value="20" /> -->
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="0" />
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="60000" />

		<!-- 
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="33" />
		 -->

		<property name="validationQuery" value="${validationQuery}" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="testWhileIdle" value="true" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />
	
		<!-- 打开removeAbandoned功能 -->
		<property name="removeAbandoned" value="true" />
		<!-- 1800秒,也就是30分钟 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 关闭abanded连接时输出错误日志 -->
		<property name="logAbandoned" value="true" /> 
	
		<!-- 监控数据库 -->
		<!-- 
		<property name="filters" value="stat" />
		 -->
		<property name="filters" value="mergeStat" />
	</bean>
	<!-- ehcache 的配置 -->
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		 <property name="configLocation">    
           <value>classpath:config/ehcache.xml</value>    
        </property>   
	</bean>
	
	<!--自定义MyShiroRealm 注入-->
	<bean id="myShiroRealm" class="com.erp.shiro.MyShiroRealm"> 
    	<!--  用来实现用户名密码的查询 --> 
    	<property name="hibernateSessionFactory" ref="sessionFactory"/>
	    <property name="cacheManager" ref="shiroCacheManager"/> 
	    <property name="authenticationCacheName" value="shiroAuthorizationCache"></property>
  	</bean>
  	 <!-- Shiro's main business-tier object for web-enabled applications -->
  	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 
  	 	<!-- <property name="sessionMode" value="native" />
  	 	<property name="sessionManager" ref="sessionManager" />  -->
   	 	<property name="realm" ref="myShiroRealm"/> 
 	</bean> 
 	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
 	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> 
 	<!-- 用户授权信息Cache, 采用EhCache -->
	 <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 
    	<property name="cacheManager" ref="cacheManager"/> 
    </bean>  
    
	 <bean id="formAuthenticationFilter"   class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter"/>

	<!--添加shiroFilter定义  Shiro Filter-->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager"/>
		<property name="loginUrl" value="/login.jsp"/> 
	    <property name="successUrl" value="/index.jsp"/> 
	    <property name="unauthorizedUrl" value="/error/error.jsp"/> 
	    <property name="filters"> 
	       <util:map> 
	         <entry key="authc" value-ref="formAuthenticationFilter"/> 
	       </util:map> 
    	</property> 
	    <property name="filterChainDefinitions"> 
	       <value>
	         /Kaptcha.jpg = anon 
	       	 /js/** = anon  
	       	 /css/** = anon  
	       	 /extend/** = anon
	       	 /systemAction!load.action =  anon
             /** = authc  
	          <!--/login=anon /  /index.jsp=authc
	          /login.do*=authc  /**=authc  /permission/**=roles[admin]
	          /logout.do*=anon -->
	           
	       </value> 
	    </property> 
	</bean>
	
	<!-- sessionFactory 工厂 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
				<prop key="cache.region.factory_class">${org.hibernate.cache.EhCacheRegionFactory}</prop>
			</props>
		</property>
		<!-- 注解方式配置 -->
		<property name="packagesToScan">
			<list>
				<value>com.erp.model</value>
			</list>
		</property>

		<!-- hbm方式配置 -->
		<!-- 
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:com/erp/model</value>
			</list>
		</property>
		 -->
	</bean>
	
	<!--Spring Hibernate 定义事务管理器(声明式的事务) -->
	<bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 注解方式配置事物 
	<tx:annotation-driven transaction-manager="transactionManager" />-->
	
	<!-- 拦截器方式配置事物 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="upd*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="modify*" propagation="REQUIRED"/>
			<tx:method name="edit*" propagation="REQUIRED"/>
			<tx:method name="del*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="remove*" propagation="REQUIRED"/>
			<tx:method name="repair" propagation="REQUIRED"/>
			<tx:method name="persistence*" propagation="REQUIRED"/>

			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut id="transactionPointcut" expression="execution(* com.erp.service..*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
	</aop:config>
	
	<!-- 配置druid监控spring jdbc -->
	<bean id="druid-stat-interceptor"
		class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
	</bean>
	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
		scope="prototype">
		<property name="patterns">
			<list>
				<value>com.erp.service.*</value>
			</list>
		</property>
	</bean>
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor"
			pointcut-ref="druid-stat-pointcut" />
	</aop:config>
</beans>


ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
		
		<!--maxElementsInMemory 缓存中最大允许创建对象数-->   
		<!--eternal 缓存中对象是否是永久的,如果是,超时设置被忽略,对象从不过期-->
		<!--overflowToDisk 内存不足时 是否启动磁盘缓存-->
		<!--timeToIdleSeconds 缓存数据钝化时间(设置对象在它们过期之前的空闲时间)--> 
		<!--timeToLiveSeconds 缓存数据生存时间(设置对象在它们过期之前的生存时间)--> 
		<defaultCache
			maxElementsInMemory="10000" 
			eternal="false"
			overflowToDisk="true" 
			timeToIdleSeconds="500" 
			timeToLiveSeconds="1000"
			diskPersistent="false" 
			diskExpiryThreadIntervalSeconds="120" 
		/> 
			  
		<cache
			name="shiroAuthorizationCache"  
            maxElementsInMemory="10000"
            eternal="false" 
            overflowToDisk="true" 
            diskPersistent="true"
            timeToIdleSeconds="120" 
            timeToLiveSeconds="120" 
            diskExpiryThreadIntervalSeconds="120" 
		/>
</ehcache>


log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">  
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">  
  
    <!-- ========================== 自定义输出格式说明================================ -->  
    <!-- %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL -->  
    <!-- #%r 输出自应用启动到输出该log信息耗费的毫秒数  -->  
    <!-- #%c 输出所属的类目,通常就是所在类的全名 -->  
    <!-- #%t 输出产生该日志事件的线程名 -->  
    <!-- #%n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n” -->  
    <!-- #%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921  -->  
    <!-- #%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java:10)  -->  
    <!-- ========================================================================== -->  
      
    <!-- ========================== 输出方式说明================================ -->  
    <!-- Log4j提供的appender有以下几种:  -->  
    <!-- org.apache.log4j.ConsoleAppender(控制台),  -->  
    <!-- org.apache.log4j.FileAppender(文件),  -->  
    <!-- org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件), -->  
    <!-- org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件),  -->  
    <!-- org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)   -->  
<!-- ========================================================================== -->  
<!-- 输出到日志文件  -->  
    <appender name="filelog_appender"  class="org.apache.log4j.RollingFileAppender">  
        <!-- 设置File参数:日志输出文件名 -->  
       <param name="File" value="${erp}logs/erp_logs_all.log" />  
        <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->  
        <param name="Append" value="true" />  
        <!-- 设置文件大小 -->  
        <param name="MaxFileSize" value="1MB" />  
        <!-- 设置文件备份 -->  
        <param name="MaxBackupIndex" value="10000" />  
        <!-- 设置输出文件项目和格式 -->  
        <layout class="org.apache.log4j.PatternLayout">  
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p (%c:%L)- %m%n" />  
        </layout>  
    </appender>  
    
<!-- 输出到日志文件 每天一个日志  -->  
    <appender name="filelog_daily" class="org.apache.log4j.DailyRollingFileAppender">     
        <param name="File" value="${erp}logs/erp_logs_daily.log" /> 
        <param name="DatePattern" value="'daily.'yyyy-MM-dd'.log'" />     
        <layout class="org.apache.log4j.PatternLayout">     
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss\} %-5p] [%t] (%c:%L) - %m%n" />     
        </layout>     
    </appender>   
  
<!-- 输出到控制台中 -->  
   <appender name="console" class="org.apache.log4j.ConsoleAppender">  
        <layout class="org.apache.log4j.PatternLayout">  
            <param name="ConversionPattern"  
                value="%d{yyyy-MM-dd HH:mm:ss} %-5p: %m%n" />  
            <!-- "%-5p: [%t] [%c{3}.%M(%L)] | %m%n" -->  
        </layout>  
    </appender>  
  
 	<appender name="EMAIL_QQ" class="org.apache.log4j.net.SMTPAppender">  
        <param name="Threshold" value="INFO"/>  
        <param name="BufferSize" value="128" />  
        <param name="SMTPHost" value="smtp.qq.com" />  
        <param name="SMTPUsername" value="756514656" />  
        <param name="SMTPPassword" value="ILOVEYOU2009" />  
        <param name="From" value="1015905041@qq.com" />  
        <param name="To" value="1181583343@qq.com" />  
        <param name="Subject" value="ERP项目异常记录" />  
        <param name="LocationInfo" value="true" />  
        <param name="SMTPDebug" value="true" />  
        <!--<layout class="org.cjj.log4j.extend.PatternLayout_zh">  
            <param name="ConversionPattern" value="[%d{ISO8601}] %-5p %c %m%n"/>  
        </layout>  -->
        <layout class="org.apache.log4j.PatternLayout">     
            <param name="ConversionPattern" value="[%d{ISO8601}] %-5p %c %m%n"/> 
        </layout> 
    </appender>  
  
 <!--- 异步测试,当日志达到缓存区大小时候执行所包的appender -->  
    <appender name="ASYNC_test" class="org.apache.log4j.AsyncAppender">     
     <param name="BufferSize" value="10"/>     
     <appender-ref ref="EMAIL_QQ"/>  
   </appender>  
 <!-- 设置包限制输出的通道 -->  
    <category name="com.erp" additivity="false">  
 <!-- 日志输出级别,起码可以有5个级别,可以扩展自己的级别,邮件发送必须是ERROR级别不好用,所以最后自己扩展一个邮件发送级别 -->  
        <level value="ERROR" />  
        <appender-ref ref="filelog_daily" />  
        <appender-ref ref="filelog_appender" /> 
        <appender-ref ref="console" />  
        <appender-ref ref="ASYNC_test" />  
  </category>  
  <root>  
  		<level value="ERROR" />  
        <appender-ref ref="filelog_daily" />  
        <appender-ref ref="filelog_appender" /> 
        <appender-ref ref="console" />  
        <appender-ref ref="ASYNC_test" />   
  </root>  
</log4j:configuration>  



ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
		
		<!--maxElementsInMemory 缓存中最大允许创建对象数-->   
		<!--eternal 缓存中对象是否是永久的,如果是,超时设置被忽略,对象从不过期-->
		<!--overflowToDisk 内存不足时 是否启动磁盘缓存-->
		<!--timeToIdleSeconds 缓存数据钝化时间(设置对象在它们过期之前的空闲时间)--> 
		<!--timeToLiveSeconds 缓存数据生存时间(设置对象在它们过期之前的生存时间)--> 
		<defaultCache
			maxElementsInMemory="10000" 
			eternal="false"
			overflowToDisk="true" 
			timeToIdleSeconds="500" 
			timeToLiveSeconds="1000"
			diskPersistent="false" 
			diskExpiryThreadIntervalSeconds="120" 
		/> 
			  
		<cache
			name="shiroAuthorizationCache"  
            maxElementsInMemory="10000"
            eternal="false" 
            overflowToDisk="true" 
            diskPersistent="true"
            timeToIdleSeconds="120" 
            timeToLiveSeconds="120" 
            diskExpiryThreadIntervalSeconds="120" 
		/>
</ehcache>

jdbc-config.properties
##数据库连接
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://192.168.1.250:3306/erp?useUnicode=true&characterEncoding=UTF-8
jdbc_username=root
jdbc_password=root

#hibernate
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
org.hibernate.cache.EhCacheRegionFactory=org.hibernate.cache.EhCacheRegionFactory
hibernate.cache.use_query_cache=true
sessionInfoName=sessionInfo

uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
flash视频播放器 java
<script type="text/javascript" src="/js/flareVideo/flarevideo.js"></script>
<script type="text/javascript" src="/js/flareVideo/jquery.flash.js"></script>


<script type="text/javascript">
    $(document).ready(function(){
        $('#newcon').flash({
            //必须要有这个
            'src':'/images/front/gddflvplayer.swf',
            //宽
            'width':'640',
            //高
            'height':'480',
            'allowfullscreen':'true',
            'allowscriptaccess':'always',
            'wmode':'transparent',
            'flashvars': {
            	//播放视频的路径
                'vdo':'${videoImgPath}',//http://www.gdd.ro/flvplayer/examples/video.mp4
                //'vdo':'http://www.gdd.ro/flvplayer/examples/video.mp4',
                //默认声音控制
                'sound':'50',
                //背景图片
                'splashscreen':'${img}',
                //是否自动播放
                'autoplay':'true',
				//'clickTAG':'http://www.gdd.ro',
                'endclipaction':'javascript:endclip();'
            }
        });
    });
</script>


 <div id="newcon" style="text-align: center; height: 490px;"></div>
JAVA加密 java
package com.sg.security;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/**
 *  基础加密组件
 * @author sungang
 *
 */
public class CoderUtils {
	public static final String KEY_SHA = "SHA";
	public static final String KEY_MD5 = "MD5";
	
	public static final String KEY_MAC = "HmacMD5";
	
	
	/**
	 * BASE64加密
	 * @param key
	 * @return
	 */
	public static String encryptBASE64(byte[] key){
		String encryKey = new BASE64Encoder().encode(key);
		return encryKey;
	}
	
	/**
	 * BASE64解密
	 * @param key
	 * @return
	 */
	public static byte[] decryptBASE64(String key){
		byte[] b = null;
		try {
			b = new BASE64Decoder().decodeBuffer(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
	/**
	 * MD5加密 
	 * @param key
	 * @return
	 */
	public static byte[] encryptMD5(byte[] key){
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance(KEY_MD5);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		md5.update(key);
		return md5.digest();
	}
	
	/** 
     * SHA加密 
     *  
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public static byte[] encryptSHA(byte[] data) throws Exception {  
  
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);  
        sha.update(data);  
  
        return sha.digest();  
  
    }  
    
    
    /** 
     * 初始化HMAC密钥 
     *  
     * @return 
     * @throws Exception 
     */  
    public static String initMacKey() throws Exception {  
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
  
        SecretKey secretKey = keyGenerator.generateKey();  
        return encryptBASE64(secretKey.getEncoded());  
    }  
    
    /** 
     * HMAC加密 
     *  
     * @param data 
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static byte[] encryptHMAC(byte[] data, String key) throws Exception {  
  
        SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);  
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
        mac.init(secretKey);  
  
        return mac.doFinal(data);  
    }  
    
    
    public static void main(String[] args) throws Exception {
    	 String inputStr = "简单加密";  
         System.err.println("原文:\n" + inputStr);
         byte[] inputData = inputStr.getBytes(); 
         String code = CoderUtils.encryptBASE64(inputData);  
         System.err.println("BASE64加密后:\n" + code);  
         
         byte[] output = CoderUtils.decryptBASE64(code);  
         String outputStr = new String(output);
         System.err.println("BASE64解密后:\n" + outputStr);  
         
         // 验证BASE64加密解密一致性  
         String key = CoderUtils.initMacKey();  
         System.err.println("Mac密钥:\n" + key);  
         
         BigInteger md5 = new BigInteger(CoderUtils.encryptMD5(inputData));  
         System.err.println("MD5:\n" + md5.toString(16));  
   
         BigInteger sha = new BigInteger(CoderUtils.encryptSHA(inputData));  
         System.err.println("SHA:\n" + sha.toString(32));  
   
         BigInteger mac = new BigInteger(CoderUtils.encryptHMAC(inputData, inputStr));  
         System.err.println("HMAC:\n" + mac.toString(16));  
	}
}
JAVA栈 先进后出 java
package com.sg.arithmetic;

public class StackDemo01 {
	private int maxSize;
	private long[] stackArray;
	private int top;

	public StackDemo01(int s) {
		maxSize = s;
		stackArray = new long[maxSize];
		top = 1;
	}

	public void push(long j) {
		stackArray[++top] = j;
	}

	public long pop() {
		return stackArray[top--];
	}

	public long peek() {
		return stackArray[top];
	}

	public boolean isEmpty() {
		return (top == -1);
	}

	public boolean isFull() {
		return (top == maxSize + 1);
	}

	public static void main(String[] args) {
		StackDemo01 stack = new StackDemo01(10);
		stack.push(20);
		stack.push(40);
		stack.push(60);
		stack.push(80);
		stack.push(100);
		stack.push(120);

		while (!stack.isEmpty()) {
			long value = stack.pop();
			System.out.print(value);
			System.out.print(" ");
		}
		System.out.println();
	}
}
Array CRUD操作 java
package com.sg.arithmetic;

public class HighArray {
	
	private long[] arr;
	private int nELems;
	
	public HighArray(int size) {
		arr = new long[size];
		nELems = 0;
	}
	
	public boolean find(long searchKey){
		int j;
		for(j = 0; j < nELems; j++){
			if (arr[j] == searchKey) {
				break;
			}
		}
		if (j == nELems) {
			return false;
		}else {
			return true;
		}
	}
	
	public void insert(long value){
		arr[nELems] = value;
		nELems++;
	}
	
	public boolean delete(long value){
		int j;
		for(j = 0; j < nELems; j++){
			if (arr[j] == value) {
				break;
			}
		}
		if (j == nELems) {
			return false;
		}else {
			for (int k = j; k < nELems; k++) {
				arr[k] = arr[k+1];
			}
			nELems--;
			return true;
		}
	}
	
	public void display(){
		int j ;
		for(j = 0; j < nELems; j++){
			System.out.print(arr[j]+" ");
		}
		System.out.println();
	}
	
	
	public static void main(String[] args) {
		int maxSize = 100;
		HighArray array = new HighArray(maxSize);
		array.insert(10);
		array.insert(80);
		array.insert(50);
		array.insert(90);
		array.insert(60);
		array.insert(30);
		array.insert(40);
		array.insert(20);
		array.insert(70);
		
		
		array.display();
		
		
		long serachKey = 40;
		if (array.find(serachKey)) {
			System.out.println("Fountd:"+serachKey);
		}else {
			System.out.println("Can't find :"+serachKey);
		}
		
		
		array.delete(10);
		array.delete(90);
		array.display();
	}
}
sql语句--查询练习 database
sql语句--查询练习 

http://blog.csdn.net/zhaoxu0312/article/details/7430606
数据库分页sql语句(mysql,oracle,sqlserver,DB2) database

mysql:

 select * from 表名 where pid=0 limit ((当前页-1)*每页显示多少), 每页显示多少)

oracle:

select * from( select rownum as rn,source.* from( sql语句) source  

where rownum <= (当前页*每页显示多少)) result where rn >= ((当前页-1)*每页显示多少)

sqlserver:

select top 每页显示多少 * from 表名 where 主键列 not in ( 

select top (当前页-1)*每页显示多少 主键列  

from 表名 order by 主键列 ) order by 主键列 如何主键列是自动增长,则可以这样增强查询速度  

select top 每页显示多少 * from 表名 where 主键列 >  (select max(主键列)  

from (select (当前页-1)*每页显示多少 主键列 from 表名 order by 主键列 )) order by 主键列 

DB2:

select * from ( select ROW_NUMBER() OVER() AS ROWNUM,source.* from (sql语句 )source ) a  

where ROWNUM >= ((当前页-1)*每页显示多少) and ROWNUM <=(当前页*每页显示多少)

java 几种排序 使用枚举实现 java
package org.sg.sgg.sort;


public enum SortType {
	/**
	 * 选择排序
	 * Selection Sorting
	 */
	SELECTION(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int len = array.length;
			for (int i = 0; i < len; i++) {
				int selected = i;
				for (int j = i + 1; j < len; j++) {
					int compare = array[j].compareTo(array[selected]);
					if (compare != 0 && compare < 0 == ascend) {
						selected = j;
					}
				}

				exchange(array, i, selected);
			}
		}
	}),
	/**
	 * 插入排序
	 * Insertion Sorting
	 */
	INSERTION(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int len = array.length;
			for (int i = 1; i < len; i++) {
				T toInsert = array[i];
				int j = i;
				for (; j > 0; j--) {
					int compare = array[j - 1].compareTo(toInsert);
					if (compare == 0 || compare < 0 == ascend) {
						break;
					}
					array[j] = array[j - 1];
				}

				array[j] = toInsert;
			}
		}
	}),

	/**
	 * 冒泡排序
	 * Bubble Sorting, it's very similar with Insertion Sorting
	 */
	BUBBLE(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int length = array.length;
			int lastExchangedIdx = 0;
			for (int i = 0; i < length; i++) {
				// mark the flag to identity whether exchange happened to false
				boolean isExchanged = false;
				// last compare and exchange happened before reaching index i
				int currOrderedIdx = lastExchangedIdx > i ? lastExchangedIdx : i;
				for (int j = length - 1; j > currOrderedIdx; j--) {
					int compare = array[j - 1].compareTo(array[j]);
					if (compare != 0 && compare > 0 == ascend) {
						exchange(array, j - 1, j);
						isExchanged = true;
						lastExchangedIdx = j;
					}
				}
				// if no exchange happen means array is already in order
				if (isExchanged == false) {
					break;
				}
			}
		}
	}),

	/**
	 * 壳(Shell)排序
	 * Shell Sorting
	 */
	SHELL(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int length = array.length;
			int gap = 1;

			// use the most next to length / 3 as the first gap
			while (gap < length / 3) {
				gap = gap * 3 + 1;
			}

			while (gap >= 1) {
				for (int i = gap; i < length; i++) {
					T next = array[i];
					int j = i;
					while (j >= gap) {
						int compare = array[j - gap].compareTo(next);
						// already find its position
						if (compare == 0 || compare < 0 == ascend) {
							break;
						}

						array[j] = array[j - gap];
						j -= gap;
					}
					if (j != i) {
						array[j] = next;
					}
				}
				gap /= 3;
			}

		}
	}),

	/**
	 * 归并排序
	 * Merge sorting
	 */
	MERGE(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			this.sort(array, 0, array.length - 1, ascend);
		}

		private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {
			// OPTIMIZE ONE
			// if the substring's length is less than 20,
			// use insertion sort to reduce recursive invocation
			if (hi - lo < 20) {
				for (int i = lo + 1; i <= hi; i++) {
					T toInsert = array[i];
					int j = i;
					for (; j > lo; j--) {
						int compare = array[j - 1].compareTo(toInsert);
						if (compare == 0 || compare < 0 == ascend) {
							break;
						}
						array[j] = array[j - 1];
					}

					array[j] = toInsert;
				}

				return;
			}

			int mid = lo + (hi - lo) / 2;
			sort(array, lo, mid, ascend);
			sort(array, mid + 1, hi, ascend);
			merge(array, lo, mid, hi, ascend);
		}

		private <T extends Comparable<T>> void merge(T[] array, int lo, int mid, int hi, boolean ascend) {
			// OPTIMIZE TWO
			// if it is already in right order, skip this merge
			// since there's no need to do so
			int leftEndCompareToRigthStart = array[mid].compareTo(array[mid + 1]);
			if (leftEndCompareToRigthStart == 0 || leftEndCompareToRigthStart < 0 == ascend) {
				return;
			}

			@SuppressWarnings("unchecked")
			T[] arrayCopy = (T[]) new Comparable[hi - lo + 1];
			System.arraycopy(array, lo, arrayCopy, 0, arrayCopy.length);

			int lowIdx = 0;
			int highIdx = mid - lo + 1;

			for (int i = lo; i <= hi; i++) {
				if (lowIdx > mid - lo) {
					// left sub array exhausted
					array[i] = arrayCopy[highIdx++];
				} else if (highIdx > hi - lo) {
					// right sub array exhausted
					array[i] = arrayCopy[lowIdx++];
				} else if (arrayCopy[lowIdx].compareTo(arrayCopy[highIdx]) < 0 == ascend) {
					array[i] = arrayCopy[lowIdx++];
				} else {
					array[i] = arrayCopy[highIdx++];
				}
			}
		}
	}),

	/**
	 * 快速排序
	 * Quick Sorting
	 */
	QUICK(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			this.sort(array, 0, array.length - 1, ascend);
		}

		private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {
			if (lo >= hi) {
				return;
			}

			// int partitionIdx = partition(array, lo, hi, ascend);

			T toFinal = array[lo];
			int leftIdx = lo;
			int rightIdx = hi;

			int i = lo + 1;

			while (i <= rightIdx) {
				int compare = array[i].compareTo(toFinal);
				if (compare == 0) {
					i++;
				} else if (compare < 0 == ascend) {
					exchange(array, leftIdx++, i++);
				} else {
					exchange(array, rightIdx--, i);
				}
			}

			// partially sort left array and right array
			// no need to include the leftIdx-th to rightIdx-th elements
			// since they are already in its final position
			sort(array, lo, leftIdx - 1, ascend);
			sort(array, rightIdx + 1, hi, ascend);
		}

		/**
		 * This is the old two-way partition method.
		 * 
		 * @param array
		 * @param lo
		 * @param hi
		 * @param ascend
		 * @return partitionIdx
		 */
		@Deprecated
		@SuppressWarnings("unused")
		private <T extends Comparable<T>> int partition(T[] array, int lo, int hi, boolean ascend) {
			int leftIdx = lo;
			int rightIdx = hi + 1;

			T toFinal = array[lo];

			while (true) {
				// search from left to right to locate the element placed
				// in the wrong position which should be in the right
				while (array[++leftIdx].compareTo(toFinal) < 0 == ascend) {
					if (leftIdx >= hi) {
						break;
					}
				}

				// search from right to left to locate the element placed
				// in the wrong position which should be in the left
				while (array[--rightIdx].compareTo(toFinal) > 0 == ascend) {
					if (rightIdx <= lo) {
						break;
					}
				}

				if (leftIdx >= rightIdx) {
					break;
				} else {
					exchange(array, leftIdx, rightIdx);
				}
			}

			exchange(array, lo, rightIdx);

			return rightIdx;
		}
	}),

	/**
	 * 
	 * 堆排序
	 * Heap Sorting
	 */
	HEAP(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			final int length = array.length;

			// Heap use array and below convention to form data. assume k is the
			// k-th node then the node with index that nearest to (k - 1) / 2 is
			// its
			// parent and nodes with 2 * k + 1 and 2 * k + 2 are its two
			// children

			// initialize a heap
			for (int k = (length - 2) / 2; k >= 0; k--) {
				sink(array, k, length, ascend);
			}

			for (int currentHeapSize = length; currentHeapSize > 0;) {
				exchange(array, 0, currentHeapSize - 1);
				sink(array, 0, --currentHeapSize, ascend);
			}
		}

		private <T extends Comparable<T>> void sink(T[] array, int nodeIdx, int heapSize, boolean ascend) {
			while (2 * nodeIdx + 1 < heapSize) {
				int childIdx = 2 * nodeIdx + 1;

				// find the larger one between its two children, if there is any
				if (childIdx + 1 < heapSize) {
					int childrenCompare = array[childIdx].compareTo(array[childIdx + 1]);
					if (childrenCompare != 0 && childrenCompare < 0 == ascend) {
						childIdx++;
					}
				}

				int parentChildCompare = array[nodeIdx].compareTo(array[childIdx]);
				if (parentChildCompare == 0 || parentChildCompare > 0 == ascend) {
					break;
				}

				exchange(array, nodeIdx, childIdx);

				nodeIdx = childIdx;
			}
		}
	})

	;

	private SortType(Sortable sortAlgo) {
		this.sortAlgo = sortAlgo;
	}

	private Sortable sortAlgo;

	public <T extends Comparable<T>> void sort(T[] array) {
		sortAlgo.sort(array, true);
	}

	public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
		if (array == null || array.length <= 2) {
			return;
		}
		sortAlgo.sort(array, ascend);
	}

	/**
	 * exchange the nodes specified by given indices, if the indices are equal,
	 * do nothing
	 * 
	 * @param array
	 *            array which hold the elements
	 * @param p
	 *            one index to exchange
	 * @param q
	 *            the other index to exchange
	 */
	private static void exchange(Object[] array, int p, int q) {
		if (p == q) {
			return;
		}
		Object temp = array[p];
		array[p] = array[q];
		array[q] = temp;
	}

}





package org.sg.sgg.sort;

public interface Sortable {

	/**
	 * Sort the given array which consists of child class of {@link Comparable}<br/>
	 * 
	 * @param array
	 * @param ascend
	 *            if true, using ascend, else using descend
	 */
	<T extends Comparable<T>> void sort(T[] array, boolean ascend);
}






package org.sg.sgg.sort;

import java.util.Arrays;
import java.util.Random;

import junit.framework.Assert;

import org.junit.Test;

public class SortingTest {

	// define the array's size
	private final int PROBLEM_SCALE = 10000;

	private boolean checkSorted = true;

	private boolean showDebugInfo = false;

	@Test
	// @Ignore
	public void selectionSort() {
		sort(SortType.SELECTION);
	}

	@Test
	// @Ignore
	public void insertionSort() {
		sort(SortType.INSERTION);
	}

	@Test
	// @Ignore
	public void bubbleSort() {
		sort(SortType.BUBBLE);
	}

	@Test
	// @Ignore
	public void shellSort() {
		sort(SortType.SHELL);
	}

	@Test
	// @Ignore
	public void mergeSort() {
		sort(SortType.MERGE);
	}

	@Test
	// @Ignore
	public void quickSort() {
		sort(SortType.QUICK);
	}

	@Test
	// @Ignore
	public void heapSort() {
		sort(SortType.HEAP);
	}

	private void sort(SortType sortType) {
		Integer[] array = generateArray(PROBLEM_SCALE);
		if (showDebugInfo) {
			System.out.println("Before: " + Arrays.toString(array));
		}
		sortType.sort(array);
		if (showDebugInfo) {
			System.out.println("After " + sortType.name() + " sort: " + Arrays.toString(array));
		}
		if (checkSorted) {
			Assert.assertTrue(isSorted(array));
		}
	}

	private Integer[] generateArray(int length) {
		Random rand = new Random();
		Integer[] array = new Integer[length];

		for (int i = 0; i < length; i++) {
			array[i] = rand.nextInt(length * 4);
		}
		return array;
	}

	private <T extends Comparable<T>> boolean isSorted(T[] array) {
		if (array == null || array.length <= 2) {
			return true;
		}

		// record the result of last comparison
		Boolean lastCompare = null;

		for (int i = 1; i < array.length; i++) {
			int compareResult = array[i - 1].compareTo(array[i]);
			if (lastCompare == null || compareResult == 0) {
				if (compareResult != 0) {
					lastCompare = compareResult > 0;
				}
				continue;
			}

			if (compareResult > 0 != lastCompare) {
				return false;
			}
		}

		return true;
	}
}
java比较两个日期大小 java
	String str1 = "2013-11-11 09:12:09";
		String str2 = "2013-10-01 09:12:11";
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		
		c1.setTime(format.parse(str1));
		c2.setTime(format.parse(str2));
		
		int result = c1.compareTo(c2);
		if (result == 0) {
			System.out.println("c1相等c2");
		}else if (result < 0) {
			System.out.println("c1小于c2");
		}else {
			System.out.println("c1大于c2");
		}
java求两个集合中的交集 并集 差集 java
package com.sg.procedure;

import java.util.HashSet;
import java.util.Set;

public class IntersectionDemo {
	public static void main(String[] args) {
		Set<Integer> result = new HashSet<Integer>();
		Set<Integer> set1 = new HashSet<Integer>(){
			{
				add(1);
				add(3);
				add(5);
			}
		};
		
		Set<Integer> set2 = new HashSet<Integer>(){{
				add(1);
				add(2);
				add(3);
		}};
		
		
		result.clear();
		result.addAll(set1);
		result.retainAll(set2);
		System.out.println(("交集:"+result));
		
		result.clear();
		result.addAll(set1);
		result.removeAll(set2);
		System.out.println("差集:" + result);
		
		result.clear();
		result.addAll(set1);
		result.addAll(set2);
		System.out.println("并集:"+ result);
	}
}
PageUtilsForResultToRequest(分页) java
package com.teamax.bean ; 

  /**
   * @author xiaoli
   * 分页对象信息
   * 2013-05-27
   */
   public class Page {

   /**
    * 总记录数
   */
   public  static int talcount;

   /**
    * 总页数
   */
   public  static int talpage;

   /**
    * 当前页
   */
   public  static int current;

   /**
    *  一页显示的记录数
   */
   public  static int getPageSize_default = 5;
   /**
   * 设置总记录数,当前页,一页显示的记录数
   * @param talcount
   * @param current
   * @param pagesize
   */
   public static void setPage(int talcount,int current,int pagesize){
        setTalcount(talcount);
        int talpage=(int)Math.ceil((float)talcount/pagesize);
        setTalpage(talpage);
        setCurrent(current);
   }

   /**
   * 返回分页的视图
   */
   public static String getviewString(){
           StringBuilder  buf=new StringBuilder();
            if(talcount==0){
                   buf.append("<a   style='color:red;font-size:12px;' >暂无记录</a>");
            }
            else{
            	buf.append("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
				buf.append("<tr>");
				buf.append("<td class='right_nk_kzbox' >共"+talpage+"页,当前第"+current+"页</td>");
				buf.append("<td class='right_nk_kzbox'>");
				   if(current<=1){
					    buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("+current+");' disabled='disabled' class='faye'><</a></div>");
		    	    }else{
		    	    	buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("+(current-1)+");'  class='faye'><</a></div>");
		    	    }
					buf.append("<div class='right_nk_fyk'><a href='#a' class='faye' >"+current+"</a></div>");
		    	    if(current>=talpage){
		    	    	buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("+talpage+");' disabled='disabled' class='faye'>></a></div>");
		    	    }else{
		    	    	buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("+(current+1)+");' class='faye'>></a></div>");
		    	    }
				buf.append("</td>");
				buf.append("</tr>");
				buf.append("</table>");
          }
          return  buf.toString();
   }
   
   /**
    * 返回分页的视图
    */
    public static String getviewString1(){
            StringBuilder  buf=new StringBuilder();
             if(talcount==0){
                    buf.append("<a   style='color:red;font-size:12px;' >暂无记录</a>");
             }
             else{
             	buf.append("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
 				buf.append("<tr>");
 				buf.append("<td class='right_nk_kzbox' >共"+talpage+"页,当前第"+current+"页</td>");
 				buf.append("<td class='right_nk_kzbox'>");
 				   if(current<=1){
 					    buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("+current+");' disabled='disabled' class='faye'><</a></div>");
 		    	    }else{
 		    	    	buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("+(current-1)+");'  class='faye'><</a></div>");
 		    	    }
 					buf.append("<div class='right_nk_fyk'><a href='#a' class='faye' >"+current+"</a></div>");
 		    	    if(current>=talpage){
 		    	    	buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("+talpage+");' disabled='disabled' class='faye'>></a></div>");
 		    	    }else{
 		    	    	buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("+(current+1)+");' class='faye'>></a></div>");
 		    	    }
 				buf.append("</td>");
 				buf.append("</tr>");
 				buf.append("</table>");
           }
           return  buf.toString();
    }


   public static int getTalcount() {
       return talcount;
   }
   public static void setTalcount(int talcount) {
        Page.talcount = talcount;
   }
   public static int getTalpage() {
       return talpage;
   }
   public static void setTalpage(int talpage) {
       Page.talpage = talpage;
   }
   public static int getCurrent() {
       return current;
   }
   public static void setCurrent(int current) {
       Page.current = current;
   }
  }




 /**
	 *  当前请求列表
	 */
	public String getSearchStaticListPage(){
	   String current = StrutsUtil.getParameter("current");
	   String pid = StrutsUtil.getParameter("pid");
	   current = (current == null?"1":current);
	   if(pvCount == null){
		   pvCount = new PvConut();
	   }
	   System.out.println("getSearchStaticListPage");
	   List<PvConut> appBeanList = super.getStatisticDao().getSearchPubCountListPage(pvCount,Integer.parseInt(current), Page.getPageSize_default);
	   System.out.println("请求列表集合大小:"+appBeanList.size());
	   for (PvConut bean : appBeanList) {
		   bean.setBrowser_name_text(StrutsUtil.getFullTextConvertPartText(bean.getBrowser_name(),25));
	  }
	   StrutsUtil.setRequestParams(new Object[][]{{"list","current","getviewString","pid","var"},{appBeanList,Page.getCurrent(),Page.getviewString(),pid,pvCount}}, 5);
	   return "sys_pub_request_list";
	}



/**
	   * 返回分页后的数据集
	   * @param  pubCount
	   * @param  current 
	   * @param  pagesize 
	   * @return  List<PvConut> 
	   */
	 public  List<PvConut> getSearchPubCountListPage(PvConut  pvCount,int current,int pagesize) {
		      System.out.println("pvCount="+pvCount);
	          int talcount = getSearchPubCountListPageCount(pvCount) ;
	          System.out.println("talcount="+talcount);
		      Page.setPage(talcount, current, pagesize);
		      int num = (current-1)*pagesize;
		      Map<String, String> map = new HashMap<String, String>();
		      map.put("num", String.valueOf(num));
		      map.put("pagesize", String.valueOf(pagesize));
		      map.put("startnum", String.valueOf((num+1)));
		      map.put("endnum",  String.valueOf((num+pagesize)));
		      map.put("ip",  pvCount.getIp());
			  beforInit();
	          return (List<PvConut>)this.getSqlMapClientTemplate().queryForList("getSearchPubCountListPage",map);
	 }
	 


/**
	   * 返回记录数
	   * @param  appBean
	   * @return  int 
	   */
	 public  int getSearchPubCountListPageCount(PvConut  pvCount){
		  beforInit();
	      Map<String, String> map = new HashMap<String, String>();
	      map.put("ip",  pvCount.getIp());
	      return (Integer)this.getSqlMapClientTemplate().queryForObject("getSearchPubCountListPageCount",map);
	 }



public static void setRequestParams(Object[][] obj,int len){
		for (int i = 0; i < len; i++) {
			getRequest().setAttribute(String.valueOf(obj[0][i]), obj[1][i]);
		}
	} 


AddrIPUtil java
package com.teamax.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户IP操作
 * */
public class AddrIPUtil {

	public static String getIpAddr2(HttpServletRequest request) {
		StringBuilder builder = new StringBuilder();

		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface intf = (NetworkInterface) en.nextElement();
				Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
				while (enumIpAddr.hasMoreElements()) {
					InetAddress inetAddress = (InetAddress) enumIpAddr
							.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& !inetAddress.isLinkLocalAddress()
							&& inetAddress.isSiteLocalAddress()) {
						builder.append(inetAddress.getHostAddress().toString()
								);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	/**
	 * 获取客户IP
	 * */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		
		return ip;
	}

	public static InetAddress getLocalHostAddress() {
		try {

			for (Enumeration<NetworkInterface> nis = NetworkInterface
					.getNetworkInterfaces();; nis.hasMoreElements()) {
				NetworkInterface ni = nis.nextElement();
				if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) {
					continue;
				}
				for (Enumeration<InetAddress> ias = ni.getInetAddresses(); ias
						.hasMoreElements();) {
					InetAddress ia = ias.nextElement();
					if (ia instanceof Inet6Address) {
						continue;
					}
					return ia;
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getlocalIPForCDM() {
		StringBuilder builder = new StringBuilder();

		String command = "cmd.exe /c ipconfig | findstr IPv4";

		try {
			Process p = Runtime.getRuntime().exec(command);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line = null;
			while ((line = br.readLine()) != null) {
				line = line.substring(line.lastIndexOf(":") + 2, line.length());
				builder.append(line);
			}
			br.close();
			p.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static String getLocalIPForJava() {
		StringBuilder builder = new StringBuilder();

		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface intf = (NetworkInterface) en.nextElement();
				Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
				while (enumIpAddr.hasMoreElements()) {
					InetAddress inetAddress = (InetAddress) enumIpAddr
							.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& !inetAddress.isLinkLocalAddress()
							&& inetAddress.isSiteLocalAddress()) {
						builder.append(inetAddress.getHostAddress().toString()
								+ "\n");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static void main(String[] args) {
		HttpServletRequest request = (HttpServletRequest)RequestFilter.threadLocalRequest;
		System.out.println(getIpAddr(request));
		System.out.println(getLocalHostAddress());
		System.out.println(getlocalIPForCDM());
		System.out.println(getLocalIPForJava());

	}

}
MemCachedClientUtils java
package com.web.util;

import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import net.sf.json.JSONObject;

public class MemCachedClientUtils {
	/**
	 * 当前登录用户session ID
	 */
	public String SESS_ID = "sess_id";
	public String FRONT_USER = "front_user";

	public String SERVICE = "192.168.1.82:11211";
	public int INIT_CONN = 20;
	public int MIN_CONN = 10;
	public int MAX_CONN = 50;
	public boolean NAGLE = false;
	public int SOCKETTO = 3000;

	/**
	 * 当前登录用户
	 */

	private static MemCachedClient memcachedClient = null;
	/**
	 * 单例模式实现客户端管理类
	 */
	private static MemCachedClientUtils INSTANCE = null;
	
	/**
	 * 构造私有化
	 */
	private MemCachedClientUtils() {
		// 获取连接池的实例
		SockIOPool pool = SockIOPool.getInstance();
		// 服务器列表及其权重
		String[] servers = { SERVICE };

		// 设置服务器信息
		pool.setServers(servers);
		Integer[] w = { 3 };
		pool.setWeights(w);

		// 设置初始连接数、最小连接数、最大连接数、最大处理时间
		pool.setInitConn(INIT_CONN);
		pool.setMinConn(MIN_CONN);
		pool.setMaxConn(MAX_CONN);

		// 设置连接池守护线程的睡眠时间
		pool.setMaintSleep(60);

		// 设置TCP参数,连接超时
		pool.setNagle(NAGLE);
		pool.setSocketTO(SOCKETTO);

		// 初始化并启动连接池
		pool.initialize();

		if (memcachedClient == null) {
			memcachedClient = new MemCachedClient();
		}
	}
	
	
	/**
	 * 获取单例实例
	 * 
	 * @return
	 */
	public static synchronized MemCachedClientUtils getInstance() {
		if (INSTANCE != null)
			return INSTANCE;
		INSTANCE = new MemCachedClientUtils();
		return INSTANCE;
	}

	
	/**
	 * 设置memcachedClient内容
	 */
	public void setMemcachedClient(Object login_user, String sessId) {
		// 将用户存放到memcached缓存里面 假设30分钟 失效
		memcachedClient.set(sessId, JSONObject.fromObject(login_user),
				new Date(1000 * 30 * 60));

	}

	public void set(String key, Object value) {
		memcachedClient.set(key, value);
	}

	public void set(String key, Object value, int milliseconds) {
		memcachedClient.set(key, value, milliseconds);
	}

	public void delete(String key) {
		memcachedClient.delete(key);
		memcachedClient.flushAll();
	}

	@SuppressWarnings("deprecation")
	public void delete(String key, int milliseconds) {
		memcachedClient.delete(key, milliseconds, new Date());
		memcachedClient.flushAll();
	}

	public void update(String key, Object value, int milliseconds) {
		memcachedClient.replace(key, value, milliseconds);
	}

	public Object get(String key) {
		return memcachedClient.get(key);
	}
}






package com.teamax.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.teamax.bean.UserBase;
import com.teamax.contant.Contant;

public class SessionFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpSession session = httpRequest.getSession();
		 String sessId = httpRequest.getParameter("sessId");//共享sessionId
		 //判断当前session是否失效
		 String sessIdStr = (String)session.getAttribute(Contant.SESS_ID);
		 if (null == sessIdStr || "".equals(sessIdStr)) {
			 if (sessId != null) {
				 session.setAttribute(Contant.SESS_ID,sessId);
			}
			 
		}
		 UserBase user = SimpleUtil.getLoginUser(httpRequest);
		 if (null != user ) {
			 httpRequest.getSession().setAttribute(Contant.FRONT_USER, user);
			 httpRequest.getSession().setAttribute("login_user", user.getUserAccount());
		}else{
			httpRequest.getSession().setAttribute(Contant.FRONT_USER, null);
			httpRequest.getSession().setAttribute("login_user", "");
		}
		 chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}



public static UserBase getLoginUser(HttpServletRequest request) {
		UserBase userBase = null;
		// HttpSession session = StrustUtil.getSession();
		HttpSession session = request.getSession();
		MemCachedClient men = SimpleUtil.getMemCachedClient();
		Object sessIdObj = session.getAttribute(Contant.SESS_ID);
		if (sessIdObj instanceof String) {
			String sessId = (String) sessIdObj;// 获取共享的sessionId
			Object obj = men.get(sessId);
			if (obj instanceof JSONObject) {
				JSONObject json = (JSONObject) obj;
				men.set(sessId, json, new Date(1000 * 30 * 60));// 更新session时间
				int userId = json.getInt("userId");
				String userName = json.getString("userName");
				String userAccount = json.getString("userAccount");
				String level = json.getString("score");
				String platformType =json.getString("platformType");
				userBase = new UserBase();

				userBase.setUserId(userId);
				userBase.setUserAccount(userAccount);
				userBase.setUserName(userName);
				userBase.setScore(level);
				userBase.setPlatformType(platformType);
			}
		}
		return userBase;
	}
PageUtilsForResultToPager<Map<>:>(分页) java
package com.teamax.tools;

import java.util.List;

public class Pager<T> {
	// 当前的页码
	private int pageNo=1;
	// 一页显示的条数
	private int pageSize=10;
	// 总的记录数
	private int totalRows;
	// 总的页数
	private int totalPages;
	// 当前页面的数据
	private List<T> rows;

	public Pager() {
		super();
	}
	


	public Pager(int pageSize) {
		super();
		this.pageSize = pageSize;
	}

	public Pager(int pageNo, int pageSize, int totalRows) {
		this.pageNo = pageNo;
		this.pageSize = pageSize;
		this.totalRows = totalRows;

		// 错误判断
		if (this.pageNo < 1) {
			this.pageNo = 1;
		}
		if (this.pageSize < 1) {
			this.pageSize = 10;
		}
	
	}
	public Integer findFirst() {
		return (getPageNo() - 1) * getPageSize();
	}
	public Integer findMax() {
		return  getPageSize();
	}
	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

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

	public int getTotalRows() {
		return totalRows;
	}

	public void setTotalRows(int totalRows) {
		this.totalRows = totalRows;
	}

	public int getTotalPages() {
		// 计算totalPages
		// pageSize totalRows
		// 10 110
		// 10 109
		// 10 101
		this.totalPages = (this.totalRows + this.pageSize - 1) / this.pageSize;

		// if(this.totalRows%this.pageSize==0){
		// this.totalPages=this.totalRows/this.pageSize;
		// }else{
		// this.totalPages=this.totalRows/this.pageSize+1;
		// }

		if (this.pageNo >= this.totalPages) {
			this.pageNo = this.totalPages;
		}
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	public void setRows(List<T> rows) {
		this.rows = rows;
	}
	public List<T> getRows() {
		return rows;
	}

}



@Override
	public Pager<Map<String, Object>> findApply(DownLoadApply cdt,Pager<Map<String, Object>> pager) {
		Object[] args = null;
		
		StringBuffer sql=new StringBuffer();
		sql.append(" select t.APPLYTIME,decode(t.checkstate,0,'未审核',1,'审核通过',2,'审核不通过','该数据为非法录入') checkstate, tt.username, ttt.filename, ttt.filedesc ");
		sql.append(" from downloadapply t ");
		sql.append(" left join sys_userbase tt ");
		sql.append(" on t.u_id = tt.userid ");
		sql.append(" left join uploadapply ttt ");
		sql.append(" on t.file_id = ttt.id ");
		sql.append(" where 1 = 1 ");
		
		StringBuilder countSql=new StringBuilder();
		Map<String, Object> sqlAndParams=iQueryCondition.getWhereSqlAndValue(cdt);
		countSql.append(" select count(1) from downloadapply t");
		countSql.append(" where 1=1 ");
		
		if (sqlAndParams!=null&&sqlAndParams.size()>0) {
			sql.append(sqlAndParams.get("sql"));
			countSql.append(sqlAndParams.get("sql"));
			args=((List<Object>)sqlAndParams.get("values")).toArray();
		}
		sql.append(" order by t.applytime ");
		int count=jdbcTemplate.queryForInt(countSql.toString(),args);
		List<Map<String,Object>> rt =jdbcTemplate.queryForList(getPageSQL(sql.toString(), pager.getPageNo(), pager.getPageSize()),args);
		pager.setRows(rt);
		pager.setTotalRows(count);
		return pager;
	}

public String findApply() throws IOException {
		Integer servicId = service.getId();// 查询服务注册申请
		Integer user_id = serviceApply.getUser_id();//查询某个用户的使用申请
			Map<String, Object> params=new HashMap<String, Object>();
			if (servicId != null) {// 如果是用服务id或者(服务id和申请人)查询单条申请数据
				List<Map<String, Object>> result = iServiceApplyService
						.findRegistAndUseApplyList(servicId, user_id);
				JSONArray jsonObject = JSONArray.fromObject(result);
				try {
					printStrJson(delJson(jsonObject.toString()));
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
			params.put("max_Time", getParamInRequest("endTime"));
			params.put("min_Time", getParamInRequest("startTime"));
			mapPager = iServiceApplyService.findRegistAndUseApply(mapPager,
					params);
		JSONObject jsonObject = JSONObject.fromObject(mapPager);
		try {
			printStrJson(delJson(jsonObject.toString()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
PageUtilsForResultToJSON(分页) java
package org.sg.sgg.page;

/**
 * 
 * @author sungang
 * 
 */
public class PageUtils {
	/**
	 * 总记录数
	 */
	public static int talcount;

	/**
	 * 总页数
	 */
	public static int talpage;

	/**
	 * 当前页
	 */
	public static int current;

	/**
	 * 一页显示的记录数
	 */
	public static int getPageSize_default = 5;

	/**
	 * 设置总记录数,当前页,每页显示的记录数
	 * 
	 * @param talcount
	 *            - 总记录数
	 * @param current
	 *            - 当前页
	 * @param pagesize
	 *            - 每页显示的记录数
	 */
	public static void setPage(int talcount, int current, int pagesize) {
		setTalcount(talcount);
		setCurrent(current);
		int talpage = (int) Math.ceil((float) talcount / pagesize);
		setTalpage(talpage);
	}

	/**
	 * 返回分页的视图 1
	 */
	public static String getviewString() {
		StringBuilder buf = new StringBuilder();
		if (talcount == 0) {
			buf.append("<a   style='color:red;font-size:12px;' >暂无记录</a>");
		} else {
			buf.append("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
			buf.append("<tr>");
			buf.append("<td class='right_nk_kzbox' >共" + talpage + "页,当前第"
					+ current + "页</td>");
			buf.append("<td class='right_nk_kzbox'>");
			if (current <= 1) {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("
						+ current
						+ ");' disabled='disabled' class='faye'><</a></div>");
			} else {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("
						+ (current - 1) + ");'  class='faye'><</a></div>");
			}
			buf.append("<div class='right_nk_fyk'><a href='#a' class='faye' >"
					+ current + "</a></div>");
			if (current >= talpage) {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("
						+ talpage
						+ ");' disabled='disabled' class='faye'>></a></div>");
			} else {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn("
						+ (current + 1) + ");' class='faye'>></a></div>");
			}
			buf.append("</td>");
			buf.append("</tr>");
			buf.append("</table>");
		}
		return buf.toString();
	}

	/**
	 * 返回分页的视图 2
	 */
	public static String getviewString1() {
		StringBuilder buf = new StringBuilder();
		if (talcount == 0) {
			buf.append("<a   style='color:red;font-size:12px;' >暂无记录</a>");
		} else {
			buf.append("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
			buf.append("<tr>");
			buf.append("<td class='right_nk_kzbox' >共" + talpage + "页,当前第"
					+ current + "页</td>");
			buf.append("<td class='right_nk_kzbox'>");
			if (current <= 1) {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("
						+ current
						+ ");' disabled='disabled' class='faye'><</a></div>");
			} else {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("
						+ (current - 1) + ");'  class='faye'><</a></div>");
			}
			buf.append("<div class='right_nk_fyk'><a href='#a' class='faye' >"
					+ current + "</a></div>");
			if (current >= talpage) {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("
						+ talpage
						+ ");' disabled='disabled' class='faye'>></a></div>");
			} else {
				buf.append("<div class='right_nk_fyk'><a href='javascript:page_fn1("
						+ (current + 1) + ");' class='faye'>></a></div>");
			}
			buf.append("</td>");
			buf.append("</tr>");
			buf.append("</table>");
		}
		return buf.toString();
	}

	public static int getTalcount() {
		return talcount;
	}

	public static void setTalcount(int talcount) {
		PageUtils.talcount = talcount;
	}

	public static int getTalpage() {
		return talpage;
	}

	public static void setTalpage(int talpage) {
		PageUtils.talpage = talpage;
	}

	public static int getCurrent() {
		return current;
	}

	public static void setCurrent(int current) {
		PageUtils.current = current;
	}

	// 使用实例
	public static void main(String[] args) {
		// current pageIndex实际应用用 直接是参数形式
		int current = 1;
		int pageIndex = 5;

		int talcount = getAllCount();
		PageUtils.setPage(talcount, current, pageIndex);
		int num = (current - 1) * pageIndex;
		int startnum = num + 1;
		int endnum = num + pageIndex;
		System.out.println("每页显示条数:" + pageIndex);
		System.out.println("开始页:" + startnum);
		System.out.println("结束页:" + endnum);
		System.out.println("共多少条数据:" + PageUtils.getTalcount());
		System.out.println("共几页:" + PageUtils.getTalpage());
	}

	// 获取所有记录总数
	private static int getAllCount() {
		return 10;
	}
}
Global site tag (gtag.js) - Google Analytics