获取request参数的工具类

时间:2021-01-04 08:16:44
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);
		}
	}
}