web工具类

package com.tgl.process.dao;

import java.io.Serializable;
import java.util.List;
public interface BaseDao {
	/**
	 * 查询
	 * 
	 * @param <T>
	 * @param jql
	 * @return
	 */
	public <T> List<T> query(String jql);

	/**
	 * 通过主键查询
	 * 
	 * @param <T>
	 * @param type
	 * @param id
	 * @return
	 */
	public <T> T findById(Class<T> type, Serializable id);

	/**
	 * 保存
	 * 
	 * @param <T>
	 * @param t
	 */
	public <T> void save(T t);

	/**
	 * 修改
	 * 
	 * @param <T>
	 * @param t
	 */
	public <T> void update(T t);

	/**
	 * 删除
	 * 
	 * @param <T>
	 * @param t
	 */
	public <T> void delete(T t);

	/**
	 * 
	 * @return
	 */
	public <T> T executeQuery(JpaTemplate<T> jt);
	/**
	 * 
	 * @param jt
	 * @return
	 */

	public <T> T executeUpdate(JpaTemplate<T> jt);
	/**
	 * 
	 * @param jt
	 * @return
	 */
	public <T> T executeJdbcQuery(JdbcTemplate<T> jt);
	/**
	 * 
	 * @param jt
	 * @return
	 */
	public <T> T executeJdbcUpdate(JdbcTemplate<T> jt);
	

}

 

package com.tgl.process.dao.impl;

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

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.tgl.process.dao.BaseDao;
import com.tgl.process.dao.JdbcTemplate;
import com.tgl.process.dao.JpaTemplate;

@Repository("baseDao")
public class BaseDaoImpl implements BaseDao {
	@PersistenceContext
	private EntityManager entityManager;
	@Autowired
	private EntityManagerFactory entityManagerFactory;

	@Override
	public <T> void delete(T t) {
		entityManager.remove(t);
	}

	@Override
	public <T> T findById(Class<T> type, Serializable id) {
		return entityManager.find(type, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> query(String jql) {
		return entityManager.createQuery(jql).getResultList();
	}

	@Override
	public <T> void save(T t) {
		entityManager.persist(t);
	}

	@Override
	public <T> void update(T t) {
		entityManager.merge(t);
	}

	@Override
	public <T> T executeQuery(JpaTemplate<T> jt) {
		T t = jt.execute(entityManagerFactory.createEntityManager());
		return t;
	}

	@Override
	public <T> T executeUpdate(JpaTemplate<T> jt) {	
		T t = jt.execute(entityManagerFactory.createEntityManager());
		return t;
	}

	@Override
	public <T> T executeJdbcQuery(JdbcTemplate<T> jt) {
		T t = jt.execute(entityManagerFactory.createEntityManager().unwrap(java.sql.Connection.class));
		return t;
	}

	@Override
	public <T> T executeJdbcUpdate(JdbcTemplate<T> jt) {
		T t = jt.execute(entityManagerFactory.createEntityManager().unwrap(java.sql.Connection.class));
		return t;
	}

}

 

package com.tgl.process.service;

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

public interface BaseService<T> {

	/**
	 * 查询
	 * 
	 * @param <T>
	 * @param jql
	 * @return
	 */
	public List<T> query(String jql);

	/**
	 * 通过主键查询
	 * 
	 * @param <T>
	 * @param type
	 * @param id
	 * @return
	 */
	public T findById(Class<T> type, Serializable id);

	/**
	 * 保存
	 * 
	 * @param <T>
	 * @param t
	 */
	public void save(T t);

	/**
	 * 修改
	 * 
	 * @param <T>
	 * @param t
	 */
	public void update(T t);

	/**
	 * 删除
	 * 
	 * @param <T>
	 * @param t
	 */
	public void delete(T t);
}

 

package com.tgl.process.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;

import com.tgl.process.dao.BaseDao;
import com.tgl.process.service.BaseService;

public class BaseServiceImpl<T> implements BaseService<T> {
	@Autowired
	private BaseDao baseDao;

	@Override
	public void delete(T t) {
		baseDao.delete(t);
	}

	@Override
	public T findById(Class<T> type, Serializable id) {
		return baseDao.findById(type, id);
	}

	@Override
	public List<T> query(String jql) {
		return baseDao.query(jql);
	}

	@Override
	public void save(T t) {
		baseDao.save(t);
	}

	@Override
	public void update(T t) {
		baseDao.update(t);
	}
}

 

package com.tgl.process.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

/**
 * 高级分页返回对象
 * 
 * @author 唐超
 * 
 */
@SuppressWarnings("unchecked")
public class ResultVo {
	
	private boolean success=false;
	// 当前页数
	private int pageNo = 1;
	// 一页有多少条
	private int pageSize = 10;
	// 下一页
	private int next;
	// 上一页
	private int previous;
	// 总页数
	private int totalPageSize;
	// 总条数
	private int totalCount;
	// 获取参数
	private Map paraMap = new HashMap();
	// 返回结果
	private List results=new ArrayList();
	//关联数据
	private Map linkedData;
	//可有可无从表数据
	private List manyResults ;
	// 封装返回前台携带的参数
	private String paramSql;
	//外键
	private String fkId;
	//构造方法
	public ResultVo() {
		
	}
	//构造方法
	public ResultVo(HttpServletRequest requset) {
		this.setParaMap(requset);
	}
	//构造方法
	public ResultVo(HttpServletRequest requset,String fkId) {
		this.setParaMap(requset);
		this.fkId=fkId;
	}
	
	
	//返回是否成功
	public boolean isSuccess() {
		return success;
	}
	//设置是否成功
	public void setSuccess(boolean success) {
		this.success = success;
	}
	//获取当前页数
	public int getPageNo() {
		return pageNo;
	}
	//获取分页大小
	public int getPageSize() {
		return pageSize;
	}
	//获取当前下一页
	public int getNext() {
		next = pageNo >= totalPageSize ? totalPageSize : pageNo + 1;
		return next;
	}
	//获取分页的总页数
	public int getTotalPageSize() {
		if (totalCount % pageSize == 0) {
			totalPageSize = totalCount / pageSize;
		} else {
			totalPageSize = totalCount / pageSize + 1;
		}
		return totalPageSize;
	}
	//获取当前下页
	public int getPrevious() {
		previous = pageNo > 1 ? pageNo - 1 : 1;
		return previous;
	}
	//获取当前总条数
	public int getTotalCount() {
		return totalCount;
	}
	//获取当前结果集
	public List getResults() {
		return results;
	}
	//设置当前结果集
	public void setResults(List results) {
		this.results = results;
	}
	//返回超链接参数
	public String getParamSql() {
		return paramSql;
	}
	//返回备份数据
	public Map getParaMap() {
		return paraMap;
	}
	//设置当前页数
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}
	//设置当前分页大小
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	//设置当前总条数
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
		getTotalPageSize();
		getNext();
		getPrevious();

	}
	//获取可有可无从表数据
	public List getManyResults() {
		return manyResults;
	}
	//设置可有可无从表数据
	public void setManyResults(List manyResults) {
		this.manyResults = manyResults;
	}
	//获取外键
	public String getFkId() {
		return fkId;
	}
	//设置外键
	public void setFkId(String fkId) {
		this.fkId = fkId;
	}

	// 获取关联数据
	public Map getLinkedData() {
		if (this.linkedData == null) {
			this.linkedData = new HashMap();
		}
		return this.linkedData;
	}
	
	//前台设置参数
	public void setParaMap(HttpServletRequest requset) {
		Map<String, String[]> reqMap = requset.getParameterMap();
		if (reqMap.containsKey("pageNo")) {
			this.pageNo = Integer.parseInt(reqMap.get("pageNo")[0].toString());
		}
		if (reqMap.containsKey("pageSize")) {
			this.pageSize = Integer.parseInt(reqMap.get("pageSize")[0].toString());
		}
		StringBuffer sb = new StringBuffer();
		int n = 1;
		for (String key : reqMap.keySet()) {
			if (!"pageNo".equals(key) && !"pageSize".equals(key)) {
				n = reqMap.get(key).length;
				if (n == 1) {
					this.paraMap.put(key, reqMap.get(key)[0]);
				} else {
					for (int i = 0; i < n; i++) {
						sb.append(reqMap.get(key)[i] + ",");
					}
					sb.delete(sb.length() - 1, sb.length());
					this.paraMap.put(key, sb.toString());
					sb.delete(0, sb.length());
				}
			}
		}
		for (Object param : this.paraMap.keySet()) {
			sb.append(param.toString() + "=" + this.paraMap.get(param) + "&");
		}
		if (sb.length() > 0) {
			sb.delete(sb.length() - 1, sb.length());
		}
		this.paramSql = sb.toString();
		this.paraMap.put("startNum", ((this.pageNo - 1) * this.pageSize)+1);
		this.paraMap.put("endNum", this.pageSize * this.pageNo);
	}
	
	//设置数据库的分页参数
	public void setDataBase() {
		this.paraMap.put("startNum", ((this.pageNo - 1) * this.pageSize)+1);
		this.paraMap.put("endNum", this.pageSize * this.pageNo);
	}
	//输出json
	public void toJson(HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		JsonUtil.toMap(this, resp.getWriter());
	}
}

 

package com.tgl.process.common;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("unchecked")
public class JsonUtil {
	//@JsonIgnoreProperties (value = {"urbanRoadInfo"})不输出关联对象
	private static ObjectMapper om = new ObjectMapper();

	static {
		om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
	}

	public static void setFormatYYY() {
		om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
	}

	public static void setFormatYYYSS() {
		om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	public static ObjectMapper getOm() {
		return om;
	}

	public static String toJson(Object ob) {
		try {
			return om.writeValueAsString(ob);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static List<Map> toListMap(String ob) {
		try {
			return om.readValue(ob, List.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> List<T> toListJavaBean(Class<T> type, String ob) {
		try {
			return om.readValue(ob, getCollectionType(ArrayList.class, type));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Map toMap(String ob) {
		try {
			return om.readValue(ob, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static LinkedHashMap toLinkedHashMap(String ob) {
		try {
			return om.readValue(ob, LinkedHashMap.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void toMap(Object ob, Writer w) {
		try {
			om.writeValue(w, ob);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void toWriter(Object ob, HttpServletResponse resp) {
		try {
			resp.setContentType("application/json;charset=UTF-8");
			resp.setCharacterEncoding("UTF-8");
			om.writeValue(resp.getWriter(), ob);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static JavaType getCollectionType(Class<?> collectionClass,Class<?>... elementClasses) {
		return om.getTypeFactory().constructParametricType(collectionClass,elementClasses);
	}

	public static void main(String[] args) {

		List<Map> map = JsonUtil
				.toListMap("[{'phone' : '','businessType' : 4,'registrationNo' : '',	'companyName' : '感觉可不能入','registeredCapital' : null,'business' : '发把附表二额二人','addresss' : '','id' : 3,	'businessTerm' : '','registeredAddress' : '',	'createDate' : '2013-08-20','legalRepresentative' : '分设备股份巴塞罗那','registrationAgency' : null}]"
						.toString().replaceAll("'", "\""));
		System.out.println(map);
	}
}

 

package com.piend.tongzhan.common;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Bean对象与Map相互转换
 * 
 * @author 唐超
 * 
 */
@SuppressWarnings("unchecked")
public class JavaBean2Map {

	public static Map<String, Object> convertBean(Object bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		Field fields[] = bean.getClass().getDeclaredFields();
		try {
			Field.setAccessible(fields, true);
			for (int i = 0; i < fields.length; i++) {
				map.put(fields[i].getName(), fields[i].get(bean));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static Object convertMap(Class<?> type, Map<String, Object> map) {
		Object ob = null;
		try {
			if (map != null && map.size() > 0) {
				ob = type.newInstance();
				Field fields[] = type.getDeclaredFields();
				Field.setAccessible(fields, true);
				for (int i = 0; i < fields.length; i++) {
					if (map.containsKey(fields[i].getName())) {
						fields[i].set(ob, map.get(fields[i].getName()));
					}
				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return ob;
	}

	public static Map convertBean1(Object bean) throws IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map returnMap = new HashMap();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo
				.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					returnMap.put(propertyName, result);
				} else {
					returnMap.put(propertyName, "");
				}
			}
		}
		return returnMap;
	}

	public static Object convertMap1(Class type, Map map)
			throws IntrospectionException, IllegalAccessException,
			InstantiationException, InvocationTargetException {
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		Object obj = type.newInstance();
		PropertyDescriptor[] propertyDescriptors = beanInfo
				.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (map.containsKey(propertyName)) {
				Object value = map.get(propertyName);
				Object[] args = new Object[1];
				args[0] = value;
				descriptor.getWriteMethod().invoke(obj, args);
			}
		}
		return obj;
	}
}

 

package com.piend.tongzhan.common;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.piend.tongzhan.common.util.JsonUtil;

@SuppressWarnings("unchecked")
public class JsonVo {
	// 前台 参数开始页
	private Integer start = 0;
	// 前台 参数分页大小
	private Integer limit = 20;
	// 前台 参数
	private Map<String, Object> paraMap = new HashMap<String, Object>();
	// 返回jsonMap
	private Map<String, Object> reJson = new HashMap<String, Object>();
	// 返回数据
	private List results;
	// 返回查询的总条数
	private Integer totalCount = 0;

	public Integer getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(Integer totalCount) {
		this.totalCount = totalCount;
	}

	public List getResults() {
		return results;
	}

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

	public Map<String, Object> getParaMap() {
		return paraMap;
	}

	public void setParaMap(HttpServletRequest requset) {
		Map<String, Object[]> reqMap = requset.getParameterMap();
		if (reqMap.containsKey("start")) {
			this.start = Integer.parseInt(reqMap.get("start")[0].toString());
		}
		if (reqMap.containsKey("limit")) {
			this.limit = Integer.parseInt(reqMap.get("limit")[0].toString());
		}
		StringBuilder sb = new StringBuilder();
		int n = 1;
		for (String key : reqMap.keySet()) {
			n = reqMap.get(key).length;
			if (n == 1) {
				this.paraMap.put(key, reqMap.get(key)[0]);
			} else {
				for (int i = 0; i < n; i++) {
					sb.append(reqMap.get(key)[i] + ",");
				}
				sb.delete(sb.length() - 1, sb.length());
				this.paraMap.put(key, sb.toString());
				sb.delete(0, sb.length());
			}

		}
		if (sb.length() > 0) {
			sb.delete(0, sb.length());
		}
		this.paraMap.remove("start");
		this.paraMap.remove("limit");

		this.paraMap.put("firstResult", this.start);
		this.paraMap.put("maxResults", this.limit);
	}

	public void toJson(HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		reJson.put("totalCount", this.totalCount);
		reJson.put("success", true);
		reJson.put("results", this.results);
		JsonUtil.toMap(this.reJson, resp.getWriter());
	}

	@Override
	public String toString() {
		reJson.put("totalCount", this.totalCount);
		reJson.put("success", true);
		reJson.put("results", this.results);
		return JsonUtil.toJson(this.reJson);
	}

}

 

public boolean saveOrUpdateBathSql(List<String> excuteUpdateSql) {
		boolean flag = false;
		java.sql.Statement st = null;
		try {
			conn.setAutoCommit(false);
			st = conn.createStatement();
			if (excuteUpdateSql.size() > 0) {
				for (int i = 0; i < excuteUpdateSql.size(); i++) {
					st.addBatch(excuteUpdateSql.get(i));
				}
			}
			st.executeBatch();
			conn.commit();
			conn.setAutoCommit(true);
			flag = true;
			return flag;
		} catch (SQLException e) {
			System.out.println("---------------------------有出错信息-----------------------------------:");
			LoginUtil.error(logger,"Sqlite批量执行常", e.getMessage());
			try {
				if (conn != null) {
					conn.rollback();
					conn.setAutoCommit(true);
				}
			} catch (SQLException e1) {
				LoginUtil.error(logger,"Sqlite批量执行回滚异常", e1.getMessage());
			}
			return flag;
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e1) {
				LoginUtil.error(logger,"Sqlite批量执行关闭异常", e1.getMessage());
			}
		}
	}

 

你可能感兴趣的:(Web)