1. 程式人生 > >WebHelp與Util工具類

WebHelp與Util工具類

恩,本人很久沒有寫關於技術問題的文章了,因為本人水平不高,難寫出出色的文章了,最近老師讓我們做一個小型的oa系統,自己也寫了兩個工具類,拿來與大家分享下

 有不足的地方望各位高手指正

WebHelp 主要用與Servlet中

Util 主要用於Dao中

下面是原始碼:

package com.aiy.util;

/**
 * @author aiyanbo
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

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

public class WebHelp {
	public static final String DIR="WEB-INF/jsp/";
	public static void alert(HttpServletResponse response,String content,String url){
		try {
			PrintWriter out=response.getWriter();
			out.print("<script>");
			out.print("alert('"+content+"');");
			out.print("location='"+url+"'");
			out.print("</script>");
		} catch (IOException e) {
			System.err.print("alert()方法中有錯誤");
			e.printStackTrace();
		}
	}
	public static void alert(HttpServletResponse response,String content){
		try {
			PrintWriter out=response.getWriter();
			out.print("<script>");
			out.print("alert('"+content+"');");
			out.print("</script>");
		} catch (IOException e) {
			System.err.print("alert()方法中有錯誤");
			e.printStackTrace();
		}
	}
                //根據pojo類與request引數生成pojo物件
	public static <T> T getObject(Class c,HttpServletRequest request) throws Exception{
		T o=(T) c.newInstance();
		Set<String> set=request.getParameterMap().keySet();
		Field[] cfs=c.getDeclaredFields();
		for (String str : set) {
			for (Field field : cfs) {
				if(str.equals(field.getName())){
					setObject(c, request, o, str);
					break;
				}
			}

		}
		return o;
	}
	private static <T> void setObject(Class c, HttpServletRequest request, T o,
			String str) throws NoSuchFieldException, NoSuchMethodException,
			ParseException, IllegalAccessException, InvocationTargetException {
		Field f=c.getDeclaredField(str);
		String cname=f.getType().getSimpleName();
		String fname=str.substring(0,1).toUpperCase()+str.substring(1);
		Method m=c.getDeclaredMethod("set"+fname, f.getType());
		if(cname.equals("Date")){
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd 00:00:00");
			Date date=format.parse(request.getParameter(str));
			m.invoke(o, date);
		}else if(cname.equals("int")){
			int i=Integer.parseInt(bool(request.getParameter(str)));
			m.invoke(o, i);
		}else if(cname.equals("Long")){
			Long l=Long.parseLong(bool(request.getParameter(str)));
			m.invoke(o, l);
		}else {
			m.invoke(o, request.getParameter(str));
		}
	}
	private static String bool(String str){
		return str.equals("1")?"1":"0";
	}
	public static void forword(HttpServletRequest request,HttpServletResponse response,String url) throws ServletException, IOException{
		request.getRequestDispatcher(url).forward(request, response);
	}
	public static int parseInt(HttpServletRequest request,String param,int def){
		String istr=request.getParameter(param);
		return istr==null?def:Integer.parseInt(istr);
	}
	public static int parseInt(HttpServletRequest request,String param){
		return WebHelp.parseInt(request, param, 0);
	}
	public static Long parseLong(HttpServletRequest request,String param,Long def){
		String lstr=request.getParameter(param);
		return lstr==null?def:Long.parseLong(lstr);
	}
	public static Long parseLong(HttpServletRequest request,String param){
		return parseLong(request,param,0L);
	}
	public static int[] parseIntArray(HttpServletRequest request,String param,String split){
		String p=request.getParameter(param);
		return Util.parseIntArray(p, split);
	}
	public static String[] parseStringArray(HttpServletRequest request,String param,String split){
		String p=request.getParameter(param);
		return Util.parseStringArray(p, split);
	}
	public static Long[] parseLongArray(HttpServletRequest request,String param,String split){
		String p=request.getParameter(param);
		return Util.parseLongArray(p, split);
	}
	public static <T> Set<T> parseObjectSet(HttpServletRequest request,String param,String split,Class c,String idcolumn) throws Exception{
		String p=request.getParameter(param);
		String[] arr=Util.parseStringArray(p, split);
		Set<T> set=new HashSet<T>();
		String setname="set"+idcolumn.substring(0,1).toUpperCase()+idcolumn.substring(1);
		try {
			Method setter=c.getDeclaredMethod(setname, c.getDeclaredField(idcolumn).getType());
			for (String str : arr) {
				T o=(T) c.newInstance();
				setter.invoke(o, str);
				set.add(o);
			}
		} catch (Exception e) {
			System.err.println("parseObjectSet方法有錯誤,可能是您的引數型別不正確!");
			e.printStackTrace();
			throw e;
		} 
		return set; 
	}
}
package com.aiy.util;

/**
 * @author aiyanbo
 */
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import net.sf.json.JsonConfig;

public class Util {
	public static String toWhere(String column,String...arr){
		StringBuffer sb=new StringBuffer(" where "+column+" in (");
		for(String str : arr){
			sb.append("'"+str+"'"+',');
		}
		sb.setCharAt(sb.length()-1, ')');
		return sb.toString();
	}
                //json的配置,轉換中包含的欄位
	public static JsonConfig setIncludes(Class c,String...p){
		JsonConfig config=new JsonConfig();
		Set<String> set=null;
		if(p!=null){
			Field[] fs=c.getDeclaredFields();
			set=new HashSet<String>();
			for (Field f : fs) {
				set.add(f.getName());
			}
			for(String str : p){
				set.remove(str);
			}
		}
		String[] str=new String[set.size()];
		config.setExcludes(set.toArray(str));
		return config;
	}
	public static String[] parseStringArray(String p,String split){
		return p.split(split);
	}
	public static int[] parseIntArray(String p,String split){
		String[] str=p.split(split);
		int[] arr=new int[str.length];
		for (int i = 0; i < str.length; i++) {
			arr[i]=Integer.parseInt(str[i]);
		}
		return arr;
	}
	public static Long[] parseLongArray(String p,String split){
		String[] str=p.split(split);
		Long[] arr=new Long[str.length];
		for (int i = 0; i < str.length; i++) {
			arr[i]=Long.parseLong(str[i]);
		}
		return arr;
	}
	public static String dateToString(String fmt,Date date){
		SimpleDateFormat format=new SimpleDateFormat(fmt);
		return format.format(date);
	}
	public static Date stringToDate(String fmt,String source){
		SimpleDateFormat format=new SimpleDateFormat(fmt);
		try {
			return format.parse(source);
		} catch (ParseException e) {
			System.err.println("日期格式不正確");
			e.printStackTrace();
			return null;
		}
	}
}