1. 程式人生 > >獲取request引數並通過BeanUtil進行封裝處理的參考工具類

獲取request引數並通過BeanUtil進行封裝處理的參考工具類

package cn.edu.hactcm.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import cn.edu.hactcm.domain.User;
import cn.edu.hactcm.exception.WebException;

public final class WebUtils {
	
	private WebUtils(){}
	
	public static <T> T request2Bean(HttpServletRequest request, Class<T> beanClazz) {
		
		try {
			T bean = beanClazz.newInstance();
			// TODO 要注意的是修改的資料相當於一條新的,應該把修改資訊重新建一個表。
			// TODO 在修改表中建立一個欄位,用於參照原始資料的ID,每次修改刪除原來記錄重新新增新資料
			// 看一下是否需要id‘
			if(request.getParameter("id")==null)
				BeanUtils.setProperty(bean, "id", makeUUID());
			Enumeration e = request.getParameterNames();
			while(e.hasMoreElements()) {
				String name = (String) e.nextElement();
				String value = request.getParameter(name);
				BeanUtils.setProperty(bean, name, value);
			}
			return bean;
		} catch (Exception e) {
			throw new WebException(e);
		}
	}
	
	@Deprecated
	public static <T> T request2Bean_forComment(HttpServletRequest request,
			Class<T> beanClazz) {
		try {
			T bean = beanClazz.newInstance();
			// TODO 要注意的是修改的資料相當於一條新的,應該把修改資訊重新建一個表。
			// TODO 在修改表中建立一個欄位,用於參照原始資料的ID,每次修改刪除原來記錄重新新增新資料
			// 看一下是否需要id‘
			Enumeration e = request.getParameterNames();
			while(e.hasMoreElements()) {
				String name = (String) e.nextElement();
				String value = request.getParameter(name);
				BeanUtils.setProperty(bean, name, value);
			}
			return bean;
		} catch (Exception e) {
			throw new WebException(e);
		}
	}
	
	//這裡使用了BeanUtils工具。
	public static void copyBean(Object orig, Object dest) {
		try {
			// ConvertUtils.register(new DateLocaleConverter(), Date.class);
			BeanUtils.copyProperties(dest, orig);
			BeanUtils.setProperty(dest, "id", makeUUID());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	//獲取UUID,作為各表的id的值
	public static String makeUUID() {
		return UUID.randomUUID().toString();
	}

	// 將訊息轉發給 message.jsp 全域性訊息頁面
	public static void forward(String message, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("message", message);
		request.getRequestDispatcher("/WEB-INF/hactcmmobleshop/message.jsp").forward(request, response);
	}

	public static <T>T uploadrequest2Bean(HttpServletRequest request, Class<T> beanClazz) {
		try {
			T bean = beanClazz.newInstance();
			//處理檔案上傳
			//建立工廠
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//建立檔案上傳元件
			ServletFileUpload upload = new ServletFileUpload(factory);
			if (!upload.isMultipartContent(request)) 
				throw new WebException("not a upload form");
			String id = makeUUID();    //這是phone的id
			//獲得遠端釋出手機資訊的電腦的ip
			String releaseip = request.getRemoteAddr();
			String releasetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format(new Date());
			
			String brandname = "";
			
			//新增手機新增者
			User user = (User) request.getSession().getAttribute("user");
			
			//看一看是否需要id
			if (request.getParameter("id") == null) 
				BeanUtils.setProperty(bean, "id", id);
			if (request.getParameter("releaseip") == null) 
				BeanUtils.setProperty(bean, "releaseip", releaseip);
			if (request.getParameter("releasetime") == null) 
				BeanUtils.setProperty(bean, "releasetime", releasetime);
			if (request.getParameter("userid") == null) 
				BeanUtils.setProperty(bean, "userid", user.getId());
			//相將brandname屬性設定為空,最後通過查詢資料庫查出
			BeanUtils.setProperty(bean, "brandname", brandname);
			
			//解析
			List<FileItem> fileItems = upload.parseRequest(request);
			for (FileItem item : fileItems) {
				if (item.isFormField()) {
					//封裝到bean
					String name = item.getFieldName();
					String value = item.getString("utf-8");
					BeanUtils.setProperty(bean, name, value);
				} else {
					//檔案上傳元件
					String name = item.getFieldName();
					//獲得檔名
					String filename = item.getName();
					filename = filename.substring(filename.lastIndexOf("\\")+1);
					
					// TODO 要將上傳圖片打散存放在不同的目錄中,同時存的也不應該僅僅是jpg格式的
					
					// TODO 在這個系統中還有一個錯誤,那就是不登陸也可以實現所有的功能,也可以實現釋出訊息,這個待完成,得使用細粒度許可權控制
					
					
					//圖片相對於web應用的路徑
					String webPath = "/uploadphonepic/" + id + ".jpg";
					//獲得絕對路徑
					String path = request.getSession().getServletContext().getRealPath(webPath);
					System.out.println(path);
					
					File file = new File(path);
					file.getParentFile().mkdirs();	// 建立目錄
					file.createNewFile();	// 建立檔案
					
					// 上傳
					InputStream in = item.getInputStream();
					OutputStream out = new FileOutputStream(file);
					Streams.copy(in, out, true);
					
					// 刪除臨時檔案
					item.delete();
					
					// 將圖片的路徑封裝到bean
					BeanUtils.setProperty(bean, name, webPath);
				}
			}
			return bean;
		} catch (Exception e) {
			throw new WebException(e);
		}
	}
}