// 分页工具类
package com.test.entity;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
public class PageParas {
/** 页面起始记录数 */
private Integer startPoint;
/** 每页显示记录数 */
private Integer pageCount;
/** 全部记录总数 */
private Integer allCount;
/** 请求action地址 */
private String actionUrl;
/** 参数map */
private Map paraMap;
/** 是否有下一页 */
private Boolean haveNextPage;
/** 是否显示 */
private Boolean haveDisplay;
/**
* 实例化,根据request请求对象初始化参数
* @param request 请求对象
*/
public PageParas(HttpServletRequest request){
paraMap=new HashMap();
Set<String> setKey = request.getParameterMap().keySet();
for(String key:setKey) {
paraMap.put(key, request.getParameter(key));
}
if(paraMap.get("startPoint")!=null){
startPoint=Integer.parseInt(paraMap.get("startPoint").toString());
}else{
startPoint=0;
}
if(paraMap.get("pageCount")!=null){
pageCount=Integer.parseInt(paraMap.get("pageCount").toString());
}else{
pageCount=0;
}
if(paraMap.get("allCount")!=null){
allCount=Integer.parseInt(paraMap.get("allCount").toString());
}else{
allCount=0;
}
if(paraMap.get("actionUrl")!=null){
actionUrl=String.valueOf(paraMap.get("actionUrl"));
}else{
actionUrl="";
}
haveNextPage=false;
haveDisplay=true;
}
/**
* 实例化,根据request请求对象初始化参数
* @param request 请求对象
*/
public PageParas(HttpServletRequest request,int index){
paraMap=new HashMap();
Set<String> setKey = request.getParameterMap().keySet();
for(String key:setKey) {
paraMap.put(key, request.getParameter(key));
}
if(index>0){
if(paraMap.get("ind$"+index+"startPoint")!=null){
startPoint=Integer.parseInt(paraMap.get("ind$"+index+"startPoint").toString());
}else{
startPoint=0;
}
if(paraMap.get("ind$"+index+"pageCount")!=null){
pageCount=Integer.parseInt(paraMap.get("ind$"+index+"pageCount").toString());
}else{
pageCount=0;
}
if(paraMap.get("ind$"+index+"allCount")!=null){
allCount=Integer.parseInt(paraMap.get("ind$"+index+"allCount").toString());
}else{
allCount=0;
}
if(paraMap.get("ind$"+index+"actionUrl")!=null){
actionUrl=String.valueOf(paraMap.get("ind$"+index+"actionUrl"));
}else{
actionUrl="";
}
}else{
if(paraMap.get("startPoint")!=null){
startPoint=Integer.parseInt(paraMap.get("startPoint").toString());
}else{
startPoint=0;
}
if(paraMap.get("pageCount")!=null){
pageCount=Integer.parseInt(paraMap.get("pageCount").toString());
}else{
pageCount=0;
}
if(paraMap.get("allCount")!=null){
allCount=Integer.parseInt(paraMap.get("allCount").toString());
}else{
allCount=0;
}
if(paraMap.get("actionUrl")!=null){
actionUrl=String.valueOf(paraMap.get("actionUrl"));
}else{
actionUrl="";
}
}
haveNextPage=false;
haveDisplay=true;
}
/**
* 实例化,根据传入参数、request请求对象初始化参数
* @param sPoint 页面起始记录数
* @param pCount 每页显示记录数
* @param aCount 全部记录总数
* @param aUrl 请求action地址
* @param request 请求对象
*/
public PageParas(Integer sPoint,Integer pCount,Integer aCount,String aUrl,HttpServletRequest request){
startPoint=sPoint;
pageCount=pCount;
allCount=aCount;
actionUrl=aUrl;
haveNextPage=false;
haveDisplay=true;
paraMap=new HashMap();
Set<String> setKey = request.getParameterMap().keySet();
for(String key:setKey) {
paraMap.put(key, request.getParameter(key));
}
}
/** getter&setter start */
public Integer getStartPoint() {
return startPoint;
}
public void setStartPoint(Integer startPoint) {
this.startPoint = startPoint;
}
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public Integer getAllCount() {
return allCount;
}
public void setAllCount(Integer allCount) {
this.allCount = allCount;
}
public String getActionUrl() {
return actionUrl;
}
public void setActionUrl(String actionUrl) {
this.actionUrl = actionUrl;
}
public Map getParaMap() {
return paraMap;
}
public void setParaMap(Map paraMap) {
this.paraMap = paraMap;
}
public Boolean getHaveNextPage() {
return haveNextPage;
}
public void setHaveNextPage(Boolean haveNextPage) {
this.haveNextPage = haveNextPage;
}
public Boolean getHaveDisplay() {
return haveDisplay;
}
public void setHaveDisplay(Boolean haveDisplay) {
this.haveDisplay = haveDisplay;
}
/** getter&setter end */
}
------------
package com.test.util;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.springframework.ui.ModelMap;
import com.test.entity.PageParas;
public class ParameterUtil {
/** log4j日志器 */
private static Logger logger=Logger.getLogger(ParameterUtil.class);
/**
* 获取request参数值
* @param request request对象
* @param paraName 参数名
* @return
*/
public static String getReqParaValue(HttpServletRequest request,String paraName){
String paraValue="";
try{
if(request.getParameter(paraName)!=null){
paraValue=request.getParameter(paraName).trim();
}
}catch(Exception ex){
logger.debug("获取参数异常", ex);
}
return paraValue;
}
/**
* 获取request参数值(经过utf-8解码转换)
* @param request request对象
* @param paraName 参数名
* @return
*/
public static String getReqParaDecodeValue(HttpServletRequest request,String paraName){
String paraValue="";
try{
if(request.getParameter(paraName)!=null){
paraValue=URLDecoder.decode(request.getParameter(paraName), "UTF-8");
}
}catch(Exception ex){
logger.debug("获取参数异常", ex);
}
return paraValue;
}
/**
* request参数将String转换成List(以sign为List元素分割点)
* @param request request对象
* @param paraName 参数名
* @return
*/
public static ArrayList<String> getReqParaListForString(HttpServletRequest request,String paraName,String sign){
String str=getReqParaValue(request,paraName);
return getListForString(str,sign);
}
/**
* 将String分割为List(以sign为List元素分割点)
* @param str 源数据
* @param sign 分割点
* @return
*/
public static ArrayList<String> getListForString(String str,String sign){
ArrayList<String> al=new ArrayList<String>();
try{
if(str.length()>0){
if(str.lastIndexOf(sign)!=str.length()-1){
str+=sign;
}
if(str.indexOf(sign)>=0){
boolean bWhile=true;
while(bWhile){
if(str.indexOf(sign)>=0){
al.add(str.substring(0,str.indexOf(sign)).trim());
str=str.substring(str.indexOf(sign)+1);
}
if(str.trim().equals("") || str.trim().length()==0){
bWhile=false;
}
}
}else{
al.add(str);
}
}
}catch(Exception ex){}
return al;
}
/**
* 将request参数自动转换成Map对象
* @param request request对象
* @return
*/
public static Map getReqParaMap(HttpServletRequest request){
Map map=new HashMap();
Set<String> setKey = request.getParameterMap().keySet();
for(String key:setKey) {
map.put(key, getReqParaValue(request,key));
}
return map;
}
/**
* 字符串补"0"
* @param str 源字符串
* @param strLength 目标位数
* @param isLeft 是否补左,true补左 false补右
* @return
*/
public static String append0ForNum(String str, int strLength,boolean isLeft) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
if(isLeft){
sb.append("0").append(str);
}else{
sb.append(str).append("0");
}
str = sb.toString();
strLen = str.length();
}
}
return str;
}
/**
* 获取单元格内容
* @param cell
* @param c
* @return
*/
public static String getCellValue(HSSFCell cell,Class c){
String value=null;
if(cell!=null){
try{
if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
if(Double.class.equals(c)){
value=String.valueOf(cell.getNumericCellValue()).trim();
}else{
value=String.valueOf((long)cell.getNumericCellValue()).trim();
}
}else if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){
value=cell.getStringCellValue()==null?null:cell.getStringCellValue().trim();
}else{
if(Long.class.equals(c)){
value=String.valueOf((long)cell.getNumericCellValue()).trim();
}else if(Double.class.equals(c)){
value=String.valueOf(cell.getNumericCellValue()).trim();
}else{
value=cell.getStringCellValue()==null?null:cell.getStringCellValue().trim();
}
}
if(value.equals("")){
value=null;
}
}catch(Exception ex){
logger.error("获取单元格内容",ex);
value=null;
}
}
return value;
}
/**
* 判断是否为小数
* @param value
* @return
*/
public static boolean judgeDecimal(String value){
return matchRegular("([1-9]+[0-9]*|0)(\\.[\\d]+)?",value);
}
/**
* 判断是否为整数
* @param value
* @return
*/
public static boolean judgeInteger(String value){
return matchRegular("^[0-9]*$",value);
}
/**
* 验证正则表达式
* @param pattern
* @param value
* @return
*/
public static boolean matchRegular(String pattern,String value){
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(value);
return m.find();
}
/**
* 自动设置翻页需要的参数
* @param request
* @param model
*/
public static PageParas initTurnPagePara(HttpServletRequest request,ModelMap model){
PageParas pageParas=new PageParas(request);
model.put("pageParas",pageParas);
return pageParas;
}
/**
* 自动设置翻页需要的参数
* @param request
* @param model
*/
public static PageParas initTurnPagePara(HttpServletRequest request,ModelMap model,int index){
PageParas pageParas=new PageParas(request,index);
model.put("pageParas",pageParas);
return pageParas;
}
}
package com.test.entity;
import java.util.List;
/**
* 列表页面实体
*
*
* @param <T> 列表页面需要操作的实体类
*/
public class Pager<T> {
/** 查询得到的实体列表总数 */
private Integer allCount;
/** 本页需要显示实体列表 */
private List<T> entityList;
/**
* 实例化
* @param allCount 查询得到的实体列表总数
* @param entityList 本页需要显示实体列表
*/
public Pager(Integer allCount,List<T> entityList){
this.allCount=allCount;
this.entityList=entityList;
}
/** getter&setter start */
public Integer getAllCount() {
return allCount;
}
public void setAllCount(Integer allCount) {
this.allCount = allCount;
}
public List<T> getEntityList() {
return entityList;
}
public void setEntityList(List<T> entityList) {
this.entityList = entityList;
}
/** getter&setter end */
}
----------
package com.test.entity;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* Cookie工具类,封装Cookie读/写操作,主要用于记录用户翻页的每页显示记录数
*
*/
public class CookieUtil {
private static Logger logger=Logger.getLogger(CookieUtil.class);
private final static String PAGE_COUNT= "50";// 设置每页默认显示记录条数
/**
* 公共分页
* @param cookieName 页面所提交表单每页多少条input的名称
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return 返回每页多少条的值
*/
public static int cookiePageCount(String cookieName,int defaultValue,HttpServletRequest request, HttpServletResponse response) {
String cookieValue=getCookie(cookieName, request, response);
logger.info("cookieName:"+cookieName+"|cookieValue:"+cookieValue);
if(request.getParameter("pageCount")!=null && request.getParameter("pageCount").trim().length()>0){
cookieValue=request.getParameter("pageCount").trim();
}
if(cookieValue.equals(PAGE_COUNT)){
cookieValue=String.valueOf(defaultValue);
}
cookieValue=cookieHandle(cookieName, cookieValue, request, response,1);
int pageCount=Integer.parseInt(cookieValue);
return pageCount;
}
/**
* 返回每页显示多少条,如果有变动则将新值记录入Cookie和Session
* @param cookieName 页面所提交表单每页多少条input的名称
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return 返回每页多少条的值
*/
public static String cookieHandle(String cookieName,String cookieValue, HttpServletRequest request, HttpServletResponse response,int cookieType) {
logger.info("Cookie: 页面传入的cookieValue=\t"+cookieValue);
String tempcookieValue="";
if(null==cookieValue||"".equals(cookieValue)){
tempcookieValue=(String) request.getSession().getAttribute(cookieName);
if(null==tempcookieValue||"".equals(tempcookieValue)){
tempcookieValue=getCookie(cookieName,request,response);
}
}else{
tempcookieValue=cookieValue;
setCookie(cookieName,cookieValue,request,response);
}
return tempcookieValue;
}
/**
* 比较从页面获取的每页显示多少条的记录和Session中存储的是否相等 如果不相等则重置cookie,Session
* @param cookieName Cookie名字
* @param newCookieVlue 此值用来和Cookie中存储的对比,如果不同则重置Cookie和Sesion
* @param request HttpServletRequest
* @param response HttpServletResponse
*/
public static void setCookie(String cookieName, String newCookieVlue, HttpServletRequest request, HttpServletResponse response) {
// Cookie中保存的
String sessioncookieValue = (String) request.getSession().getAttribute(cookieName);
// 如果用户从新设置了每页的显示记录条数,则从新设置Cookie
if (!newCookieVlue.equals(sessioncookieValue)) {
// System.err.println("Cookie: 页面传入的cookieValue与Session中保存的不符,重置Cookie");
Cookie cookies[] = request.getCookies();
Cookie c;
for (int i = 0; i < cookies.length; i++) {
c = cookies[i];
if (c.getName().equals(cookieName)) {
logger.info("Cookie:用户从新定义了"+cookieName+"的值,删除原Cookie");
c.setPath("/");
c.setMaxAge(0);// 删除Cookie
response.addCookie(c);
}
}
// 重新设置Cookie
Cookie newCookie = new Cookie(cookieName, newCookieVlue);
newCookie.setPath("/");
newCookie.setMaxAge(3600 * 24 * 3650);// 10年有效
response.addCookie(newCookie);
// 从新存储到Session以备下次同页面提交的数值比对
request.getSession().setAttribute(cookieName, newCookieVlue);
}
logger.info("Cookie:cookieName=" + cookieName + "\tCookieVlue=" + newCookieVlue);
}
/**
* 此方法主要用于获取分页的每页显示多少条,如果没有则默认为15
* @param cookieName
* @param request
* @param response
* @return
*/
public static String getCookie(String cookieName, HttpServletRequest request, HttpServletResponse response) {
String cookieValue = "";
Cookie cookies[] = request.getCookies();
Cookie c;
for (int i = 0; i < cookies.length; i++) {
c = cookies[i];
if (c.getName().equalsIgnoreCase(cookieName)) {
cookieValue = c.getValue();
}
}
// 如果Cookie不存在,则创建Cookie并设置默认初始条数为15条
if (null == cookieValue || "".equals(cookieValue)) {
//默认每页条数
Cookie c1 = new Cookie(cookieName, PAGE_COUNT);
c1.setPath("/");
c1.setMaxAge(3600 * 24 * 3650);// 10年有效
response.addCookie(c1);
cookieValue = PAGE_COUNT;
logger.info("Cookie:不存在每页显示记录条数信息,设置为默认每页显示记录条数为\t" + cookieValue);
}
request.getSession().setAttribute(cookieName, cookieValue);
return cookieValue;
}
/**
* 此方法用于记录除分页外的其他字段到Cookie
* @param cookieName 要存入或取出的cookieValue的名字
* @param defaultValue 当Cookie中不存在时的默认值
* @param request
* @param response
* @return
*/
public static String getCookie(String cookieName,String defaultValue, HttpServletRequest request, HttpServletResponse response) {
logger.info("Cookie: CookieUtil=getCookie= 进入设置Cookie方法,如果Cookie不存在则默认值为"+defaultValue);
String tempcookieValue=(String) request.getSession().getAttribute(cookieName);
//判断Session中是否已存在,如果存在则直接返回Sessoin中的值
if(null==tempcookieValue||"".equals(tempcookieValue)){
String cookieValue = "";
Cookie cookies[] = request.getCookies();
Cookie c;
for (int i = 0; i < cookies.length; i++) {
c = cookies[i];
if (c.getName().equalsIgnoreCase(cookieName)) {
cookieValue = c.getValue();
logger.info("Cookie:取得了Cookie数据\t" + cookieValue + "\tcookieName为" + cookieName);
}
}
if (null == cookieValue || "".equals(cookieValue)) {
Cookie c2 = new Cookie(cookieName, defaultValue);
c2.setPath("/");
c2.setMaxAge(3600 * 24 * 3650);// 10年有效
response.addCookie(c2);
cookieValue = defaultValue;
logger.info("Cookie:不存在Cookie记录入默认值\t" + cookieValue);
}
logger.debug("返回"+cookieName+"对应的Cookie值为:"+cookieValue);
request.getSession().setAttribute(cookieName, cookieValue);
return cookieValue;
}else{
return tempcookieValue;
}
}
}
------
package cn.xhcf.common.exception;
import org.apache.log4j.Logger;
public class EntityValidateException extends Exception {
/** log4j日志器 */
private Logger logger=Logger.getLogger(EntityValidateException.class);
private static final long serialVersionUID = -1418335318912972789L;
/** 异常类型 */
private EntityExpType expType;
/** 异常描述 */
private String expDesc;
public EntityValidateException(EntityExpType expType,String expDesc){
this.expType=expType;
this.expDesc=expDesc;
}
@Override
public String getMessage() {
StringBuilder sbMsg=new StringBuilder();
sbMsg.append("[").append(expDesc).append("]").append(expType.getName());
logger.debug(sbMsg.toString());
return sbMsg.toString();
}
}
-------
package cn.xhcf.common.exception;
public enum EntityExpType {
LENGTH("超过限制长度",1),DATATYPE("数据类型错误",2),REQUIRED("数据不能为空",3);
private String name;
private int index;
private EntityExpType(String name,int index){
this.name=name;
this.index=index;
}
public static String getName(int index) {
for (EntityExpType e:EntityExpType.values()) {
if (e.getIndex() == index) {
return e.name;
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
-------
package cn.xhcf.common.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* 生成唯一一串字符串
* @author qinguotao
*
*/
public class UUIDUtil {
/** 循环起始数 */
private static final int START_NUM = 100;
/** 循环结束数 */
private static final int END_NUM = 999;
/** 循环变量 */
private static int LOOP_NUM = START_NUM;
/**
* 获取唯一字串
* @return
*/
public static String getGUID() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
StringBuffer buffer = new StringBuffer(sdf.format(new Date()));
if (LOOP_NUM == END_NUM){
LOOP_NUM = START_NUM;
}
buffer.append(new Integer(LOOP_NUM++).toString());
return buffer.toString();
}
public static String getCUID(){
return getUUID()+getGUID();
}
public static String getUUID(){
return UUID.randomUUID().toString().replace("-", "");
}
}
------------------
package com.test.service.impl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import com.test.entity.DbField;
import com.test.service.EntityService;
import com.test.util.EntityExpType;
import com.test.util.EntityValidateException;
import com.test.util.ParameterUtil;
import com.test.util.UUIDUtil;
/**
* 实体操作Service
*
*/
@Service("entityService")
public class EntityServiceImpl implements EntityService {
/** log4j日志器 */
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 填充实体列表(子列表)
* @param map
* @param c
* @param iSub
* @return
* @throws Exception
*/
public List fillEntityList(Map map,Class c,int iSub)throws Exception {
List<String> fieldList=null;
Field[] fields=c.getDeclaredFields();
for(Field f:fields){
if(fieldList==null){
DbField df=f.getAnnotation(DbField.class);
if(df!=null){
if(df.required() && df.uuid()==false){
if(iSub==0){
Object obj=map.get(f.getName());
if(obj!=null){
if(obj.getClass().equals(String.class)){
fieldList=new ArrayList<String>();
fieldList.add(String.valueOf(obj));
}else if(obj.getClass().equals(List.class) || obj.getClass().equals(ArrayList.class)){
fieldList=(List<String>)obj;
}
}
}else{
Object obj=map.get(f.getName()+"*"+iSub);
if(obj!=null){
if(obj.getClass().equals(String.class)){
fieldList=new ArrayList<String>();
fieldList.add(String.valueOf(obj));
}else if(obj.getClass().equals(List.class) || obj.getClass().equals(ArrayList.class)){
fieldList=(List<String>)obj;
}
}
}
}
}
}else{
break;
}
}
List objList=new ArrayList();
if(fieldList!=null){
for(String string:fieldList){
Object o=c.newInstance();
objList.add(o);
}
for(Field f:fields){
String showName=f.getName();
try{
List<String> valueList=null;
if(iSub==0){
Object obj=map.get(f.getName());
if(obj!=null){
if(obj.getClass().equals(String.class)){
valueList=new ArrayList<String>();
valueList.add(String.valueOf(obj));
}else if(obj.getClass().equals(List.class) || obj.getClass().equals(ArrayList.class)){
valueList=(List<String>)obj;
}
}
}else{
Object obj=map.get(f.getName()+"*"+iSub);
if(obj!=null){
if(obj.getClass().equals(String.class)){
valueList=new ArrayList<String>();
valueList.add(String.valueOf(obj));
}else if(obj.getClass().equals(List.class) || obj.getClass().equals(ArrayList.class)){
valueList=(List<String>)obj;
}
}
}
for(int i=0;i<objList.size();i++){
Object o=objList.get(i);
f.setAccessible(true);
DbField df=f.getAnnotation(DbField.class);
if(df!=null){
showName=df.comment();
if(df.javaType().equals("EntityList")){
f.set(o, fillEntityList(map,df.subClass(),i+1));
}else{
if(valueList!=null && valueList.size()==fieldList.size()){
String value=valueList.get(i);
if(value==null || value.trim().equals("")){
if(df.uuid()){
f.set(o,UUIDUtil.getUUID());
}else if(df.required()){
throw new EntityValidateException(EntityExpType.REQUIRED,showName);
}
}else{
value=value.trim();
if(df.maxLength()==-1 || getStrLength(value)<=df.maxLength()){
if(df.javaType().equals("Long")){
f.set(o, Long.parseLong(value));
}else if(df.javaType().equals("Double")){
f.set(o, Double.parseDouble(value));
}else if(df.javaType().equals("Date")){
f.set(o, DateUtil.dateFormat(value, df.patternDate()));
}else if(df.javaType().equals("List")){
try{
f.set(o, map.get(f.getName()));
}catch(IllegalArgumentException iaex){
List list=new ArrayList();
list.add(map.get(f.getName()));
f.set(o, list);
}
}else{
f.set(o, value);
}
}else{
throw new EntityValidateException(EntityExpType.LENGTH,showName);
}
}
}else{
if(df.uuid()){
f.set(o,UUIDUtil.getUUID());
}else if(df.required()){
throw new EntityValidateException(EntityExpType.REQUIRED,showName);
}
}
}
}
}
}catch(IllegalArgumentException iaex){
logger.error("fillEntityList异常:",iaex);
throw new EntityValidateException(EntityExpType.DATATYPE,showName);
}
}
logger.debug("objList.size:"+objList.size());
}
return objList;
}
/**
* 填充实体
* @param map 页面传过来的参数
* @param c 需要填充实体的类
* @return
* @throws Exception
*/
public Object fillEntity(Map map,Class c) throws Exception {
Object o=c.newInstance();
Field[] fields=c.getDeclaredFields();
for(Field f:fields){
String showName=f.getName();
try{
DbField df=f.getAnnotation(DbField.class);
if(df!=null){
showName=df.comment();
String value=null;
if(map.get(f.getName())!=null){
value=String.valueOf(map.get(f.getName())).trim();
}
f.setAccessible(true);
if(df.javaType().equals("EntityList")){
f.set(o, fillEntityList(map,df.subClass(),0));
}else{
if(value==null || value.trim().equals("")){
if(df.uuid()){
f.set(o,UUIDUtil.getUUID());
}else if(df.required()){
throw new EntityValidateException(EntityExpType.REQUIRED,showName);
}
}else{
value=value.trim();
if(df.maxLength()==-1 || getStrLength(value)<=df.maxLength()){
if(df.javaType().equals("Long")){
f.set(o, Long.parseLong(value));
}else if(df.javaType().equals("Double")){
f.set(o, Double.parseDouble(value));
}else if(df.javaType().equals("Date")){
f.set(o, DateUtil.dateFormat(value, df.patternDate()));
}else if(df.javaType().equals("List")){
try{
f.set(o, map.get(f.getName()));
}catch(IllegalArgumentException iaex){
List list=new ArrayList();
list.add(map.get(f.getName()));
f.set(o, list);
}
}else{
f.set(o, value);
}
}else{
throw new EntityValidateException(EntityExpType.LENGTH,showName);
}
}
}
}
}catch(IllegalArgumentException iaex){
logger.error("fillEntity异常:"+showName, iaex);
throw new EntityValidateException(EntityExpType.DATATYPE,showName);
}
}
return o;
}
/**
* 获取字符串字节长度
* @param s
* @return
*/
private int getStrLength(String s){
s = s.replaceAll("[^\\x00-\\xff]", "**");
int length = s.length();
return length;
}
/**
* 填充实体
* @param request 请求
* @param c 需要填充实体的类
* @return
* @throws Exception
*/
public Object fillEntity(HttpServletRequest request,Class c) throws Exception {
return fillEntity(fillPageMap(request,null),c);
}
/**
* 填充查询页面Map
* @param request 请求
* @return
* @throws Exception
*/
public Map<String,Object> fillQueryMap(HttpServletRequest request,ModelMap model){
return fillPageMap(request,model);
}
/**
* 填充页面Map
* @param request 请求
* @return
* @throws Exception
*/
public Map<String,Object> fillPageMap(HttpServletRequest request,ModelMap model){
Map<String,Object> pageMap=new HashMap<String,Object>();
Set<String> setKey = request.getParameterMap().keySet();
for(String key:setKey) {
String sign="$";
if(key.indexOf(".")>0){
sign=".";
}
ArrayList<String> keyList=ParameterUtil.getListForString(key, sign);
int index=0;
if(keyList.size()!=0){
index=keyList.size()-1;
}
String[] values=request.getParameterValues(key);
if(values==null || values.length==0){
pageMap.put(keyList.get(index), "");
if(model!=null){
model.put(key,"");
}
}else if(values.length>1){
if(keyList.get(index).indexOf("GTeam")>0){
StringBuilder sb=new StringBuilder();
if(keyList.get(index).indexOf("GTeamStr")>0){
for(String value:values){
sb.append("'").append(value).append("',");
}
}else{
for(String value:values){
sb.append(value).append(",");
}
}
String value=sb.toString();
value=value.substring(0, value.length()-1);
pageMap.put(keyList.get(index),value);
}else{
List<String> list=new ArrayList<String>();
for(String value:values){
list.add(value);
}
pageMap.put(keyList.get(index), list);
}
if(model!=null){
model.put(key, values);
}
}else if(values.length==1){
if(keyList.get(index).indexOf("List")>0){
List<String> list=new ArrayList<String>();
for(String value:values){
list.add(value);
}
pageMap.put(keyList.get(index), list);
if(model!=null){
model.put(key, values);
}
}else if(keyList.get(index).indexOf("Array")>0){
List<String> list=ParameterUtil.getListForString(values[0].trim(), ";");
pageMap.put(keyList.get(index).replaceAll("Array", "List"), list);
if(model!=null){
model.put(key, values[0].trim());
}
}else if(keyList.get(index).indexOf("GTeam")>0){
if(keyList.get(index).indexOf("GTeamStr")>0){
pageMap.put(keyList.get(index), "'"+values[0].trim()+"'");
}else{
pageMap.put(keyList.get(index), values[0].trim());
}
if(model!=null){
model.put(key, values);
}
}else{
pageMap.put(keyList.get(index), values[0].trim());
if(model!=null){
model.put(key, values[0].trim());
}
}
}
}
return pageMap;
}
}
------------
package com.test.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.test.entity.CookieUtil;
import com.test.entity.PageParas;
import com.test.entity.Pager;
import com.test.entity.User;
import com.test.service.EntityService;
import com.test.service.UserService;
import com.test.util.ParameterUtil;
@Controller
@RequestMapping(value="/mvc")
public class SpringTest{
@Autowired
private UserService userService;
private EntityService entityService;
@RequestMapping(value="/byby")
public String toByte(HttpSession session,HttpServletResponse response,HttpServletRequest request,ModelMap model){
model.put("message", "Hellow word ��õ�");
return "byby";
}
@RequestMapping(value="/getPerson")
public void getPerson(String name,HttpServletResponse response){
response.setContentType("text/html; charset=utf-8");
PrintWriter p;
try {
System.out.println("=========="+name);
p = response.getWriter();
p.print("Hellow:" +userService.getUser(1).getUserName()+name);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 注册信息查询
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/registerList")
public String registerList(HttpSession session,HttpServletResponse response,HttpServletRequest request,ModelMap model){
try {
// 翻页框架回调地址
String actionUrl = "/customer/registerList.do";
// 设置查询的起始位置,如果首次 ,起始位置设置为0
String startIndex = ParameterUtil.getReqParaValue(request, "startPoint");
int startPos = 0;
if (!StringUtils.isEmpty(startIndex)) {
startPos = Integer.parseInt(startIndex);
}
// 设置每页显示的记录数,并将设置的结果存放人cookie
String pageCount = ParameterUtil.getReqParaValue(request, "pageCount");
//int count = 1;
int count = CookieUtil.cookiePageCount("registerListCount", 50, request, response);
if (!StringUtils.isEmpty(pageCount)) {
count = CookieUtil.cookiePageCount("registerListCount", Integer.parseInt(pageCount), request, response);
}
/** 查询条件填充 **/
Map<String, Object> queryMap = entityService.fillQueryMap(request, model);
String storesid = ParameterUtil.getReqParaValue(request,"queryOrgId");
if(StringUtils.isNotEmpty(storesid)){
if (storesid.substring(storesid.length() - 1,storesid.length()).equals(",")) {
queryMap.put("queryOrgId", storesid.substring(0,(storesid.length() - 1)));
}
}
User user = (User) session.getAttribute("CF_USERINFO");
queryMap.put("queryRegister", "sign");
//是否展示查询条件div
String queryShowQuerys="0";
if(request.getParameterValues("queryShowQuerys")!=null){
queryShowQuerys=ParameterUtil.getReqParaValue(request,"queryShowQuerys");
}
model.put("queryShowQuerys",queryShowQuerys);
/** 分页查询结果 **/
Pager<User> pager = userService.queryUserListPage(startPos,count,queryMap);
model.put("pclist", pager.getEntityList());
//将翻页框架使用的参数回写至request参数
model.put("pageParas",new PageParas(startPos,count,pager.getAllCount(),actionUrl,request));
}catch (Exception e) {
}
return "customer/registerList";
}
}
---------
package com.test.service.impl;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.dao.UserDao;
import com.test.entity.Pager;
import com.test.entity.User;
import com.test.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
public UserDao userDao;
@Override
public User getUser(int userId) {
return userDao.selectByPrimaryKey(userId);
}
@Override
public Pager<User> queryUserListPage(int startPos, int count,Map<String, Object> queryMap) {
Integer allCount = userDao.selectUserListCount(queryMap);
List<User> list = userDao.selectUserList(queryMap,new RowBounds(startPos,count));
return new Pager<User> (allCount,list);
}
}
-------------------
<sql id="selectCustomerListFrom">
from
CRM_CUSTOMER a
left join
(select cust_id,max(create_time) updateTime from CRM_CUST_CONSULT group by cust_id) b
on a.id = b.cust_id
left join CRM_CUSTOMER_MCRM c on c.os_id = a.id
left join
CRM_CUSTOMER_GROUP cg
on a.id=cg.CUSTOMER_ID
left join
CRM_USER_GROUP u
on cg.groupid=u.groupid
left join
crm_customer_prentorguser p
on p.fm_code=u.fm_code
where 1 = 1
</sql>
<sql id="selectCustomerListWhere">
<if test="queryCustName!=null and queryCustName!=''">
and a.cust_name like '%${queryCustName}%'
</if>
<if test="id!=null and id!=''">
and a.id=#{id}
</if>
<if test="queryCustMobile !=null and queryCustMobile !=''">
and a.cust_mobile like '%${queryCustMobile}%'
</if>
<if test="queryDockSys !=null and queryDockSys !=''">
and a.dock_sys =#{queryDockSys}
</if>
<if test="queryCustGroupId !=null and queryCustGroupId !=''">
and cg.GROUPID like '%${queryCustGroupId}%'
</if>
<if test="queryRegisterDate1 !=null and queryRegisterDate1 !=''">
and to_char(a.register_date,'yyyy-mm-dd') <![CDATA[>=]]> #{queryRegisterDate1}
</if>
<if test="queryRegisterDate2 !=null and queryRegisterDate2 !=''">
and to_char(a.register_date,'yyyy-mm-dd') <![CDATA[<=]]> #{queryRegisterDate2}
</if>
<if test="queryFmName !=null and queryFmName !=''">
and p.fm_name like '%${queryFmName}%'
</if>
<if test="queryFromDelivery !=null and queryFromDelivery !=''">
and a.from_delivery =#{queryFromDelivery}
</if>
<if test="queryTeamName !=null and queryTeamName !=''">
and p.team_name like '%${queryTeamName}%'
</if>
<if test="queryTeamFmName !=null and queryTeamFmName !=''">
and p.team_fm_name like '%${queryTeamFmName}%'
</if>
<if test="queryAuthInfoDate1 !=null and queryAuthInfoDate1 !=''">
and a.validate_date <![CDATA[>=]]> to_date(#{queryAuthInfoDate1},'yyyy-mm-dd')
</if>
<if test="queryAuthInfoDate2 !=null and queryAuthInfoDate2 !=''">
and a.validate_date <![CDATA[<=]]> to_date(#{queryAuthInfoDate2},'yyyy-mm-dd')
</if>
<if test="queryInvDate1 !=null and queryInvDate1 !=''">
and a.start_inv_time <![CDATA[>=]]> to_date(#{queryInvDate1},'yyyy-mm-dd')
</if>
<if test="queryInvDate2 !=null and queryInvDate2 !=''">
and a.start_inv_time <![CDATA[<=]]> to_date(#{queryInvDate2},'yyyy-mm-dd')
</if>
<if test="queryOrgId != null and queryOrgId !=''">
and p.org_id in (${queryOrgId})
</if>
<if test="queryIsDelivery !=null and queryIsDelivery !=''">
and a.is_delivery =#{queryIsDelivery}
</if>
<if test="usertypes == 1 "> <!-- 理财经理 -->
and p.FM_CODE = #{empcode}
</if>
<if test="usertypes == 2 "> <!-- 团队经理 -->
and p.TEAM_ID = #{orgid}
</if>
<if test="usertypes == 3 "> <!-- 营业部 -->
and p.ORG_ID = #{orgid}
</if>
<if test="usertypes == 4 "> <!-- 支公司 -->
and p.SUB_COMP_ID = #{orgid}
</if>
<if test="usertypes == 5 "><!-- 分公司 -->
and p.BRANCH_COMP_ID = #{orgid}
</if>
<if test="usertypes == 6 "> <!-- 财富中心 -->
and p.FORTUNE_ID = #{orgid}
</if>
<if test="usertypes == -1 "> <!-- 其他角色 -->
and 1 != 1
</if>
<if test="queryRegister !=null and queryRegister !=''">
and a.data_state = '1'
order by a.CUST_GROUP_ID
<choose>
<when test="newUpdateOrderBy !=null and newUpdateOrderBy !=''">
,a.UPDATE_TIME
<if test="newUpdateOrderBy == 'asc'">ASC</if>
<if test="newUpdateOrderBy == 'desc'">DESC</if>
</when>
<when test="registOrderBy !=null and registOrderBy !=''">
,a.REGISTER_DATE
<if test="registOrderBy == 'asc'">ASC</if>
<if test="registOrderBy == 'desc'">DESC</if>
</when>
<otherwise>
,a.REGISTER_DATE DESC
</otherwise>
</choose>
</if>
<if test="queryAuth !=null and queryAuth !=''">
and a.data_state = '2'
order by a.CUST_GROUP_ID
<choose>
<when test="newUpdateOrderBy !=null and newUpdateOrderBy !=''">
,a.update_time
<if test="newUpdateOrderBy == 'asc'">ASC</if>
<if test="newUpdateOrderBy == 'desc'">DESC</if>
</when>
<when test="authOrderBy !=null and authOrderBy !=''">
,a.validate_date
<if test="authOrderBy == 'asc'">ASC</if>
<if test="authOrderBy == 'desc'">DESC</if>
</when>
<otherwise>
,a.validate_date DESC
</otherwise>
</choose>
</if>
<!-- 查询处理中的客户 -->
<if test="queryHanding != null and queryHanding != ''">
and a.data_state = '4'
order by a.CUST_GROUP_ID
<choose>
<when test="newUpdateOrderBy !=null and newUpdateOrderBy !=''">
,a.update_time
<if test="newUpdateOrderBy == 'asc'">ASC</if>
<if test="newUpdateOrderBy == 'desc'">DESC</if>
</when>
<when test="authOrderBy !=null and authOrderBy !=''">
,a.validate_date
<if test="authOrderBy == 'asc'">ASC</if>
<if test="authOrderBy == 'desc'">DESC</if>
</when>
<when test="invOrderBy !=null and invOrderBy !=''">
,a.first_order_date
<if test="invOrderBy == 'asc'">ASC</if>
<if test="invOrderBy == 'desc'">DESC</if>
</when>
<otherwise>
,a.first_order_date DESC
</otherwise>
</choose>
</if>
</sql>
<select id="selectCustomerList" parameterType="java.util.Map" resultType="cn.xhcf.customer.entity.CRMCustomer">
select a.ID id,
cg.GROUPID custGroupId,
a.CUST_NAME custName,
a.CUST_MOBILE custMobile,
a.DOCK_SYS dockSys,
a.REGISTER_DATE registerDate,
a.START_INV_TIME startInvTime,
a.VALIDATE_DATE validateDate,
a.TO_FREE_DATE toFreeDate,
a.CUST_SOURCE custSource,
a.CUST_ASK_CODE custAskCode,
a.CUST_USER_NAME custUserName,
a.CUST_LOGIN_NAME custLoginName,
a.CUST_CODE custCode,
p.FM_CODE fmCode,
p.FM_NAME fmName,
p.TEAM_NAME teamName,
p.TEAM_FM_CODE teamFmCode,
p.TEAM_FM_NAME teamFmName,
p.ORG_ID orgId,
p.ORG_NAME orgName,
p.SUB_COMP_ID subCompId,
p.SUB_COMP_NAME subCompName,
p.BRANCH_COMP_ID branchCompId,
p.BRANCH_COMP_NAME branchCompName,
p.FORTUNE_ID fortuneId,
p.FORTUNE_NAME fortuneName,
a.UR_NAME urName,
a.UR_RELATION urRelation,
a.UR_CARD_TYPE urCardType,
a.UR_CARD_NUMBER urCardNumber,
a.UR_MOBILE urMobile,
a.UR_PROVINCE urProvince,
a.UR_CITY urCity,
a.UR_COUNTY urCounty,
a.UR_ADDR urAddr,
a.CUST_MAIL custMail,
a.CUST_SEX custSex,
a.CUST_BIRTHDAY custBirthday,
a.CARD_TYPE cardType,
a.CARD_NUMBER cardNumber,
a.CUST_PROVINCE custProvince,
a.CUST_CITY custCity,
a.CUST_COUNTY custCounty,
a.CUST_ADDR custAddr,
a.INVEST_SUM investSum,
a.CREATE_ACT_ID createActId,
a.CREATE_TIME cardateTime,
a.UPDATE_ACT_ID updateActId,
b.updateTime,
a.DATA_STATE dataState,
a.SYNC_TYPE syncType,
a.is_delivery isDelivery,
a.org_fm_name orgFmName,
c.os_id osId,
(case c.dock_sys
when 9 then 'MCRM'
else '空'
end
) dockSys1,
( case a.cust_source
when '1' then '商超'
when '2' then '老客户介绍'
when '3' then '陌CALL'
when '4' then '客户服务节'
when '5' then '其他'
when '6' then '呼叫中心'
else '空'
end
) custSource1,
c.CREATE_TIME createTime1,
( case c.cust_sex
when '1' then '男'
when '2' then '女'
else '空'
end
) custSex1,
c.CUST_MAIL custMail1,
c.zip_code zipCode,
c.CUST_ADDR custAddr1,
c.TEAM_FM_NAME teamFmName1,
c.CUST_PROVINCE custProvince1,
c.CUST_CITY custCity1,
c.CUST_COUNTY custCounty1,
c.cust_name custName1,
c.cust_mobile custMobile1
<include refid="selectCustomerListFrom"/>
<include refid="selectCustomerListWhere"/>
</select>
<select id="selectCustomerListCount" parameterType="java.util.Map" resultType="java.lang.Integer">
select count(a.id)
<include refid="selectCustomerListFrom"/>
<include refid="selectCustomerListWhere"/>
</select>
分页实现
最新推荐文章于 2023-03-15 17:52:18 发布