Java 源代码

wangfy 贡献于2013-11-26

作者 Windows 用户  创建于2013-07-05 06:03:00   修改者Windows 用户  修改于2013-07-05 06:44:00字数135281

文档摘要:Java 源代码
关键词:

第 页 /共 172页 /** * 动态拼装sql 修改用户前的查询 * @param o * @param className * @param flag * @return */ public String getHqlEditer(Object o) { String className=o.getClass().getSimpleName();//.getName(); String hql="from "+className+" where 1=1"; if(o!=null) { Field [] fields = o.getClass().getDeclaredFields(); for(int i=0;i */ public List findByFilter(Map filter) { return dao.findByFilter(filter); } /** * 通过示例查询 QBE * * @param entity * @return List */ public List findByExample(E entity) { 第 页 /共 172页 return dao.findByExample(entity); } /** * 通过Map filter 、查询 * * @param Map * filter * @param int * pageSize * @param int * startRow * @return List */ public List findByFilter(Map filter, int pageSize, int startRow) { return dao.findByFilter(filter, pageSize, startRow); } /** * 合并 * * @param entity * @return */ public E merge(E entity) { return dao.merge(entity); } /** * 判断对象某些属性的值在数据库中是否唯一. * * @param uniquePropertyNames * 在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password" */ 第 页 /共 172页 public boolean isUnique(E entity, String uniquePropertyNames) { return dao.isUnique(entity, uniquePropertyNames); } /** * 取得对象的主键值,辅助函数. */ public Serializable getId(Object entity) { return dao.getId(entity); } /** * 取得对象的主键名,辅助函数. */ public String getIdName() { return dao.getIdName(); } /** * 刷新缓存 */ public void flush() { dao.flush(); } /** * 清楚缓存 */ public void clear() { dao.clear(); } public List execHqlQueryPage(String hql,Page page){ return dao.execHqlQueryPage(hql,page); 第 页 /共 172页 } public Date getSysDateTime(){ return dao.getSysDateTime(); } /** * 动态拼装sql * @param o * @param className * @param flag * @return */ public String getHql(Object o,String flag,String sort,String order) { String className=o.getClass().getSimpleName();//.getName(); String hql="from "+className+" where 1=1"; if(o!=null) { Field [] fields = o.getClass().getDeclaredFields(); for(int i=0;i getActionItemsByRoleIdFunctionId(String functionId,int userId) { String sql="select * from sys_action_items i ,sys_rel_role_action_items r where i.function_id="+functionId+" and r.role_id in (SELECT ru.role_id FROM sys_rel_user_role ru,sys_role r WHERE user_id ="+userId+" AND r.role_id=ru.role_id AND r.column_7='T') and i.action_items_id=r.action_items_id"; return (List )this.execSqlQuery(sql); } /** * 循环向上转型,获取对象的DeclaredField. * * @throws NoSuchFieldException 如果没有该Field时抛出. */ public static Field getDeclaredField(Object object, String propertyName) throws NoSuchFieldException { Assert.notNull(object); Assert.hasText(propertyName); return getDeclaredField(object.getClass(), propertyName); } /** * 循环向上转型,获取对象的DeclaredField. * 第 页 /共 172页 * @throws NoSuchFieldException 如果没有该Field时抛出. */ public static Field getDeclaredField(Class clazz, String propertyName) throws NoSuchFieldException { Assert.notNull(clazz); Assert.hasText(propertyName); for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) { try { return superClass.getDeclaredField(propertyName); } catch (NoSuchFieldException e) { // Field不在当前类定义,继续向上转型 } } throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + propertyName); } /** * 暴力获取对象变量值,忽略private,protected修饰符的限制. * * @throws NoSuchFieldException 如果没有该Field时抛出. */ public static Object forceGetProperty(Object object, String propertyName) throws NoSuchFieldException { Assert.notNull(object); Assert.hasText(propertyName); Field field = getDeclaredField(object, propertyName); boolean accessible = field.isAccessible(); field.setAccessible(true); Object result = null; try { result = field.get(object); } catch (IllegalAccessException e) { 第 页 /共 172页 logger.info("error wont' happen"); } field.setAccessible(accessible); return result; } /** * 暴力设置对象变量值,忽略private,protected修饰符的限制. * * @throws NoSuchFieldException 如果没有该Field时抛出. */ public static void forceSetProperty(Object object, String propertyName, Object newValue) throws NoSuchFieldException { Assert.notNull(object); Assert.hasText(propertyName); Field field = getDeclaredField(object, propertyName); boolean accessible = field.isAccessible(); field.setAccessible(true); try { field.set(object, newValue); } catch (IllegalAccessException e) { logger.info("Error won't happen"); } field.setAccessible(accessible); } /** * 暴力调用对象函数,忽略private,protected修饰符的限制. * * @throws NoSuchMethodException 如果没有该Method时抛出. */ public static Object invokePrivateMethod(Object object, String methodName, Object... params) throws NoSuchMethodException { Assert.notNull(object); 第 页 /共 172页 Assert.hasText(methodName); Class[] types = new Class[params.length]; for (int i = 0; i < params.length; i++) { types[i] = params[i].getClass(); } Class clazz = object.getClass(); Method method = null; for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) { try { method = superClass.getDeclaredMethod(methodName, types); break; } catch (NoSuchMethodException e) { // 方法不在当前类定义,继续向上转型 } } if (method == null) throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName); boolean accessible = method.isAccessible(); method.setAccessible(true); Object result = null; try { result = method.invoke(object, params); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } method.setAccessible(accessible); return result; } /** * 按Filed的类型取得Field列表. 第 页 /共 172页 */ public static List getFieldsByType(Object object, Class type) { List list = new ArrayList(); Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { if (field.getType().isAssignableFrom(type)) { list.add(field); } } return list; } /** * 按FiledName获得Field的类型. */ public static Class getPropertyType(Class type, String name) throws NoSuchFieldException { return getDeclaredField(type, name).getType(); } /** * 获得field的getter函数名称. */ public static String getGetterName(Class type, String fieldName) { Assert.notNull(type, "Type required"); Assert.hasText(fieldName, "FieldName required"); if (type.getName().equals("boolean")) { return "is" + StringUtils.capitalize(fieldName); } else { return "get" + StringUtils.capitalize(fieldName); } } /** * 获得field的getter函数,如果找不到该方法,返回null. 第 页 /共 172页 */ public static Method getGetterMethod(Class type, String fieldName) { try { return type.getMethod(getGetterName(type, fieldName)); } catch (NoSuchMethodException e) { logger.error(e.getMessage(), e); } return null; } public static String getPrimaryKey() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String nowTime = sdf.format(date); int i = (int)(Math.random()*999)+100; return nowTime+String.valueOf(i); } public static void main(String [] str) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String nowTime = sdf.format(date); int i = (int)(Math.random()*999)+100; System.out.println(nowTime+String.valueOf(i)); } /** * 信息转换成json格式 * @param message * @param success 第 页 /共 172页 * @return */ public static JSONObject messageToJSON(String message, boolean success) { Map map = new HashMap(); map.put("success", success); map.put("message", message); return JSONObject.fromObject(map); } public static JSONObject objectToJSON(Object obj){ return JSONObject.fromObject(obj, registerType()); } public static JSONObject objectToJSONDict(Object obj){ return JSONObject.fromObject(obj, registerTypeDict()); } public static JSONObject objectToJSONF(Object obj){ return JSONObject.fromObject(obj, registerTypeUnit()); } /** * list转换成JSON * @param list * @return */ public static JSONArray listToJSON(List list){ return JSONArray.fromObject(list,registerType()); } public static JSONArray listToJSONUnit(List list){ return JSONArray.fromObject(list,registerTypeUnit()); } 第 页 /共 172页 /** * 针对easyui控件的list转换成JSON * @param list * @return */ public static JSONObject listToJSONForEasyUI(List list){ Map map = new HashMap(); map.put("total", list.size()); map.put("rows", list); return JSONObject.fromObject(map,registerType()); } /** * 针对easyui控件的list转换成JSON 有过滤单位 * @param list * @return */ public static JSONObject listToJSONForEasyUI(Long count,List list){ Map map = new HashMap(); map.put("total", count); map.put("rows", list); return JSONObject.fromObject(map,registerType()); } /*** * 针对树形结构生成的JSON * @param list * @return */ public static JSONObject listToJSONForTree(List list) { Map map = new HashMap(); 第 页 /共 172页 map.put("tree", list); return JSONObject.fromObject(map,registerTypeDict()); } /** * 针对easyui控件的list转换成JSON * @param list * @return */ public static JSONObject listToJSONForEasyUIUnit(Long count,List list){ Map map = new HashMap(); map.put("total", count); map.put("rows", list); return JSONObject.fromObject(map,registerTypeUnit()); } public static JSONObject listToJSONForEasyUIUser(Long count,List list){ Map map = new HashMap(); map.put("total", count); map.put("rows", list); return JSONObject.fromObject(map,registerTypeUser()); } /** * 针对easyui控件的list转换成JSON * @param list * @return */ public static JSONObject listToJSONForEasyUIDict(Long count,List list){ Map map = new HashMap(); map.put("total", count); map.put("rows", list); return JSONObject.fromObject(map,registerTypeDict()); } 第 页 /共 172页 /** * 针对easyui控件的list转换成JSON * @param list * @return */ public static JSONObject listToJSONForEasyUIDict(List list){ Map map = new HashMap(); map.put("rows", list); return JSONObject.fromObject(map,registerTypeDict()); } /** * 注册类型 * @param clazz * @return */ private static JsonConfig registerType(){ JsonConfig jsonConfig = new JsonConfig(); //过滤单位 jsonConfig.setJsonPropertyFilter(new PropertyFilter(){ public boolean apply(Object source, String name, Object value) { if( name.equals("proxyUnit") || name.equals("creator") || name.equals("updator")) { return true; } else { return false; } } }); jsonConfig.registerJsonValueProcessor(Date.class, new CustomJsonValueProcessor()); return jsonConfig; } /** * 注册类型 第 页 /共 172页 * @param clazz * @return */ private static JsonConfig registerTypeDict(){ JsonConfig jsonConfig = new JsonConfig(); //过滤单位 jsonConfig.setJsonPropertyFilter(new PropertyFilter(){ public boolean apply(Object source, String name, Object value) { if(name.equals("creator")) { return true; } else { return false; } } }); jsonConfig.registerJsonValueProcessor(Date.class, new CustomJsonValueProcessor()); return jsonConfig; } /** * 注册类型 * @param clazz * @return */ private static JsonConfig registerTypeUnit(){ JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new CustomJsonValueProcessor()); return jsonConfig; } private static JsonConfig registerTypeUser(){ JsonConfig jsonConfig = new JsonConfig(); //过滤单位 jsonConfig.setJsonPropertyFilter(new PropertyFilter(){ public boolean apply(Object source, String name, Object value) { 第 页 /共 172页 if(name.equals("proxyUnit") || name.equals("creator") || name.equals("updator")) { return true; } else { return false; } } }); jsonConfig.registerJsonValueProcessor(Date.class, new CustomJsonValueProcessor()); return jsonConfig; } } class CustomJsonValueProcessor implements JsonValueProcessor { public static final String Default_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value); } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { return process(value); } private Object process(Object value) { if(value != null){ if(value instanceof Date){ DateFormat dateFormat; try { dateFormat = new SimpleDateFormat(Default_DATE_PATTERN); } catch (Exception e) { dateFormat = new SimpleDateFormat(Default_DATE_PATTERN); } 第 页 /共 172页 return dateFormat.format((Date) value); }else return value; }else return value; } /** * 向前台打印JSON对象 * @param respone * @param jsonStr */ public static void printJSON(HttpServletResponse respone,String jsonStr){ printJSON(respone,jsonStr); } /** * 向前台打印JSON对象 * @param respone * @param jsonStr */ public static void printJSON(HttpServletResponse respone,Object jsonObject){ PrintWriter writer = null; try { respone.setContentType("application/json; charset=UTF-8"); writer = respone.getWriter(); writer.print(jsonObject); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.flush(); writer.close(); } 第 页 /共 172页 } } /** * 向前台打印文本信息 * @param respone * @param textStr */ public static void printText(HttpServletResponse respone,String textStr){ PrintWriter writer = null; try { respone.setContentType("text/html; charset=UTF-8"); writer = respone.getWriter(); writer.print(textStr); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.flush(); writer.close(); } } } private static final long serialVersionUID = 3040179406403718174L; static final int S11 = 7; static final int S12 = 12; static final int S13 = 17; static final int S14 = 22; static final int S21 = 5; static final int S22 = 9; static final int S23 = 14; static final int S24 = 20; static final int S31 = 4; static final int S32 = 11; 第 页 /共 172页 static final int S33 = 16; static final int S34 = 23; static final int S41 = 6; static final int S42 = 10; static final int S43 = 15; static final int S44 = 21; static final byte PADDING[] = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private long state[]; private long count[]; private byte buffer[]; public String digestHexStr; private byte digest[]; public MD5() { state = new long[4]; count = new long[2]; buffer = new byte[64]; digest = new byte[16]; md5Init(); } private void Decode(long al[], byte abyte0[], int i) { int j = 0; for (int k = 0; k < i; k += 4) { al[j] = b2iu(abyte0[k]) | b2iu(abyte0[k + 1]) << 8 | b2iu(abyte0[k + 2]) << 16 | b2iu(abyte0[k + 3]) << 24; j++; 第 页 /共 172页 } } private void Encode(byte abyte0[], long al[], int i) { int j = 0; for (int k = 0; k < i; k += 4) { abyte0[k] = (byte) (int) (al[j] & 255L); abyte0[k + 1] = (byte) (int) (al[j] >>> 8 & 255L); abyte0[k + 2] = (byte) (int) (al[j] >>> 16 & 255L); abyte0[k + 3] = (byte) (int) (al[j] >>> 24 & 255L); j++; } } private long F(long l, long l1, long l2) { return l & l1 | ~l & l2; } private long FF(long l, long l1, long l2, long l3, long l4, long l5, long l6) { l += F(l1, l2, l3) + l4 + l6; l = (int) l << (int) l5 | (int) l >>> (int) (32L - l5); l += l1; return l; } private long G(long l, long l1, long l2) { return l & l2 | l1 & ~l2; } private long GG(long l, long l1, long l2, long l3, long l4, long l5, long l6) { l += G(l1, l2, l3) + l4 + l6; 第 页 /共 172页 l = (int) l << (int) l5 | (int) l >>> (int) (32L - l5); l += l1; return l; } private long H(long l, long l1, long l2) { return l ^ l1 ^ l2; } private long HH(long l, long l1, long l2, long l3, long l4, long l5, long l6) { l += H(l1, l2, l3) + l4 + l6; l = (int) l << (int) l5 | (int) l >>> (int) (32L - l5); l += l1; return l; } private long I(long l, long l1, long l2) { return l1 ^ (l | ~l2); } private long II(long l, long l1, long l2, long l3, long l4, long l5, long l6) { l += I(l1, l2, l3) + l4 + l6; l = (int) l << (int) l5 | (int) l >>> (int) (32L - l5); l += l1; return l; } public static long b2iu(byte byte0) { return (long) (byte0 >= 0 ? byte0 : byte0 & 0xff); } public static String byteHEX(byte byte0) { char ac[] = { 第 页 /共 172页 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char ac1[] = new char[2]; ac1[0] = ac[byte0 >>> 4 & 0xf]; ac1[1] = ac[byte0 & 0xf]; String s = new String(ac1); return s; } public String getMD5ofStr(String s) { if(s==null){ return ""; }else{ md5Init(); md5Update(s.getBytes(), s.length()); md5Final(); digestHexStr = ""; for (int i = 0; i < 16; i++) { digestHexStr += byteHEX(digest[i]); } } return digestHexStr; } public static void main(String args[]) { MD5 md5 = new MD5(); System.out.println("MD5(\"123456\"):" + md5.getMD5ofStr("123456")); } private void md5Final() { byte abyte0[] = new byte[8]; Encode(abyte0, count, 8); int i = (int) (count[0] >>> 3) & 0x3f; 第 页 /共 172页 int j = i >= 56 ? 120 - i : 56 - i; md5Update(PADDING, j); md5Update(abyte0, 8); Encode(digest, state, 16); } private void md5Init() { count[0] = 0L; count[1] = 0L; state[0] = 0x67452301L; state[1] = 0xefcdab89L; state[2] = 0x98badcfeL; state[3] = 0x10325476L; } private void md5Memcpy(byte abyte0[], byte abyte1[], int i, int j, int k) { for (int l = 0; l < k; l++) { abyte0[i + l] = abyte1[j + l]; } } private void md5Transform(byte abyte0[]) { long l = state[0]; long l1 = state[1]; long l2 = state[2]; long l3 = state[3]; long al[] = new long[16]; Decode(al, abyte0, 64); l = FF(l, l1, l2, l3, al[0], 7L, 0xd76aa478L); l3 = FF(l3, l, l1, l2, al[1], 12L, 0xe8c7b756L); l2 = FF(l2, l3, l, l1, al[2], 17L, 0x242070dbL); l1 = FF(l1, l2, l3, l, al[3], 22L, 0xc1bdceeeL); l = FF(l, l1, l2, l3, al[4], 7L, 0xf57c0fafL); l3 = FF(l3, l, l1, l2, al[5], 12L, 0x4787c62aL); 第 页 /共 172页 l2 = FF(l2, l3, l, l1, al[6], 17L, 0xa8304613L); l1 = FF(l1, l2, l3, l, al[7], 22L, 0xfd469501L); l = FF(l, l1, l2, l3, al[8], 7L, 0x698098d8L); l3 = FF(l3, l, l1, l2, al[9], 12L, 0x8b44f7afL); l2 = FF(l2, l3, l, l1, al[10], 17L, 0xffff5bb1L); l1 = FF(l1, l2, l3, l, al[11], 22L, 0x895cd7beL); l = FF(l, l1, l2, l3, al[12], 7L, 0x6b901122L); l3 = FF(l3, l, l1, l2, al[13], 12L, 0xfd987193L); l2 = FF(l2, l3, l, l1, al[14], 17L, 0xa679438eL); l1 = FF(l1, l2, l3, l, al[15], 22L, 0x49b40821L); l = GG(l, l1, l2, l3, al[1], 5L, 0xf61e2562L); l3 = GG(l3, l, l1, l2, al[6], 9L, 0xc040b340L); l2 = GG(l2, l3, l, l1, al[11], 14L, 0x265e5a51L); l1 = GG(l1, l2, l3, l, al[0], 20L, 0xe9b6c7aaL); l = GG(l, l1, l2, l3, al[5], 5L, 0xd62f105dL); l3 = GG(l3, l, l1, l2, al[10], 9L, 0x2441453L); l2 = GG(l2, l3, l, l1, al[15], 14L, 0xd8a1e681L); l1 = GG(l1, l2, l3, l, al[4], 20L, 0xe7d3fbc8L); l = GG(l, l1, l2, l3, al[9], 5L, 0x21e1cde6L); l3 = GG(l3, l, l1, l2, al[14], 9L, 0xc33707d6L); l2 = GG(l2, l3, l, l1, al[3], 14L, 0xf4d50d87L); l1 = GG(l1, l2, l3, l, al[8], 20L, 0x455a14edL); l = GG(l, l1, l2, l3, al[13], 5L, 0xa9e3e905L); l3 = GG(l3, l, l1, l2, al[2], 9L, 0xfcefa3f8L); l2 = GG(l2, l3, l, l1, al[7], 14L, 0x676f02d9L); l1 = GG(l1, l2, l3, l, al[12], 20L, 0x8d2a4c8aL); l = HH(l, l1, l2, l3, al[5], 4L, 0xfffa3942L); l3 = HH(l3, l, l1, l2, al[8], 11L, 0x8771f681L); l2 = HH(l2, l3, l, l1, al[11], 16L, 0x6d9d6122L); l1 = HH(l1, l2, l3, l, al[14], 23L, 0xfde5380cL); l = HH(l, l1, l2, l3, al[1], 4L, 0xa4beea44L); l3 = HH(l3, l, l1, l2, al[4], 11L, 0x4bdecfa9L); l2 = HH(l2, l3, l, l1, al[7], 16L, 0xf6bb4b60L); l1 = HH(l1, l2, l3, l, al[10], 23L, 0xbebfbc70L); l = HH(l, l1, l2, l3, al[13], 4L, 0x289b7ec6L); 第 页 /共 172页 l3 = HH(l3, l, l1, l2, al[0], 11L, 0xeaa127faL); l2 = HH(l2, l3, l, l1, al[3], 16L, 0xd4ef3085L); l1 = HH(l1, l2, l3, l, al[6], 23L, 0x4881d05L); l = HH(l, l1, l2, l3, al[9], 4L, 0xd9d4d039L); l3 = HH(l3, l, l1, l2, al[12], 11L, 0xe6db99e5L); l2 = HH(l2, l3, l, l1, al[15], 16L, 0x1fa27cf8L); l1 = HH(l1, l2, l3, l, al[2], 23L, 0xc4ac5665L); l = II(l, l1, l2, l3, al[0], 6L, 0xf4292244L); l3 = II(l3, l, l1, l2, al[7], 10L, 0x432aff97L); l2 = II(l2, l3, l, l1, al[14], 15L, 0xab9423a7L); l1 = II(l1, l2, l3, l, al[5], 21L, 0xfc93a039L); l = II(l, l1, l2, l3, al[12], 6L, 0x655b59c3L); l3 = II(l3, l, l1, l2, al[3], 10L, 0x8f0ccc92L); l2 = II(l2, l3, l, l1, al[10], 15L, 0xffeff47dL); l1 = II(l1, l2, l3, l, al[1], 21L, 0x85845dd1L); l = II(l, l1, l2, l3, al[8], 6L, 0x6fa87e4fL); l3 = II(l3, l, l1, l2, al[15], 10L, 0xfe2ce6e0L); l2 = II(l2, l3, l, l1, al[6], 15L, 0xa3014314L); l1 = II(l1, l2, l3, l, al[13], 21L, 0x4e0811a1L); l = II(l, l1, l2, l3, al[4], 6L, 0xf7537e82L); l3 = II(l3, l, l1, l2, al[11], 10L, 0xbd3af235L); l2 = II(l2, l3, l, l1, al[2], 15L, 0x2ad7d2bbL); l1 = II(l1, l2, l3, l, al[9], 21L, 0xeb86d391L); state[0] += l; state[1] += l1; state[2] += l2; state[3] += l3; } private void md5Update(byte abyte0[], int i) { byte abyte1[] = new byte[64]; int k = (int) (count[0] >>> 3) & 0x3f; if ((count[0] += i << 3) < (long) (i << 3)) { count[1]++; } 第 页 /共 172页 count[1] += i >>> 29; int l = 64 - k; int j; if (i >= l) { md5Memcpy(buffer, abyte0, k, 0, l); md5Transform(buffer); for (j = l; j + 63 < i; j += 64) { md5Memcpy(abyte1, abyte0, 0, j, 64); md5Transform(abyte1); } k = 0; } else { j = 0; } md5Memcpy(buffer, abyte0, k, j, i - j); } /** * 字符串转化成日期时间 * * @param sDatetime * 要转化的字符串 * @return 日期时间 */ public static Date strToDateTime(String sDatetime) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); java.util.Date dateTemp = new Date(); try { dateTemp = df.parse(sDatetime); } catch (ParseException e) { e.printStackTrace(); } java.sql.Date date = new java.sql.Date(dateTemp.getTime()); java.util.Date sysDateTime = new java.sql.Timestamp(date.getTime()); 第 页 /共 172页 return sysDateTime; } /** * 用于将字符串数组组成用逗号分隔的字符串 * * @param strs * 字符串数组 * @return 字符串 */ public static String ToStr(String[] strs) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < strs.length; i++) { sb.append(strs[i]); sb.append(","); } sb.deleteCharAt(sb.lastIndexOf(",")); return sb.toString(); } /** * 用于将字符串数组组成用‘-’分隔的字符串 * * @param strs * 字符串数组 * @return 字符串 */ public static String ToChain(String[] strs) { StringBuffer sb = new StringBuffer(); if (strs.length > 0) { sb.append(strs[0]); for (int i = 1; i < strs.length; i++) { if (null == strs[i] || "".equals(strs[i])) break; 第 页 /共 172页 else { sb.append("-"); sb.append(strs[i]); } } } return sb.toString(); } /** * 用于将字符串数组组成用逗号分隔并且带单引号的字符串 * * @param strs * @return */ public static String ToStrChar(String[] strs) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < strs.length; i++) { sb.append("'"); sb.append(strs[i]); sb.append("',"); } sb.deleteCharAt(sb.lastIndexOf(",")); return sb.toString(); } /** * 页面截取字符串 * * @param str * 要截取的字符串 * @param start * 开始点 * @param stop * 结束点 第 页 /共 172页 * @return */ public static String SubString(String str, int start, int stop) { return str.substring(start, stop); } /** * 四舍五入处理 * * @param v * 需要处理的数字 * @param scale * 小数点儿后位数 * @return */ public static Double Round(Double v, int scale) { BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 用于将double类型数值转换成中文大写 * * @param value * @return */ public static String RMB(double value) { char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示 char[] vunit = { '万', '亿' };// 段名表示 char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };// 数字表示 第 页 /共 172页 long midVal = (long) (value * 100);// 转化成整形 String valStr = String.valueOf(midVal); // 转化成字符串 String head = valStr.substring(0, valStr.length() - 2); // 取整数部分 String rail = valStr.substring(valStr.length() - 2);// 取小数部分 String prefix = "";// 整数部分转化的结果 String suffix = "";// 小数部分转化的结果 // 处理小数点后面的数 if (rail.equals("00")) {// 如果小数部分为0 suffix = "整"; } else { suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分";// 否则把角分转化出来 } // 处理小数点前面的数 char[] chDig = head.toCharArray();// 把整数部分转化成字符数组 char zero = '0'; // 标志'0'表示出现过0 byte zeroSerNum = 0; // 连续出现0的次数 for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字 int idx = (chDig.length - i - 1) % 4; // 取段内位置 int vidx = (chDig.length - i - 1) / 4; // 取段位置 if (chDig[i] == '0') { // 如果当前字符是0 zeroSerNum++; // 连续0次数递增 if (zero == '0') { // 标志 zero = digit[0]; } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) { prefix += vunit[vidx - 1]; zero = '0'; } continue; } zeroSerNum = 0; // 连续0次数清零 if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的 prefix += zero; zero = '0'; } 第 页 /共 172页 prefix += digit[chDig[i] - '0']; // 转化该数字表示 if (idx > 0) prefix += hunit[idx - 1]; if (idx == 0 && vidx > 0) { prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿 } } if (prefix.length() > 0) prefix += '圆'; // 如果整数部分存在,则有圆的字样 return prefix + suffix; // 返回正确表示 } /** * 得到两个时间相减的天数 * @param date1 * @param date2 * @return */ public static Integer getDay(Date date1,Date date2){ return Integer.parseInt(((date1.getTime()-date2.getTime())/1000/60/60/24)+""); } /** * * @return */ public static Double formatDouble(Double d){ DecimalFormat df = new DecimalFormat("######0.00"); return new Double (df.format(d)); } /** * 计算两个时间相差的月份数 第 页 /共 172页 * @param startdate * @param stopdate * @return */ public static Integer getMonth(Date startdate,Date stopdate){ return (12*(stopdate.getYear()-startdate.getYear())-startdate.getMonth()+stopdate.getMonth()+1); } /** * 验证权限方法的有效性 * @param intercept * @return * @throws Exception */ public Boolean visible(ActionInvocation intercept)throws Exception { flag = false; Object obj = intercept.getInvocationContext().getSession().get(Context.USER_LONGIN_SESSION); if(obj == null){ flag = true; ActionContext actionContext = intercept.getInvocationContext(); HttpServletResponse response = (HttpServletResponse)actionContext.get(ServletActionContext.HTTP_RESPONSE); PrintWriter printWriter = response.getWriter(); printWriter.write(""); printWriter.close(); return false; } //获得当前类class Class clazz = intercept.getProxy().getClass(); //获取当前请求方法名称 String methodName = intercept.getProxy().getMethod(); //获得请求方法 第 页 /共 172页 Method method = intercept.getAction().getClass().getMethod(methodName,new Class[0]); Type[] paramTypeList = method.getGenericParameterTypes();// 方法的参数列表 if(null!=method){ return true; } return false; } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); HttpSession session=request.getSession(); // 在内存中创建图象 int width=60, height=20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 //这个之后要用PublicService的相关函数进行替换 第 页 /共 172页 Random random = new Random(); // 设定背景色 g.setColor(getRandColor(200,250)); g.fillRect(0, 0, width, height); //设定字体 g.setFont(new Font("Times New Roman",Font.PLAIN,18)); //画边框 //g.setColor(new Color()); //g.drawRect(0,0,width-1,height-1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160,200)); for (int i=0;i<155;i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x,y,x+xl,y+yl); } 第 页 /共 172页 // 取随机产生的认证码(4位数字) String verifyCode = commonService.generateRandCode(4,Constance.RADOM_CER_NUM_CHAR).toUpperCase(); for (int i=0;i255) fc=255; if(bc>255) bc=255; int r=fc+random.nextInt(bc-fc); int g=fc+random.nextInt(bc-fc); int b=fc+random.nextInt(bc-fc); return new Color(r,g,b); } // public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } 第 页 /共 172页 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return "Short description"; } /** * Initialization of the servlet.
* * @throws ServletException * if an error occurs */ public void init() throws ServletException { commonService = (CommonService)this.getService("commonService"); } public boolean commit() { try { getSession().connection().commit(); return true; } catch (Exception e) { log.error(e.getMessage()); return false; } } 第 页 /共 172页 public boolean rollback() { try { getSession().connection().rollback(); return true; } catch (Exception e) { log.error(e.getMessage()); return false; } } public boolean create(E entity) { try { this.getHibernateTemplate().save(entity); return true; } catch (Exception ex) { log.error(ex.getMessage()); return false; } } public boolean evict(E entity) { try { this.getHibernateTemplate().evict(entity); return true; } catch (Exception ex) { log.error(ex.getMessage()); return false; } } 第 页 /共 172页 public List execHqlQuery(String hql) { Assert.hasText(hql); List list = getHibernateTemplate().find(hql); return list; } /** * 返回单个对象 * @param hql * @return */ public E execHqlQueryObj(final String hql) { Assert.hasText(hql); return (E)getHibernateTemplate().execute(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { // TODO Auto-generated method stub return session.createQuery(hql).uniqueResult(); } }); } public List getAllEntity() { List list= getHibernateTemplate().find( "from " + entity.getClass().getSimpleName()); return list; } public int execHql(final String hql) { return (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { 第 页 /共 172页 Query query = session.createQuery(hql); return query.executeUpdate(); } }); } public List findByFilter(Map filter) { this.criteriaFilter(criteria, filter); return criteria.list(); } public List findByFilter(Map filter, int pageSize, int startRow) { return null; } public E get(Serializable id) { return (E) this.get(entity.getClass(), id); } public E load(Serializable id){ return (E) this.load(entity.getClass(), id); } public int getTotal(Map filter) { criteriaFilter(criteria, filter); int totalCount = ((Integer) criteria.setProjection( Projections.rowCount()).uniqueResult()).intValue(); criteria.setProjection(null); return totalCount; } 第 页 /共 172页 // /* public Page pageByFilter(Map filter, int pageNo, int pageSize) { criteriaFilter(criteria, filter); return this.pagedQuery(criteria, pageNo, pageSize); }*/ public boolean delete(E entity) { try { this.getHibernateTemplate().delete(entity); return true; } catch (Exception ex) { log.error(ex.getMessage()); return false; } } public int delete(String[] ids,E entity) { StringBuffer sb = new StringBuffer(); sb.append("-1"); for (String s : ids) { sb.append("," + s); } String hql = "delete from " + entity.getClass().getSimpleName() + " where id in (" + sb.toString() + ")"; return this.execHql(hql); } public int delete(String ids,E entity) { String hql = "delete from " + entity.getClass().getSimpleName() + " where id in (" + ids + ")"; return this.execHql(hql); 第 页 /共 172页 } public boolean removeById(Serializable id) { return this.delete(this.get(id)); } public boolean save(E entity) { try { this.getHibernateTemplate().saveOrUpdate(entity); return true; } catch (Exception ex) { log.error(ex.getMessage()); return false; } } public void setAutoCommit(boolean bool) { try { getSession().connection().setAutoCommit(bool); } catch (Exception e) { log.error(e.getMessage()); } } /** * 作用针对key为"xxx_xx"的查询条件 QBC * * @param criteria * @param filter */ protected void criteriaFilter(Criteria criteria, Map filter) { try { getCriteria(); 第 页 /共 172页 if (this.resultseCount > 0) { criteria.setMaxResults(this.resultseCount); } if (filter == null) return; for (String key : filter.keySet()) { Object value = filter.get(key); String[] keys; int o = key.lastIndexOf("_"); if (o < 0) { criteria.add(Restrictions.eq(key, value)); continue; } keys = new String[2]; keys[0] = key.substring(0, o); keys[1] = key.substring(o + 1); keys[1] = keys[1].toLowerCase(); // == if ("eq".equals(keys[1])) { criteria.add(Restrictions.eq(keys[0], value)); }// != else if ("ne".equals(keys[1])) { criteria.add(Restrictions.ne(keys[0], value)); } // > else if ("gt".equals(keys[1])) { criteria.add(Restrictions.gt(keys[0], value)); }// < else if ("lt".equals(keys[1])) { criteria.add(Restrictions.lt(keys[0], value)); }// <= else if ("le".equals(keys[1])) { criteria.add(Restrictions.le(keys[0], value)); }// >= 第 页 /共 172页 else if ("ge".equals(keys[1])) { criteria.add(Restrictions.ge(keys[0], value)); }// like else if ("like".equals(keys[1])) { criteria.add(Restrictions.like(keys[0], value)); } else if ("in".equals(keys[1])) { criteria.add(Restrictions.in(keys[0], ((String) value) .split(","))); } else if ("crealias".equals(keys[1])) { criteria.createAlias(keys[0], (String) value); }// 是否为null filter.put("xxx_isnull", true); else if ("isnull".equals(keys[1]) && value != null) { if ((Boolean) value) criteria.add(Restrictions.isNull(keys[0])); else criteria.add(Restrictions.isNotNull(keys[0])); } else if ("or".equals(keys[1])) { if (value instanceof List) { List list = (List) value; Object[] values = (Object[]) list.get(0); Criterion c = null; if (values.length == 1) { c = Restrictions.or(Restrictions.isNull(keys[0]), Restrictions.eq(keys[0], values[0])); } else if (values.length > 1) { for (int i = 1; i < values.length; i++) { c = Restrictions.or(c, Restrictions.eq(keys[0], values[i])); } } criteria.add(c); } else { Object[] values = (Object[]) value; if (values.length == 1) { criteria.add(Restrictions.eq(keys[0], values[0])); 第 页 /共 172页 } else if (values.length > 1) { Criterion c = Restrictions.or(Restrictions.eq( keys[0], values[0]), Restrictions.eq( keys[0], values[1])); for (int i = 2; i < values.length; i++) { c = Restrictions.or(c, Restrictions.eq(keys[0], values[i])); } criteria.add(c); } } } else if ("order".equals(keys[1])) { if ("asc".equals(value)) { criteria.addOrder(Order.asc(keys[0])); } else { criteria.addOrder(Order.desc(keys[0])); } } else if ("group".equals(keys[1])) {// 分组查询 criteria.setProjection(Projections.property(keys[0])); } } criteria .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); } catch (Exception ex) { log.error(ex.getMessage()); } } /** * 根据ID获取对象. 实际调用Hibernate的session.load()方法返回实体或其proxy对象. 如果对象不存在,抛出异常. */ protected E load(Class entity, Serializable id) { return (E) getHibernateTemplate().load(entity, id); 第 页 /共 172页 } /** * 根据ID获取对象. 实际调用Hibernate的session.get()方法返回实体. */ protected E get(Class entity, Serializable id){ return (E) getHibernateTemplate().get(entity, id); } /** * 分页查询函数,使用已设好查询条件与排序的Criteria. * * @param pageNo * 页号,从1开始. * @return 含总记录数和当前页数据的Page对象. */ /* protected Page pagedQuery(Criteria criteria, int pageNo, int pageSize) { Assert.notNull(criteria); Assert.isTrue(pageNo >= 1, "pageNo should start from 1"); CriteriaImpl impl = (CriteriaImpl) criteria; // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作 Projection projection = impl.getProjection(); List orderEntries; try { orderEntries = (List) BeanUtils.forceGetProperty(impl, "orderEntries"); BeanUtils.forceSetProperty(impl, "orderEntries", new ArrayList()); } catch (Exception e) { throw new InternalError(" Runtime Exception impossibility throw "); } // 执行查询 int totalCount = (Integer) criteria.setProjection( Projections.rowCount()).uniqueResult(); 第 页 /共 172页 // 将之前的Projection和OrderBy条件重新设回去 criteria.setProjection(projection); if (projection == null) { criteria .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); } try { BeanUtils.forceSetProperty(impl, "orderEntries", orderEntries); } catch (Exception e) { throw new InternalError(" Runtime Exception impossibility throw "); } // 返回分页对象 if (totalCount < 1) return new Page(); int startIndex = Page.getStartOfPage(pageNo, pageSize); List list = criteria.setFirstResult(startIndex).setMaxResults(pageSize) .list(); return new Page(startIndex, totalCount, pageSize, list); }*/ public Criteria getCriteria() { return criteria = getSession().createCriteria( getEntityClass().getClass()); } public void setCriteria(Criteria criteria) { this.criteria = criteria; } public E getEntityClass() { return entity; } 第 页 /共 172页 public void setEntityClass(E entity) { this.entity = entity; } public boolean isUnique(E entity, String uniquePropertyNames) { Assert.hasText(uniquePropertyNames); Criteria criteria = createCriteria(entity.getClass()).setProjection( Projections.rowCount()); String[] nameList = uniquePropertyNames.split(","); try { // 循环加入唯一列 for (String name : nameList) { criteria.add(Restrictions.eq(name, PropertyUtils.getProperty( entity, name))); } // 以下代码为了如果是update的情况,排除entity自身. String idName = getIdName(); // 取得entity的主键值 Serializable id = getId(entity); // 如果id!=null,说明对象已存在,该操作为update,加入排除自身的判断 if (id != null) criteria.add(Restrictions.not(Restrictions.eq(idName, id))); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } return (Integer) criteria.uniqueResult() == 0; } public Serializable getId(Object entity) { 第 页 /共 172页 Assert.notNull(entity); try { return (Serializable) PropertyUtils .getProperty(entity, getIdName()); } catch (Exception e) { log.error(e.getMessage()); return null; } } public String getIdName() { Assert.notNull(entity); ClassMetadata meta = getSessionFactory().getClassMetadata( entity.getClass()); Assert.notNull(meta, "Class " + entity + " not define in hibernate session factory."); String idName = meta.getIdentifierPropertyName(); return idName; } /** * 创建Criteria对象. * * @param criterions * 可变的Restrictions条件列表,见{@link #createQuery(String,Object...)} */ protected Criteria createCriteria(Class entity, Criterion... criterions) { Criteria criteria = getSession().createCriteria(entity); for (Criterion c : criterions) { criteria.add(c); } return criteria; } 第 页 /共 172页 public void flush() { getHibernateTemplate().flush(); } public void clear() { getHibernateTemplate().clear(); } public Query createQuery(String hql, Object... values) { Assert.hasText(hql); Query query = getSession().createQuery(hql); for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } return query; } public int execSql(final String sql) { return (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { SQLQuery query = session.createSQLQuery(sql); return query.executeUpdate(); } }); } public List execSqlQuery(final String sql) { return (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { SQLQuery query = session.createSQLQuery(sql); query.addEntity(entity.getClass()); return query.list(); } 第 页 /共 172页 }); } public int getResultseCount() { return resultseCount; } public void setResultseCount(int resultseCount) { this.resultseCount = resultseCount; } public List findByExample(E entity) { log.debug("finding Test instance by example"); try { List results = getHibernateTemplate().findByExample(entity); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); // throw re; } return null; } public E merge(E entity) { log.debug("merging Test instance"); try { E result = (E) getHibernateTemplate().merge(entity); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); 第 页 /共 172页 } return null; } public void beginTransaction() { getSession().beginTransaction(); } public E getEntity() { return entity; } public void setEntity(E entity) { this.entity = entity; } public List execHqlQueryPage(final String hql,final Page page) { Assert.hasText(hql); List li = getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(hql); if(null!=page){ ScrollableResults scrollableResults = query.scroll(); scrollableResults.last(); long totalCount = scrollableResults.getRowNumber(); int startIndex = page.getStartOfpage(); query.setFirstResult(startIndex); query.setMaxResults(page.getPageSize()); page.setTotalCount(java.lang.Math.abs(totalCount)+1); } return query.list(); } }); 第 页 /共 172页 if(null!=page){ page.setData(li); return page.getData(); }else return li; } /** * 取得数据库当前时间 */ public Date getSysDateTime(){ List list = new ArrayList(); list = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query query = session.createSQLQuery("SELECT NOW()"); return query.list(); } }); // 返回数据库时间 return UtilTools.strToDateTime(list.get(0).toString()); } /** * 取得数据库当前时间 */ public String getSysDateTimeStr(){ List list = new ArrayList(); list = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query query = session.createQuery("SELECT NOW()"); return query.list(); } }); 第 页 /共 172页 // 返回数据库时间 return list.get(0).toString(); } /* public int queryCampaigCountRow(String obj) { String hql = "from "+obj; int num = 0; List list = this.execHqlQuery(hql); if(list!=null && !list.isEmpty()){ num = list.size(); } return num; }*/ /** * 查询总行数 */ public long queryPageRow(final String hql) { // TODO Auto-generated method stub return (Long)this.getHibernateTemplate().execute(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { // TODO Auto-generated method stub return session.createQuery(hql).uniqueResult(); } }); 第 页 /共 172页 } /** * 分页查询 * @param pageBean * @param hql * @return */ public List queryThispage(final PageBean pageBean,final String hql) { // TODO Auto-generated method stub return (List)this.getHibernateTemplate().execute(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { // TODO Auto-generated method stub return session.createQuery(hql) .setFirstResult((pageBean.getThispage()-1)*pageBean.getElerow()) .setMaxResults(pageBean.getElerow()).list(); } }); } public void setUrl(String action,String namespace) { if(null!=namespace&&!"".equals(namespace.trim())) this.url = "/htcs"+namespace; if(null!=action&&!"".equals(action.trim())) { this.url += "/"+action+".action"; } else this.url = ((RequestMap)this.getStack().findValue("request")).get("struts.request_uri").toString(); } 第 页 /共 172页 public Pages(ValueStack arg0) { super(arg0); } @Override public boolean start(Writer writer) { boolean result = super.start(writer); this.setStyle("page"); try { StringBuilder str = new StringBuilder(); str.append("
"); str.append("
"); str.append(""); str.append("  "); if (currentpage < 2) str.append("  "); else str.append("  "); str.append(" 第 "+currentpage+"/"+totalpage+" 页 "); if (currentpage == totalpage) str.append("  "); else str.append("  "); 第 页 /共 172页 str.append("  "); str.append(" 跳转到 "); str.append(" 页"); str.append(""); //str.append(" / "+totalpage+" 页"); str.append(""); str.append(""); str.append("
"); writer.write(str.toString()); } catch (IOException ex) { Logger.getLogger(Pages.class.getName()).log(Level.SEVERE, null, ex); } return result; } /** * *分页查询列表 第 页 /共 172页 *@param pageBean 分页bean *@param sysDictSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysDict(PageBean pageBean,SysDict sysDictSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysDictSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysDictSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysDictSele 作为查询条件对象 */ public JSONObject getSysDictByParameter(SysDict sysDictSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysDictSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysDict(String [] orgChecks,SysDict sysDictSele){ int s = this.dao.delete(orgChecks,sysDictSele); 第 页 /共 172页 return s; } /** * 跳转到展示页面 */ public String toShowSysDict() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * *展示 */ public void showSysDict() { getpager(); JSONObject sysDict_json= this.service.getThisSysDict(ipage,sysDictSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysDict_json); } /** * *添加对象 */ public void addSysDict() { String textStr="fail"; 第 页 /共 172页 boolean flag = this.service.addSysDict(sysDict); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysDict=null; } /** * *转到修改页面 */ public void toModSysDict() { JSONObject sysDict_json= this.service.getSysDictByParameter(sysDictSele); Print.printJSON(getResponse(), sysDict_json); sysDictSele=null; } /** * *修改对象 */ public void modSysDict() { String textStr="fail"; boolean flag = this.service.modSysDict(sysDict); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysDict=null; } public void deleteSysDict() { 第 页 /共 172页 String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysDict(str,sysDict); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * *分页查询列表 *@param pageBean 分页bean *@param sysFunctionSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysFunction(PageBean pageBean,SysFunction sysFunctionSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysFunctionSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysFunctionSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } 第 页 /共 172页 /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysFunctionSele 作为查询条件对象 */ public JSONObject getSysFunctionByParameter(SysFunction sysFunctionSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysFunctionSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息)登录 *@param sysFunctionSele 作为查询条件对象 */ public List getSysFunctionByParameterLogin(String valid,String sort,String sortType,int userId) { String sql="SELECT * FROM sys_function WHERE function_id IN(SELECT function_id FROM sys_rel_role_function WHERE role_id IN (SELECT ru.role_id FROM sys_rel_user_role ru,sys_role r WHERE user_id ="+userId+" AND r.role_id=ru.role_id AND r.column_7='"+valid+"') GROUP BY function_id ) "+" order by "+sort+" "+sortType; return dao.execSqlQuery(sql); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysFunction(String [] orgChecks,SysFunction sysFunctionSele){ int s = this.dao.delete(orgChecks,sysFunctionSele); return s; } /** 第 页 /共 172页 * 生成树形结构 * @param valid 有效标志 * @param sort 排序字段 * @param sortType 排序方式 * @return */ public JSONArray getSysFunctionTree(String valid,String sort,String sortType) { String hql="from SysFunction where valid='"+valid+"' order by "+sort+" "+sortType; return JSONConvert.listToJSON(dao.execHqlQuery(hql)); } /** * 跳转到展示页面 */ public String toShowSysFunction() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * *展示 */ public void showSysFunction() { getpager(); 第 页 /共 172页 JSONObject sysFunction_json= this.service.getThisSysFunction(ipage,sysFunctionSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysFunction_json); } /** * 展示树形结构 */ public void showTreeSysFunction() { JSONArray sysFunction_json=this.service.getSysFunctionTree("T","functionId", "desc"); System.out.println("=============="+sysFunction_json); Print.printJSON(getResponse(), sysFunction_json); } /** * *添加对象 */ public void addSysFunction() { String textStr="fail"; boolean flag = this.service.addSysFunction(sysFunction); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysFunction=null; } /** * *转到修改页面 */ public void toModSysFunction() { 第 页 /共 172页 JSONObject sysFunction_json= this.service.getSysFunctionByParameter(sysFunctionSele); Print.printJSON(getResponse(), sysFunction_json); sysFunctionSele=null; } /** * *修改对象 */ public void modSysFunction() { String textStr="fail"; boolean flag = this.service.modSysFunction(sysFunction); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysFunction=null; } public void deleteSysFunction() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysFunction(str,sysFunction); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; 第 页 /共 172页 } /** * *添加对象hql */ public boolean addSysRelRoleActionItems(SysRelRoleActionItems sysRelRoleActionItems) { return this.dao.create(sysRelRoleActionItems); } /** * * *修改对象hql */ public boolean modSysRelRoleActionItems(SysRelRoleActionItems sysRelRoleActionItems) { return this.dao.save(sysRelRoleActionItems); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysRelRoleActionItemsSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysRelRoleActionItems(PageBean pageBean,SysRelRoleActionItems sysRelRoleActionItemsSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysRelRoleActionItemsSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 第 页 /共 172页 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysRelRoleActionItemsSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysRelRoleActionItemsSele 作为查询条件对象 */ public JSONObject getSysRelRoleActionItemsByParameter(SysRelRoleActionItems sysRelRoleActionItemsSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysRelRoleActionItemsSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysRelRoleActionItems(String [] orgChecks,SysRelRoleActionItems sysRelRoleActionItemsSele){ int s = this.dao.delete(orgChecks,sysRelRoleActionItemsSele); return s; } /** * 通过权限Id roleId删除 * @param roleId * @return 第 页 /共 172页 */ public int deleteSysRelRoleActionItemsByRoleId(String roleId) { String hql="delete from SysRelRoleActionItems where roleId="+roleId; return this.dao.execHql(hql); } public List getRoleActionItemsByRoleIdActionItemsId(String roleId,String actionItemsId) { String hql="from SysRelRoleActionItems where roleId="+roleId+" and actionItemsId="+actionItemsId; return this.dao.execHqlQuery(hql); } /*** * 批量添加,批量删除 * @param roleId * @param functionIds * @return */ public boolean addSysRoleFunction(String roleId,String functionIds) { //this.deleteSysRelRoleActionItemsByRoleId(roleId); if(functionIds!=null && !functionIds.equals("")) { String [] fIds=functionIds.split(","); if(fIds!=null &&fIds.length>0) { for(String fId:fIds) { List list=this.getRoleActionItemsByRoleIdActionItemsId(roleId, fId); if(list!=null && list.size()>0) continue; SysRelRoleActionItems sysRelRoleActionItems = new SysRelRoleActionItems(); sysRelRoleActionItems.setActionItemsId(Integer.valueOf(fId)); 第 页 /共 172页 sysRelRoleActionItems.setRoleId(Integer.valueOf(roleId)); sysRelRoleActionItems.setValid("T"); this.dao.save(sysRelRoleActionItems); } } }else return false; return true; } public void addBathSysRelRoleActionItems() { String textStr="fail"; //批量删除,批量添加 boolean flag = this.service.addSysRoleFunction(roleId, roleActionItemsIds); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); } /** * 跳转到展示页面 */ public String toShowSysRelRoleActionItems() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * *展示 */ 第 页 /共 172页 public void showSysRelRoleActionItems() { getpager(); JSONObject sysRelRoleActionItems_json= this.service.getThisSysRelRoleActionItems(ipage,sysRelRoleActionItemsSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysRelRoleActionItems_json); } /** * *添加对象 */ public void addSysRelRoleActionItems() { String textStr="fail"; boolean flag = this.service.addSysRelRoleActionItems(sysRelRoleActionItems); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysRelRoleActionItems=null; } /** * *转到修改页面 */ public void toModSysRelRoleActionItems() { JSONObject sysRelRoleActionItems_json= this.service.getSysRelRoleActionItemsByParameter(sysRelRoleActionItemsSele); Print.printJSON(getResponse(), sysRelRoleActionItems_json); sysRelRoleActionItemsSele=null; } /** * 第 页 /共 172页 *修改对象 */ public void modSysRelRoleActionItems() { String textStr="fail"; boolean flag = this.service.modSysRelRoleActionItems(sysRelRoleActionItems); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysRelRoleActionItems=null; } public void deleteSysRelRoleActionItems() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysRelRoleActionItems(str,sysRelRoleActionItems); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * 通过权限查询所有菜单,带选择菜单 * @param roleId 权限ID * @return */ public JSONArray getAllCheckedTreeSysFunction(String roleId) 第 页 /共 172页 { String sql="SELECT * FROM sys_rel_role_function WHERE role_id="+roleId+" GROUP BY function_id "; return JSONConvert.listToJSON(this.dao.execSqlQuery(sql)); } /** * *添加对象hql */ public boolean addSysRelRoleFunction(SysRelRoleFunction sysRelRoleFunction) { return this.dao.create(sysRelRoleFunction); } /** * * *修改对象hql */ public boolean modSysRelRoleFunction(SysRelRoleFunction sysRelRoleFunction) { return this.dao.save(sysRelRoleFunction); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysRelRoleFunctionSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysRelRoleFunction(PageBean pageBean,SysRelRoleFunction sysRelRoleFunctionSele,String sort,String order) { 第 页 /共 172页 String num = String.valueOf(dao.queryPageRow(getHql(sysRelRoleFunctionSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysRelRoleFunctionSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysRelRoleFunctionSele 作为查询条件对象 */ public JSONObject getSysRelRoleFunctionByParameter(SysRelRoleFunction sysRelRoleFunctionSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysRelRoleFunctionSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysRelRoleFunction(String [] orgChecks,SysRelRoleFunction sysRelRoleFunction){ int s = this.dao.delete(orgChecks,sysRelRoleFunction); return s; } /** * 通过权限Id roleId删除 第 页 /共 172页 * @param roleId * @return */ public int deleteSysRelRoleFunctionByRoleId(String roleId) { String hql="delete from SysRelRoleFunction where roleId="+roleId; return this.dao.execHql(hql); } /*** * 批量添加,批量删除 * @param roleId * @param functionIds * @return */ public boolean addSysRoleFunction(String roleId,String functionIds) { this.deleteSysRelRoleFunctionByRoleId(roleId); if(functionIds!=null && !functionIds.equals("")) { String [] fIds=functionIds.split(","); if(fIds!=null &&fIds.length>0) { for(String fId:fIds) { SysRelRoleFunction sysRoleFunction = new SysRelRoleFunction(); sysRoleFunction.setFunctionId(Integer.valueOf(fId)); sysRoleFunction.setRoleId(Integer.valueOf(roleId)); sysRoleFunction.setValid("T"); this.dao.save(sysRoleFunction); } } }else return false; return true; } 第 页 /共 172页 /** * 通过权限id查询所有权限菜单 */ public void showByRoleIdSysRelRoleFunction() { JSONArray sysFoleFunctions_json=this.service.getAllCheckedTreeSysFunction(roleId); System.out.println("asd========================="+sysFoleFunctions_json); Print.printJSON(getResponse(),sysFoleFunctions_json); } /** * 跳转到展示页面 */ public String toShowSysRelRoleFunction() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * *展示 */ public void showSysRelRoleFunction() { getpager(); JSONObject sysRelRoleFunction_json= this.service.getThisSysRelRoleFunction(ipage,sysRelRoleFunctionSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysRelRoleFunction_json); } 第 页 /共 172页 /** * *添加对象 */ public void addSysRelRoleFunction() { String textStr="fail"; //批量删除,批量添加 boolean flag = this.service.addSysRoleFunction(roleId,functionIds); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysRelRoleFunction=null; } /** * *转到修改页面 */ public void toModSysRelRoleFunction() { JSONObject sysRelRoleFunction_json= this.service.getSysRelRoleFunctionByParameter(sysRelRoleFunctionSele); Print.printJSON(getResponse(), sysRelRoleFunction_json); sysRelRoleFunctionSele=null; } /** * *修改对象 */ public void modSysRelRoleFunction() { String textStr="fail"; boolean flag = this.service.modSysRelRoleFunction(sysRelRoleFunction); 第 页 /共 172页 if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysRelRoleFunction=null; } public void deleteSysRelRoleFunction() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysRelRoleFunction(str,sysRelRoleFunction); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * *添加对象hql */ public boolean addSysParameter(SysParameter sysParameter) { return this.dao.create(sysParameter); } /** * * 第 页 /共 172页 *修改对象hql */ public boolean modSysParameter(SysParameter sysParameter) { return this.dao.save(sysParameter); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysParameterSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysParameter(PageBean pageBean,SysParameter sysParameterSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysParameterSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysParameterSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysParameterSele 作为查询条件对象 */ public JSONObject getSysParameterByParameter(SysParameter sysParameterSele) { 第 页 /共 172页 List temp=this.dao.execHqlQuery(getHqlEditer(sysParameterSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysParameter(String [] orgChecks,SysParameter sysParameterSele){ int s = this.dao.delete(orgChecks,sysParameterSele); return s; } /** * 通过用户Id查询所有 用户权限 * @param roleId 权限ID * @return */ public JSONArray getAllCheckedSysRel(String userId) { String sql="SELECT * FROM sys_role WHERE role_id IN (SELECT role_id FROM sys_rel_user_role WHERE user_id="+userId+" GROUP BY role_id)"; return JSONConvert.listToJSON(this.dao.execSqlQuery(sql)); } /** * 通过用户Id查询所有 用户权限 和部门 * @param userId * @param deptId * @return */ public List getCheckedSysRoleForUserIdDeptId(String userId) { 第 页 /共 172页 String sql="SELECT * FROM sys_role WHERE role_id IN(SELECT role_id FROM sys_rel_user_role WHERE user_id="+userId+" GROUP BY role_id)"; return this.dao.execSqlQuery(sql); } /** * 查询所有 * @param roleId 权限ID * @return */ public JSONArray getAllSysRel(String userId) { String sql="SELECT * FROM sys_role "; List allRole =this.dao.execSqlQuery(sql); if(allRole!=null) { for(SysRole role:allRole) { if(verChecked(role.getRoleId(),userId)) role.setCheckFlag("checked"); } } for(SysRole r:allRole) { System.out.println("flag==="+r.getCheckFlag()); } return JSONConvert.listToJSON(allRole); } public boolean verChecked(int roleId,String userId) { List checkedRole =this.getCheckedSysRoleForUserIdDeptId(userId); if(checkedRole!=null) { for(SysRole role:checkedRole) { 第 页 /共 172页 if(role.getRoleId()==roleId) { return true; } } } return false; } /** * *添加对象hql */ public boolean addSysRole(SysRole sysRole) { sysRole.setRoleStatus(1); sysRole.setColumn7("T"); return this.dao.create(sysRole); } /** * * *修改对象hql */ public boolean modSysRole(SysRole sysRole) { return this.dao.save(sysRole); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysRoleSele 作为查询条件对象 第 页 /共 172页 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysRole(PageBean pageBean,SysRole sysRoleSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysRoleSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysRoleSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysRoleSele 作为查询条件对象 */ public JSONObject getSysRoleByParameter(SysRole sysRoleSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysRoleSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysRole(String [] orgChecks,SysRole sysRole){ int s = this.dao.delete(orgChecks,sysRole); return s; 第 页 /共 172页 } /** * 跳转到展示页面 */ public String toShowSysRole() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * 通过权限id查询所有权限菜单 */ public void showByUserIdSysRole() { JSONArray sysFoleFunctions_json=this.service.getAllCheckedSysRel(userId); System.out.println("asd========================="+sysFoleFunctions_json); Print.printJSON(getResponse(),sysFoleFunctions_json); } public void showAllSysRole() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); JSONArray sysFoleFunctions_json=this.service.getAllSysRel(userId); System.out.println("asd========================="+sysFoleFunctions_json); Print.printJSON(getResponse(),sysFoleFunctions_json); } /** 第 页 /共 172页 * *展示 */ public String showSysRole() { getpager(); JSONObject sysRole_json= this.service.getThisSysRole(ipage,sysRoleSele,getSort(),getOrder()); System.out.println("============"+sysRole_json.toString()); Print.printJSON(getResponse(), sysRole_json); sysRole=null; return null; } /** * *添加对象 */ public void addSysRole() { String textStr="fail"; boolean flag = this.service.addSysRole(sysRole); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysRole=null; } /** * *转到修改页面 */ public void toModSysRole() { JSONObject sysRole_json= this.service.getSysRoleByParameter(sysRoleSele); 第 页 /共 172页 Print.printJSON(getResponse(), sysRole_json); sysRoleSele=null; } /** * *修改对象 */ public void modSysRole() { String textStr="fail"; boolean flag = this.service.modSysRole(sysRole); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysRole=null; } public void deleteSysRole() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysRole(str,sysRole); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } 第 页 /共 172页 /** * 通过用户Id查询所有 用户权限 * @param roleId 权限ID * @return */ public JSONArray getAllCheckedSysRelUserRole(String userId) { String sql="SELECT * FROM sys_rel_user_role WHERE user_id="+userId+" GROUP BY role_id "; return JSONConvert.listToJSON(this.dao.execSqlQuery(sql)); } /** * *添加对象hql */ public boolean addSysRelUserRole(SysRelUserRole sysRelUserRole) { return this.dao.create(sysRelUserRole); } /** * 批量添加 * @param userId * @param searchable * @return */ public boolean addBathSysRelUserRole(String userId,String searchable) { if(userId==null||userId.equals("")) { return false; } 第 页 /共 172页 if(searchable!=null &&!searchable.equals("")){ String []searchables=searchable.split(","); for(int i=0;i temp=dao.queryThispage(pageBean,getHql(sysRelUserRoleSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysRelUserRoleSele 作为查询条件对象 */ public JSONObject getSysRelUserRoleByParameter(SysRelUserRole sysRelUserRoleSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysRelUserRoleSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysRelUserRole(String [] orgChecks,SysRelUserRole sysRelUserRoleSele){ int s = this.dao.delete(orgChecks,sysRelUserRoleSele); return s; } 第 页 /共 172页 /** * 跳转到展示页面 */ public String toShowSysUser() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } public void saveUsrRolSysUser() { String textStr="fail"; boolean flag=this.sysRelUserRoleService.addBathSysRelUserRole(userId, searchable); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); } /** * 登陆 * @return */ public String loginSysUser() { SysUser us = this.service.findSysUserByUserName(userName); if(us!=null && us.getUserPwd()!=null &&userPassword.equals(us.getUserPwd())) { functoins=sysFunctionService.getSysFunctionByParameterLogin("T","function_Id", "desc",us.getUserId()); request.getSession().setAttribute(Context.USER_LONGIN_SESSION, us); loginFlag="success"; 第 页 /共 172页 return "login"; } loginFlag="fail"; return "fail"; } public void queryTreeSysUser() { List funcntions=sysFunctionService.getSysFunctionByParameterLogin("T","functionId", "desc"); menuStr="
    "; menuStr+="
  • "; menuStr+="系统管理"; menuStr+="
      "; for(SysFunction funtion:funcntions) { menuStr+="
    • "; menuStr+="
      "; menuStr+=""; menuStr+=""+funtion.getFunctionName()+""; menuStr+="
    • "; } menuStr+="
    "; menuStr+="
  • "; menuStr+="
"; Print.printText(getResponse(), menuStr); } /** * *展示 */ public void showSysUser() { 第 页 /共 172页 getpager(); JSONObject sysUser_json= this.service.getThisSysUser(ipage,sysUserSele,getSort(),getOrder()); System.out.println("=========================="+sysUser_json); Print.printJSON(getResponse(), sysUser_json); } /** * *添加对象 */ public void addSysUser() { String textStr="fail"; sysUser.setCreateTime(this.service.getSysDateTime()); // sysUser.setLastLogInTime(this.service.getSysDateTime()); boolean flag = this.service.addSysUser(sysUser); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysUser=null; } /** * *转到修改页面 */ public void toModSysUser() { JSONObject sysUser_json= this.service.getSysUserByParameter(sysUserSele); Print.printJSON(getResponse(), sysUser_json); sysUserSele=null; } /** 第 页 /共 172页 * *修改对象 */ public void modSysUser() { String textStr="fail"; boolean flag = this.service.modSysUser(sysUser); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysUser=null; } public void deleteSysUser() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysUser(str,sysUser); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * *添加对象hql */ public boolean addSysOrg(SysOrg sysOrg) 第 页 /共 172页 { sysOrg.setOrgStatus(1); sysOrg.setValid("T"); if(sysOrg.getPorgId()==null) sysOrg.setPorgId(0); return this.dao.create(sysOrg); } /** * * *修改对象hql */ public boolean modSysOrg(SysOrg sysOrg) { if(sysOrg.getPorgId()==null) sysOrg.setPorgId(0); return this.dao.save(sysOrg); } /** * 查询所有机构 * @return */ public JSONArray getAllSysOrg() { String hql="from SysOrg where valid='"+"T'"; return JSONConvert.listToJSON(this.dao.execHqlQuery(hql)); } /** * *分页查询列表 *@param pageBean 分页bean 第 页 /共 172页 *@param sysOrgSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysOrg(PageBean pageBean,SysOrg sysOrgSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysOrgSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysOrgSele,"page",sort,order)); if(temp!=null &&temp.size()>0) { for(SysOrg org:temp) { String hql="from SysOrg where orgId="+org.getPorgId(); SysOrg sysOrg=dao.execHqlQueryObj(hql); if(sysOrg!=null) { org.setPorgName(sysOrg.getOrgName()); }else org.setPorgName(""); } } return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysOrgSele 作为查询条件对象 */ public JSONObject getSysOrgByParameter(SysOrg sysOrgSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysOrgSele)); return JSONConvert.listToJSONForEasyUIDict(temp); 第 页 /共 172页 } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysOrg(String orgChecks,SysOrg sysOrg){ String [] orgIds=orgChecks.split(","); if(orgIds!=null &&orgIds.length>0) { for(int i=0;i orgs=dao.execHqlQuery(hql); if(orgs!=null &&orgs.size()>0) return i; String depthql="from SysDept where orgId="+orgIds[i]; List depts=sysDeptDao.execHqlQuery(depthql); if(depts!=null &&depts.size()>0) return i; } } this.dao.delete(orgChecks,sysOrg); return 100; } /** * 跳转到展示页面 */ public String toShowSysOrg() { 第 页 /共 172页 SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } public void showComBoSysOrg() { JSONArray sysOrg_json=this.service.getAllSysOrg(); System.out.println("==========================="+sysOrg_json); Print.printJSON(getResponse(), sysOrg_json); } /** * *展示 */ public void showSysOrg() { getpager(); JSONObject sysOrg_json= this.service.getThisSysOrg(ipage,sysOrgSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysOrg_json); } /** * *添加对象 */ public void addSysOrg() { String textStr="fail"; boolean flag = this.service.addSysOrg(sysOrg); 第 页 /共 172页 if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysOrg=null; } /** * *转到修改页面 */ public void toModSysOrg() { JSONObject sysOrg_json= this.service.getSysOrgByParameter(sysOrgSele); Print.printJSON(getResponse(), sysOrg_json); sysOrgSele=null; } /** * *修改对象 */ public void modSysOrg() { String textStr="fail"; boolean flag = this.service.modSysOrg(sysOrg); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysOrg=null; } public void deleteSysOrg() { String textStr="fail"; 第 页 /共 172页 String [] names=orgNames.split(","); if(dataChecks!=null && !dataChecks.equals("")){ int flag = this.service.deleteSysOrg(dataChecks,sysOrg); if(flag!=100) textStr="fail"+"_"+names[flag]; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * 通过菜单id functionId查询所有操作项 * @param roleId 权限ID * @return */ public JSONArray getAllCheckedItemsSysActionItems(String functionId,String roleId) { String hql="FROM SysActionItems WHERE function_id="+functionId; String hql1="FROM SysRelRoleActionItems WHERE roleId="+roleId; List roleItems=sysRelRoleActionItemsDao.execHqlQuery(hql1); List items=this.dao.execHqlQuery(hql); if(items!=null && items.size()>0) { for(SysActionItems item:items) { if(verChecked(item.getActionItemsId(),roleItems)) item.setCheckedFlag("checked"); } } return JSONConvert.listToJSON(this.dao.execHqlQuery(hql)); } /** 第 页 /共 172页 * 验证是否选中 * @param actionItemsId * @param checkedRole * @return */ public boolean verChecked(int actionItemsId,List checkedRole) { if(checkedRole!=null) { for(SysRelRoleActionItems items:checkedRole) { if(items.getActionItemsId()==actionItemsId) { return true; } } } return false; } /** * 查询有权限的操作项 * @param roleId * @param functionId * @return */ public List getActionItemsByRoleIdFunctionId(String functionId,int userId) { String sql="select * from sys_action_items i ,sys_rel_role_action_items r where i.function_id="+functionId+" and r.role_id in (SELECT ru.role_id FROM sys_rel_user_role ru,sys_role r WHERE user_id ="+userId+" AND r.role_id=ru.role_id AND r.column_7='T') and i.action_items_id=r.action_items_id"; return (List )this.execSqlQuery(sql); } /** 第 页 /共 172页 * 查询有权限的操作项 * @param roleId * @param functionId * @return */ public List getActionItemsByRoleIdFunctionId(String roleId,String functionId) { String sql="select * from sys_action_items i ,sys_rel_role_action_items r where i.function_id="+functionId+" and r.role_id="+roleId+" and i.action_items_id=r.action_items_id"; String hql="from SysActionItems i join SysRelRoleActionItems r on i.actionItemsId=r.actionItemsId and r.roleId="+roleId+" and i.functionId="+functionId; return this.dao.execSqlQuery(sql); } /** * *添加对象hql */ public boolean addSysActionItems(SysActionItems sysActionItems) { return this.dao.create(sysActionItems); } /** * * *修改对象hql */ public boolean modSysActionItems(SysActionItems sysActionItems) { return this.dao.save(sysActionItems); } /** * *分页查询列表 第 页 /共 172页 *@param pageBean 分页bean *@param sysActionItemsSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysActionItems(PageBean pageBean,SysActionItems sysActionItemsSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysActionItemsSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysActionItemsSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysActionItemsSele 作为查询条件对象 */ public JSONObject getSysActionItemsByParameter(SysActionItems sysActionItemsSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysActionItemsSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysActionItems(String [] orgChecks,SysActionItems sysActionItemsSele){ 第 页 /共 172页 int s = this.dao.delete(orgChecks,sysActionItemsSele); return s; } public void setSysRelRoleActionItemsDao( SysRelRoleActionItemsDao sysRelRoleActionItemsDao) { this.sysRelRoleActionItemsDao = sysRelRoleActionItemsDao; } /** * 通过functionId查询所有的按钮 */ public void showByFunctionIdSysActionItems() { this.service.getActionItemsByRoleIdFunctionId(roleId,functionId); JSONArray json_array=this.service.getAllCheckedItemsSysActionItems(functionId,roleId); System.out.println(json_array); Print.printJSON(getResponse(), json_array); } /** * 跳转到展示页面 */ public String toShowSysActionItems() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * 第 页 /共 172页 *展示 */ public void showSysActionItems() { getpager(); JSONObject sysActionItems_json= this.service.getThisSysActionItems(ipage,sysActionItemsSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysActionItems_json); } public void initItemsr() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.service.getActionItemsByRoleIdFunctionId(functionId, user.getUserId()); this.getRequest().setAttribute("items", items); } /** * *添加对象 */ public void addSysActionItems() { String textStr="fail"; boolean flag = this.service.addSysActionItems(sysActionItems); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysActionItems=null; } /** * *转到修改页面 第 页 /共 172页 */ public void toModSysActionItems() { JSONObject sysActionItems_json= this.service.getSysActionItemsByParameter(sysActionItemsSele); Print.printJSON(getResponse(), sysActionItems_json); sysActionItemsSele=null; } /** * *修改对象 */ public void modSysActionItems() { String textStr="fail"; boolean flag = this.service.modSysActionItems(sysActionItems); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysActionItems=null; } public void deleteSysActionItems() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysActionItems(str,sysActionItems); if(flag<=0) textStr="fail"; else textStr="success"; 第 页 /共 172页 }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * 通过菜单id functionId查询所有操作项 * @param roleId 权限ID * @return */ public JSONArray getAllCheckedItemsSysRelFunctionAction(String functionId) { String sql="SELECT * FROM sys_rel_function_action WHERE function_id="+functionId+""; return JSONConvert.listToJSON(this.dao.execSqlQuery(sql)); } /** * *添加对象hql */ public boolean addSysRelFunctionAction(SysRelFunctionAction sysRelFunctionAction) { return this.dao.create(sysRelFunctionAction); } /** * 批量添加 、删除菜单功能项关系表 * @param functionId * @param itemIds * @return */ public boolean addBathRelFunctionAction(String functionId,String itemIds) { //先删除 后添加 return true; 第 页 /共 172页 } /** * * *修改对象hql */ public boolean modSysRelFunctionAction(SysRelFunctionAction sysRelFunctionAction) { return this.dao.save(sysRelFunctionAction); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysRelFunctionActionSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysRelFunctionAction(PageBean pageBean,SysRelFunctionAction sysRelFunctionActionSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysRelFunctionActionSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysRelFunctionActionSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) 第 页 /共 172页 *@param sysRelFunctionActionSele 作为查询条件对象 */ public JSONObject getSysRelFunctionActionByParameter(SysRelFunctionAction sysRelFunctionActionSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysRelFunctionActionSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysRelFunctionAction(String [] orgChecks,SysRelFunctionAction sysRelFunctionActionSele){ int s = this.dao.delete(orgChecks,sysRelFunctionActionSele); return s; } /** * 通过权限Id roleId删除 * @param roleId * @return */ public int deleteSysRelFunctionActionByFunctionId(String functionId) { String hql="delete from SysRelFunctionAction where functionId="+functionId; return this.dao.execHql(hql); } /*** * 批量添加,批量删除 第 页 /共 172页 * @param roleId * @param functionIds * @return */ public boolean addSysRelFunctionAction(String functionId,String actionItemsId) { this.deleteSysRelFunctionActionByFunctionId(functionId); if(actionItemsId!=null && !actionItemsId.equals("")) { String [] fIds=actionItemsId.split(","); if(fIds!=null &&fIds.length>0) { for(String fId:fIds) { SysRelFunctionAction sysRelFunctionAction = new SysRelFunctionAction(); sysRelFunctionAction.setFunctionId(Integer.valueOf(functionId)); sysRelFunctionAction.setActionItemsId(Integer.valueOf(fId)); sysRelFunctionAction.setValid("T"); this.dao.save(sysRelFunctionAction); } } }else return false; return true; } /** * 查询所有机构下的所有部门 * @return */ public JSONArray getAllSysDept(String orgId) { if(orgId!=null &&!orgId.equals("")) { String hql="from SysDept where valid='"+"T' and orgId="+orgId; return JSONConvert.listToJSON(this.dao.execHqlQuery(hql)); 第 页 /共 172页 }else { List list = new ArrayList(); return JSONConvert.listToJSON(list); } } /** * *添加对象hql */ public boolean addSysDept(SysDept sysDept) { sysDept.setValid("T"); sysDept.setDeptStatus(1); return this.dao.create(sysDept); } /** * * *修改对象hql */ public boolean modSysDept(SysDept sysDept) { return this.dao.save(sysDept); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysDeptSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 第 页 /共 172页 */ public JSONObject getThisSysDept(PageBean pageBean,SysDept sysDeptSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysDeptSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysDeptSele,"page",sort,order)); return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysDeptSele 作为查询条件对象 */ public JSONObject getSysDeptByParameter(SysDept sysDeptSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysDeptSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除 * @param orgChecks * @return */ public int deleteSysDept(String [] orgChecks,SysDept sysDept){ int s = this.dao.delete(orgChecks,sysDept); return s; } @Override 第 页 /共 172页 public int doStartTag() throws JspException { boolean result = false; List rmList = Utils.getRoleMenuList((HttpServletRequest)pageContext.getRequest()); for(SysRelRoleFunction rm:rmList){ if(rm != null){ Menu m = rm.getMenuId(); if(m!=null){ if(type.equals(m.getType()) && module.equals(m.getModule()) && privilege.equals(m.getPrivilege()) ){ result = true; break; } } } } if("user".equals(module) && "update".equals(privilege)){ result = true; } return result?EVAL_BODY_INCLUDE:SKIP_BODY; } /** * 获取系统的reqeust对象 绝大多数情况下都不需要调用此方法 * * @return 当前的request */ public static final HttpServletRequest getRequest() { return ServletActionContext.getRequest(); } /** 第 页 /共 172页 * 获取response对象 绝大多数情况下都不需要调用此方法 * * @return 当前的response */ public static final HttpServletResponse getResponse() { return ServletActionContext.getResponse(); } /*** * 获取URI的路径,如路径为http://www.baidu.com/action/post.htm?method=add, 得到的值为"/action/post.htm" * * @param request * @return */ public static String getRequestURI(HttpServletRequest request) { return request.getRequestURI(); } /** * 获取完整请求路径(含内容路径及请求参数) * * @param request * @return */ public static String getRequestURIWithParam(HttpServletRequest request) { return getRequestURI(request) + ( request.getQueryString() == null ? "" : "?" + request.getQueryString() ); } /** * 获取图片扩展名 * 第 页 /共 172页 * @param file * @return */ public static String getExt(String fileName) { return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); } /** * 处理中文问题,实现编码转换 * * @param str * @return */ public static String toChinese(String str) { String strResult = ""; try { if ( str != null ) { strResult = new String(str.getBytes("ISO8859_1"), "UTF-8"); // strResult = str; } else { strResult = ""; } } catch ( Exception e ) { e.printStackTrace(); } return strResult; } 第 页 /共 172页 /** * 根据字符串的标记将字符串拆分成Integer数组 * * @param str 字符 * @param flg 标记 * @return 整形数组 */ public static Integer[] toIntegerByStringFlg(String str, String flg) { if ( str == null || flg == null ) { return null; } String[] strArray = str.split(flg); Integer[] nArray = new Integer[strArray.length]; for ( int i = 0; i < strArray.length; i++ ) { try { Integer temp = Integer.parseInt(strArray[i]); nArray[i] = temp; } catch ( Exception e ) { System.out.println("类型转换出错 StringUtil.class"); } } return nArray; } /** * 去除html代码 * * @param inputString * @return 第 页 /共 172页 */ public static String HtmltoText(String inputString) { String htmlStr = inputString; // 含html标签的字符串 String textStr = ""; java.util.regex.Pattern p_script; java.util.regex.Matcher m_script; java.util.regex.Pattern p_style; java.util.regex.Matcher m_style; java.util.regex.Pattern p_html; java.util.regex.Matcher m_html; java.util.regex.Pattern p_ba; java.util.regex.Matcher m_ba; try { String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或]*?>[\\s\\S]*?<\\/script> // } String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或]*?>[\\s\\S]*?<\\/style> // } String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 String patternStr = "\\s+"; p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); m_html = p_html.matcher(htmlStr); 第 页 /共 172页 htmlStr = m_html.replaceAll(""); // 过滤html标签 p_ba = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE); m_ba = p_ba.matcher(htmlStr); htmlStr = m_ba.replaceAll(""); // 过滤空格 textStr = htmlStr; } catch ( Exception e ) { System.err.println("Html2Text: " + e.getMessage()); } return textStr;// 返回文本字符串 } /** * 执行搜索 **/ public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { UserInfoQuery query = newPageRequest(request,UserInfoQuery.class,DEFAULT_SORT_COLUMNS); Page page = this.userInfoManager.findPage(query); savePage(page,query,request); return LIST_FORWARD; } /** * 查看对象 **/ public ActionForward show(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { java.lang.Long id = new java.lang.Long(request.getParameter("userId")); 第 页 /共 172页 UserInfo userInfo = (UserInfo)userInfoManager.getById(id); copyProperties(form,userInfo); return SHOW_FORWARD; } /** * 进入新增页面 **/ public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { return CREATE_FORWARD; } /** * 保存新增对象 **/ public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { UserInfo userInfo = new UserInfo(); copyProperties(userInfo,form); userInfoManager.save(userInfo); saveDirectMessage(request, MSG_SAVED_SUCCESS); return LIST_ACTION_FORWARD; } /** * 进入更新页面 **/ public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { java.lang.Long id = new java.lang.Long(request.getParameter("userId")); UserInfo userInfo = (UserInfo)userInfoManager.getById(id); copyProperties(form,userInfo); 第 页 /共 172页 return EDIT_FORWARD; } /** * 保存更新对象 **/ public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { java.lang.Long id = new java.lang.Long(request.getParameter("userId")); UserInfo userInfo = (UserInfo)userInfoManager.getById(id); copyProperties(userInfo,form); userInfoManager.update(userInfo); saveDirectMessage(request, MSG_SAVED_SUCCESS); return LIST_ACTION_FORWARD; } /** *删除对象 **/ public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String[] items = request.getParameterValues("items"); for(int i = 0; i < items.length; i++) { Hashtable params = HttpUtils.parseQueryString(items[i]); java.lang.Long id = new java.lang.Long((String)params.get("userId")); userInfoManager.removeById(id); } saveDirectMessage(request, MSG_DELETE_SUCCESS); return LIST_ACTION_FORWARD; } 第 页 /共 172页 protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain chain)throws ServletException,IOException { try { //示例为一个固定的登陆用户,请直接修改代码 MDC.put("loginUserId", "demo-loginUsername"); MDC.put("req.requestURI", StringUtils.defaultString(request.getRequestURI())); MDC.put("req.queryString", StringUtils.defaultString(request.getQueryString())); MDC.put("req.requestURIWithQueryString", request.getRequestURI() + (request.getQueryString() == null ? "" : "?"+request.getQueryString())); MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr())); //为每一个请求创建一个ID,方便查找日志时可以根据ID查找出一个http请求所有相关日志 MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(),"-")); chain.doFilter(request, response); }finally { clearMDC(); } } private void clearMDC() { Map map = MDC.getContext(); if(map != null) { map.clear(); } } public static void registerConverters() { ConvertUtils.register(new StringConverter(), String.class); //date ConvertUtils.register(new DateConverter(null),java.util.Date.class); ConvertUtils.register(new SqlDateConverter(null),java.sql.Date.class); ConvertUtils.register(new SqlTimeConverter(null),Time.class); ConvertUtils.register(new SqlTimestampConverter(null),Timestamp.class); //number ConvertUtils.register(new BooleanConverter(null), Boolean.class); 第 页 /共 172页 ConvertUtils.register(new ShortConverter(null), Short.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); } // public static void registerConverters(ConvertUtilsBean convertUtils) { // registerConverters(convertUtils,new String[] {"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm:ss.SSS","HH:mm:ss"}); // } public static void registerConverters(ConvertUtilsBean convertUtils,String[] datePatterns) { convertUtils.register(new StringConverter(), String.class); //date convertUtils.register(ConvertRegisterHelper.setPatterns(new DateConverter(null),datePatterns),java.util.Date.class); convertUtils.register(ConvertRegisterHelper.setPatterns(new SqlDateConverter(null),datePatterns),java.sql.Date.class); convertUtils.register(ConvertRegisterHelper.setPatterns(new SqlTimeConverter(null),datePatterns),Time.class); convertUtils.register(ConvertRegisterHelper.setPatterns(new SqlTimestampConverter(null),datePatterns),Timestamp.class); //number convertUtils.register(new BooleanConverter(null), Boolean.class); convertUtils.register(new ShortConverter(null), Short.class); convertUtils.register(new IntegerConverter(null), Integer.class); convertUtils.register(new LongConverter(null), Long.class); convertUtils.register(new FloatConverter(null), Float.class); convertUtils.register(new DoubleConverter(null), Double.class); convertUtils.register(new BigDecimalConverter(null), BigDecimal.class); convertUtils.register(new BigIntegerConverter(null), BigInteger.class); } static { //用于注册日期类型的转换 第 页 /共 172页 String[] datePatterns = new String[] {"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm:ss.SSS","HH:mm:ss"}; ConvertRegisterHelper.registerConverters(beanUtils.getConvertUtils(),datePatterns); System.out.println("PageRequestFactory.MAX_PAGE_SIZE="+MAX_PAGE_SIZE); } public static PageRequest bindPageRequest(PageRequest pageRequest,HttpServletRequest request){ return bindPageRequest(pageRequest, request, null); } public static PageRequest bindPageRequest(PageRequest pageRequest,HttpServletRequest request,String defaultSortColumns){ return bindPageRequest(pageRequest, request, defaultSortColumns, BaseQuery.DEFAULT_PAGE_SIZE); } /** * 绑定PageRequest的属性值 */ public static PageRequest bindPageRequest(PageRequest pageRequest, HttpServletRequest request,String defaultSortColumns, int defaultPageSize) { try { Map params = WebUtils.getParametersStartingWith(request, ""); beanUtils.copyProperties(pageRequest, params); } catch (IllegalAccessException e) { throw new IllegalArgumentException("beanUtils.copyProperties() error",e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("beanUtils.copyProperties() error",e.getTargetException()); } pageRequest.setPageNumber(ServletRequestUtils.getIntParameter(request, "pageNumber", 1)); pageRequest.setPageSize(ServletRequestUtils.getIntParameter(request, "pageSize", defaultPageSize)); pageRequest.setSortColumns(ServletRequestUtils.getStringParameter(request, "sortColumns",defaultSortColumns)); if(pageRequest.getPageSize() > MAX_PAGE_SIZE) { pageRequest.setPageSize(MAX_PAGE_SIZE); 第 页 /共 172页 } return pageRequest; } /** * *添加数据字典对象hql */ public boolean addSysDict(SysDict sysDict) { return this.dao.create(sysDict); } /** * * *修改数据字典对象hql */ public boolean modSysDict(SysDict sysDict) { return this.dao.save(sysDict); } /** * *分页查询列表 *@param pageBean 分页bean *@param sysDictSele 作为查询条件对象 *@param sort 排序条件 *@param order 升序 还是降序 */ public JSONObject getThisSysDict(PageBean pageBean,SysDict sysDictSele,String sort,String order) { String num = String.valueOf(dao.queryPageRow(getHql(sysDictSele,"count",sort,order))); pageBean.setCountrow(Integer.valueOf(num)); //设置总页数 pageBean.setCountpage(); List temp=dao.queryThispage(pageBean,getHql(sysDictSele,"page",sort,order)); 第 页 /共 172页 return JSONConvert.listToJSONForEasyUIDict(Long.valueOf(num),temp); } /** *通过条件查询对象列表 在修改前查询时使用 (注:修改时只查询出一条信息) *@param sysDictSele 作为查询条件对象 */ public JSONObject getSysDictByParameter(SysDict sysDictSele) { List temp=this.dao.execHqlQuery(getHqlEditer(sysDictSele)); return JSONConvert.listToJSONForEasyUIDict(temp); } /** * 批量删除数据字典 * @param orgChecks * @return */ public int deleteSysDict(String [] orgChecks,SysDict sysDictSele){ int s = this.dao.delete(orgChecks,sysDictSele); return s; } /** * 跳转到数据字典展示页面 */ public String toShowSysDict() { SysUser user=(SysUser)this.getRequest().getSession().getAttribute(Context.USER_LONGIN_SESSION); List items=this.sysActionItemsService.getActionItemsByRoleIdFunctionId(this.getFunctionId(), user.getUserId()); this.getRequest().setAttribute("items", items); return SUCCESS; } /** * 第 页 /共 172页 *展示数据字典 */ public void showSysDict() { getpager(); JSONObject sysDict_json= this.service.getThisSysDict(ipage,sysDictSele,getSort(),getOrder()); Print.printJSON(getResponse(), sysDict_json); } /** * *添加数据字典对象 */ public void addSysDict() { String textStr="fail"; boolean flag = this.service.addSysDict(sysDict); if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysDict=null; } /** * *转到修改数据字典页面 */ public void toModSysDict() { JSONObject sysDict_json= this.service.getSysDictByParameter(sysDictSele); Print.printJSON(getResponse(), sysDict_json); sysDictSele=null; } /** * *修改数据字典对象 */ public void modSysDict() { String textStr="fail"; boolean flag = this.service.modSysDict(sysDict); 第 页 /共 172页 if(flag) textStr="success"; else textStr="fail"; Print.printText(getResponse(), textStr); sysDict=null; } public void deleteSysDict() { String textStr="fail"; if(dataChecks!=null && !dataChecks.equals("")){ String [] str = dataChecks.split(","); int flag = this.service.deleteSysDict(str,sysDict); if(flag<=0) textStr="fail"; else textStr="success"; }else textStr="fail"; Print.printText(getResponse(), textStr); dataChecks=null; } /** * 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 **/ public void setSysDictService(SysDictService sysDictService) { this.sysDictService = sysDictService; } /** * 增加getXXXX()方法,用于页面的属性 **/ public SysDict getSysDictSele() { return this.sysDictSele; } /** * 增加setXXXX()方法,用于页面的属性 **/ public void setSysDictSele(SysDict sysDictSele) { this.sysDictSele = sysDictSele; } 第 页 /共 172页 /** * 增加getXXXX()方法,用于页面的属性 **/ public String getDataChecks() { return this.dataChecks; } /** * 增加setXXXX()方法,用于页面的属性 **/ public void setDataChecks(String dataChecks) { this.dataChecks = dataChecks; } /** * 增加getXXXX()方法,用于页面的属性 **/ public SysDict getSysDict() { return this.sysDict; } /** * 增加setXXXX()方法,用于页面的属性 **/ public void setSysDict(SysDict sysDict) { this.sysDict = sysDict; } /** * 增加getXXXX()方法,用于页面的属性 **/ public List getSysDictList() { return this.sysDictList; } /** * 增加setXXXX()方法,用于页面的属性 **/ public void setSysDict(List sysDictList) { this.sysDictList = sysDictList; } 第 页 /共 172页 public void setSysActionItemsService(SysActionItemsService sysActionItemsService) { this.sysActionItemsService = sysActionItemsService; } public void onPostInsert(PostInsertEvent event) { if (event.getEntity() instanceof Auditable) { Auditable entity = (Auditable) event.getEntity(); System.out.println( entity.getClass().getName() + "——" + entity.getPK() + "插入操作" ); } } public void onPostUpdate(PostUpdateEvent event) { if (event.getEntity() instanceof Auditable) { for (int i = 0; i < event.getState().length; i++) { // 更新前的值 Object oldValue = event.getOldState()[i]; // 更新后的新值 Object newValue = event.getState()[i]; // 跳过集合属性 if (newValue instanceof PersistentCollection) { continue; } if (oldValue != null && !oldValue.equals(newValue)) { // 取得属性名称 String _s = event.getPersister().getPropertyNames()[i]; System.out.println(_s + "——修改前值:" + oldValue + ",修改后值:" + newValue ); } } } } public void onPostDelete(PostDeleteEvent event) { if (event.getEntity() instanceof Auditable) { Auditable entity = (Auditable) event.getEntity(); System.out.println( entity.getClass().getName() + "——" + entity.getPK() + "删除操作" ); } } 第 页 /共 172页 private void recordHistroy(Session session ,Audit audit){ Session _session = session.getSessionFactory().openSession(); Transaction tx = _session.beginTransaction(); try { tx.begin(); _session.save(audit); _session.flush(); tx.commit(); } catch (HibernateException e) { if(tx != null){ tx.rollback(); } logger.error("数据库审计日志:" + audit.getClass().getName()); }finally{ if(_session != null){ _session.close(); } } } @Override protected String doIntercept(ActionInvocation invocation) throws Exception { ActionContext context = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST); String currentURL = request.getRequestURI(); String targetURL = currentURL.substring(currentURL.indexOf("/", 1),currentURL.length()); System.out.println(currentURL + ".............." + targetURL); Map session = context.getSession(); if( targetURL.indexOf("user_login") == -1 && targetURL.indexOf("user_authentiCode") == -1){ if (session.get(Utils.USER_SESSION) != null) { invocation.invoke(); }else{ return "exit"; } }else{ 第 页 /共 172页 invocation.invoke(); } return "exit"; } /** * 日期转换成字符串 * @param patternStyle * @param date * @return */ public static String dateToString(String dateStyle,Date date){ if (dateStyle == null || dateStyle.trim().equals("")) { dateStyle = DEFAULT_DATE_STYLE; } else if (date == null) { throw new IllegalArgumentException( "param date is null in dateToString"); } SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern(dateStyle); return sdf.format(date); } /** * 将指定格式的String转换为Date * * @param args */ public static Date stringToDate(String dateStyle, String dateStr) throws ParseException { if (dateStyle == null || dateStyle.trim().equals("")) { System.out.println("dateStyle is null in stringToDate"); return null; } else if (dateStr == null || dateStr.equals("")) { System.out.println("dateStr is null in stringToDate"); return null; } Date date = null; SimpleDateFormat sdf = new SimpleDateFormat(dateStyle); try { date = sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); throw e; } 第 页 /共 172页 return date; } /** * 解析EXCLE 返回一个List集合(集合内包涵Excel的所有内容) * @param is * @return */ public static List parseExcel(InputStream is){ List list = new ArrayList() ; Workbook wb = null ; try { wb = Workbook.getWorkbook(is); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(wb==null){ return null ; } //获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了 Sheet[] sheet = wb.getSheets(); if(sheet!=null&&sheet.length>0){ Sheet sheet0=sheet[0]; //得到当前工作表的行数 int rowNum = sheet0.getRows(); for(int i=0;i row=new ArrayList(); if(cells!=null&&cells.length>0){ int cellNum=cells.length; String[] fieldValue = new String[cellNum]; //对每个单元格进行循环 for(int j=0;j< cellNum;j++){ //读取当前单元格的值 Cell c=cells[j]; String cellValue = cells[j].getContents().trim(); if(c.getType() == CellType.LABEL) { LabelCell labelc00 = (LabelCell)c; cellValue = labelc00.getString().trim(); 第 页 /共 172页 }else if(c.getType() == CellType.NUMBER) { NumberCell numc10 = (NumberCell)c; cellValue = getFormatNumber(numc10.getValue()); }else if(c.getType() == CellType.DATE) { DateCell datec11 = (DateCell)c; cellValue = getFormatTime(datec11.getDate()); } fieldValue[j] = cellValue; } list.add(fieldValue); } } } //最后关闭资源,释放内存 wb.close(); return list; } /** * 时间格式转换 * @author yaofuyuan * @createTime 2012-04-28 16:00 */ public static String getFormatTime(Date logtime) { if (null == logtime) { logtime = new Date(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = ""; try { time = sdf.format(logtime); } catch (Exception e) { e.printStackTrace(); } return time; } @AfterThrowing(pointcut="anyMethod()",throwing="e") 第 页 /共 172页 public void showErrors(JoinPoint jp,Exception e){ Logger log = Logger.getLogger(jp.getClass()) ; StringBuffer errors = new StringBuffer(""); errors.append("发生异常\n\t"); errors.append("异常类型:" + e.getClass().getName() + "\n\t"); errors.append("异常描述:" + e.getMessage() + "\n\t"); errors.append(getErrorDetail(e.getStackTrace())); log.log(Level.ERROR, errors.toString()); } /** * 获取错误详情 * @return */ private String getErrorDetail(StackTraceElement[] steArr){ StringBuffer errors = new StringBuffer(""); errors.append("异常详情:\n\t"); errors.append("\n\t"); for (StackTraceElement ste:steArr ) { errors.append("at:"+ste.toString()).append("\n\t"); } errors.append("\n\t"); return errors.toString(); } /** * 获取专业竞赛动态列表 */ public void list() { // 填充分页参数信息 repositoryDTO = (repositoryDTO == null ? new RepositoryDTO() : repositoryDTO); fillPagination(repositoryDTO); JSONObject _contestdynamics_json = iRepositoryService .getRepositoryList(repositoryDTO); Print.printJSON(getResponse(), _contestdynamics_json); repositoryDTO = null; } public String getPath() { // 属性文件 Properties prop = new Properties(); InputStream is = this.getClass().getResourceAsStream( 第 页 /共 172页 "/system.properties"); // 从输入流中读取属性列表 try { prop.load(is); } catch (IOException e) { e.printStackTrace(); } String path = prop.getProperty("path"); return path; } /**************** * 添加 */ public String add() { Repository re = new Repository(); RepositoryAction a = new RepositoryAction(); String path = a.getPath(); try { File dirFile = null; dirFile = new File(path); if (!(dirFile.exists()) && !(dirFile.isDirectory())) { boolean creadok = dirFile.mkdirs(); } // getRequest().getSession().getServletContext().getRealPath("/tmp"); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String d = format.format(new Date()); String oldname = this.docFileName; String lastname = oldname.substring(oldname.lastIndexOf(".")); String newname = d + (new Random()).nextInt(9999999) + lastname; File oldName = new File(path, newname); // ss.substring(0, ss.lastIndexOf(".")) if (!oldName.getParentFile().exists()) oldName.getParentFile().mkdirs(); try { FileUtils.copyFile(doc, oldName); 第 页 /共 172页 } catch (Exception e) { e.printStackTrace(); } String docName = docFileName.substring(0, docFileName .lastIndexOf(".")); String filename=docName+lastname; Date date = new Date(); String time = DateUtil.dateToString("yyyy-MM-dd", date); String userid = (String) getSession().get("currentUserId"); User u = iUserService.getUser(userid); Dictionary dic = this.dictionaryService.getByID(dict); Unit unit = u.getUnit(); re.setFileName(filename); re.setCreate_date(time); re.setCreator(u); re.setDescs(descs); re.setName(docName); re.setType(dic); re.setUnit(unit); re.setUpdate_date(time); re.setUpdator(u); re.setPath(oldName.getName()); } catch (Exception e) { e.printStackTrace(); } iRepositoryService.addRepository(re); return this.page(); } /********** * 删除 * * @return */ public void delete() { RepositoryAction a = new RepositoryAction(); String path = a.getPath(); try { repositoryDTO = (repositoryDTO == null ? new RepositoryDTO() : repositoryDTO); 第 页 /共 172页 String delpath = path + "/"; String status = iRepositoryService.deleteRepository(repositoryDTO, delpath); Print.printText(getResponse(), status); } catch (Exception e) { e.printStackTrace(); } repository = null; } /******** * 查询一个 */ public void getRositoryById() { repository = (repository == null ? new Repository() : repository); try { System.out.println(repository.getCode() + ":code"); JSONObject _user_json = iRepositoryService .getRepositoryById(repository); Print.printJSON(getResponse(), _user_json); } catch (Exception e) { } repository = null; } /*********** * 修改 * * @return */ public void update() { try { repository = (repository == null ? new Repository() : repository); Repository re = iRepositoryService.getById(repository.getCode()); Date date = new Date(); String time = DateUtil.dateToString("yyyy-MM-dd", date); String userid = (String) getSession().get("currentUserId"); 第 页 /共 172页 User u = iUserService.getUser(userid); Dictionary dic = this.dictionaryService.getByID(repository.getType() .getId()); Unit unit = u.getUnit(); re.setDescs(repository.getDescs()); re.setName(repository.getName()); re.setType(dic); re.setUnit(unit); re.setUpdate_date(time); re.setUpdator(u); String status = iRepositoryService.updateRepository(re); Print.printText(getResponse(), status); } catch (Exception e) { e.printStackTrace(); } repository = null; } /************** * 下载 * * @return */ public InputStream getInputStream() throws Exception { RepositoryAction a = new RepositoryAction(); String path = a.getPath(); Repository re = iRepositoryService.getById(repository.getCode()); String dir = path + File.separator + re.getPath(); File f = new File(dir); return new FileInputStream(f); // 如果dir是绝对路径 // return // ServletActionContext.getServletContext().getResourceAsStream(dir); // //如果dir是Resource下的相对路径 } public String downLoad() { System.out.println("jientiejt!!!!!!!!!!"); System.out.println("code="+repository.getCode()); Repository re = 第 页 /共 172页 iRepositoryService.getById(repository.getCode()); docFileName=re.getFileName(); return "download"; } public void clear(){ HttpServletResponse response = ServletActionContext.getResponse(); //清除登陆页面缓存 response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); } /************ * 查询前8项 * * @return */ public String getTop() { clear(); try { List ar = this.iRepositoryService.getReposity(type, begin, end); net.sf.json.JSONArray json = JSONConvert.listToJSON(ar); Print.printJSON(getResponse(), json); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取字典列表 * @param dictionaryDTO * @return */ public JSONObject getDictionaryList(DictionaryDTO dictionaryDTO){ Map _queryMap = new HashMap(); _queryMap.put("Dictionary", Dictionary.class.getName()); _queryMap.put("sort", dictionaryDTO.getSort()); _queryMap.put("order", dictionaryDTO.getOrder()); _queryMap.put("code", StringUtils.isNotEmpty(dictionaryDTO.getCode())?"%" + dictionaryDTO.getCode() + "%":null); 第 页 /共 172页 _queryMap.put("name", StringUtils.isNotEmpty(dictionaryDTO.getName())?"%" + dictionaryDTO.getName() + "%":null); Dictionary d = dictionaryDTO.getParentId(); _queryMap.put("parentId", d==null?null:(StringUtils.isNotEmpty(d.getId())?d.getId():null)); List dictList = dictionaryDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "dictionary_list", dictionaryDTO.getPage(), dictionaryDTO.getRows(), _queryMap); long count = dictionaryDAO.findCountByNamedQuery( StatementTemplate.Type.DYNAMIC, "dictionary_list", _queryMap); return JSONConvert.listToJSONForEasyUIDict(count, dictList); } /** * 添加字典项 */ public String addDictionary(Dictionary dict){ String status = Utils.STATUS_FAIL; Dictionary _dict = dictionaryDAO.findUniqueBy("code",dict.getCode().toUpperCase()); if(_dict!=null){ status = Utils.STATUS_EXIST; }else{ dict.setCode(dict.getCode().toUpperCase()); dict.setCreateDate(new Date()); dict.setCreator(getCurrentUser()); if(dictionaryDAO.save(dict)){ status = Utils.STATUS_SUCCESS; } } return status; } public String deleteDictionary(DictionaryDTO dictionaryDTO){ 第 页 /共 172页 String status = Utils.STATUS_SUCCESS; String[] ids = dictionaryDTO.getIds().split(","); for(String id:ids){ if(!dictionaryDAO.delete(id)){ return Utils.STATUS_FAIL; } } return status; } /** * 修改字典项 */ public String updateDictionary(Dictionary dict){ String status = Utils.STATUS_FAIL; Map _queryMap = new HashMap(); _queryMap.put("Dictionary", Dictionary.class.getName()); _queryMap.put("id", dict.getId()); _queryMap.put("code", dict.getCode().toUpperCase()); List dictList = dictionaryDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "dictionary_hasOtherDictByCode", _queryMap); if(dictList!=null && dictList.size() > 0){ status = Utils.STATUS_EXIST; }else{ if(!dict.getId().equals(dict.getParentId().getId())){ //本身不能作为自己的分类 Dictionary _dict = dictionaryDAO.get(dict.getId()); _dict.setCode(dict.getCode().toUpperCase()); _dict.setName(dict.getName()); _dict.setRemark(dict.getRemark()); _dict.setParentId(dict.getParentId()); if(dictionaryDAO.update(_dict)){ status = Utils.STATUS_SUCCESS; } } } return status; } 第 页 /共 172页 /** * 根据id获取字典项 */ public JSONObject getDictById(Dictionary dict){ Dictionary _dict = dictionaryDAO.get(dict.getId()); return JSONConvert.objectToJSONDict(_dict); } /** * 根据父节点获取 */ public JSONArray getDictItemsByParentCode(DictionaryDTO dictionaryDTO){ Dictionary dict = dictionaryDAO.findUniqueBy("code", dictionaryDTO.getParentId().getCode()); List dictionaryList = dictionaryDAO.findBy("parentId", dict); return JSONConvert.listToJSON(dictionaryList); } public JSONArray getDictTree(DictionaryDTO dictionaryDTO){ List dictionaryList = dictionaryDAO.findBy("parentId", dictionaryDTO.getParentId()); List treeList = new ArrayList(); for(Dictionary dict:dictionaryList){ Tree tree = new Tree(); tree.setId(dict.getId()); tree.setText(dict.getName()); tree.setState(has_child(dict)?"closed":"open"); treeList.add(tree); } if("0".equals(dictionaryDTO.getParentId().getId())){ List _treeList = new ArrayList(); Tree _tree = new Tree(); _tree.setId("0"); _tree.setText("数据字典"); _tree.setChildren(treeList); _treeList.add(_tree); return JSONConvert.listToJSON(_treeList); }else{ return JSONConvert.listToJSON(treeList); } } public JSONObject getMenuList(MenuDTO menuDTO){ 第 页 /共 172页 Map _queryMap = new HashMap(); _queryMap.put("Menu", Menu.class.getName()); _queryMap.put("name", StringUtils.isNotEmpty(menuDTO.getName())?"%" + menuDTO.getName() + "%":null); _queryMap.put("sort", menuDTO.getSort()); _queryMap.put("order", menuDTO.getOrder()); Menu m = menuDTO.getParentId(); _queryMap.put("parentId", m==null?null:(StringUtils.isNotEmpty(m.getId())?m.getId():null)); List _menuList = menuDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "menu_list", menuDTO.getPage(), menuDTO.getRows(), _queryMap); long count = menuDAO.findCountByNamedQuery( StatementTemplate.Type.DYNAMIC, "menu_list", _queryMap); JSONObject _menusJSON = JSONConvert.listToJSONForEasyUIUnit(count,_menuList); return _menusJSON; } public String addMenu(Menu menu){ String status = Utils.STATUS_FAIL; Menu _menu = menuDAO.findUniqueByHQL("from Menu m where m.module=? and m.privilege=?" , menu.getModule(),menu.getPrivilege()); if(_menu!=null){ status = Utils.STATUS_EXIST; }else{ if(menuDAO.save(menu)){ status = Utils.STATUS_SUCCESS; } } return status; } 第 页 /共 172页 public String deleteMenu(MenuDTO menuDTO){ String status = Utils.STATUS_SUCCESS; String[] ids = menuDTO.getIds().split(","); for(String id:ids){ if(!menuDAO.delete(id)){ return Utils.STATUS_FAIL; } } return status; } public String updateMenu(Menu menu){ String status = Utils.STATUS_FAIL; Map _queryMap = new HashMap(); _queryMap.put("Menu", Menu.class.getName()); _queryMap.put("id", menu.getId()); _queryMap.put("type", menu.getType()); _queryMap.put("module", menu.getModule()); _queryMap.put("privilege", menu.getPrivilege()); List menuList = menuDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "menu_hasOtherMenu", _queryMap); if(menuList!=null && menuList.size() > 0){ status = Utils.STATUS_EXIST; }else{ if(!menu.getId().equals(menu.getParentId().getId())){ Menu _menu = menuDAO.get(menu.getId()); _menu.setName(menu.getName()); _menu.setUrl(menu.getUrl()); _menu.setType(menu.getType()); _menu.setModule(menu.getModule()); _menu.setPrivilege(menu.getPrivilege()); _menu.setParentId(menu.getParentId()); _menu.setSortNum(menu.getSortNum()); if(menuDAO.update(_menu)){ status = Utils.STATUS_SUCCESS; } } } 第 页 /共 172页 return status; } public JSONObject getMenuById(Menu menu){ Menu _menu = menuDAO.get(menu.getId()); return JSONConvert.objectToJSONF(_menu); } public JSONArray getMenuTree(MenuDTO menuDTO){ List menuList = menuDAO.findBy("parentId", menuDTO.getParentId()); List treeList = new ArrayList(); for(Menu menu:menuList){ Tree tree = new Tree(); tree.setId(menu.getId()); tree.setText(menu.getName()); tree.setState(has_child(menu)?"closed":"open"); treeList.add(tree); } if("0".equals(menuDTO.getParentId().getId())){ List _treeList = new ArrayList(); Tree _tree = new Tree(); _tree.setId("0"); _tree.setText("功能菜单"); _tree.setChildren(treeList); _treeList.add(_tree); return JSONConvert.listToJSON(_treeList); }else{ return JSONConvert.listToJSON(treeList); } } public JSONArray getMenuTreeForRole(MenuDTO menuDTO){ List rmList = roleMenuDAO.findByHQL(" from RoleMenu rm where rm.roleId.id=?", menuDTO.getRoleId()); List menuList = menuDAO.findBy("parentId", menuDTO.getParentId()); List treeList = new ArrayList(); for(Menu menu:menuList){ Tree tree = new Tree(); tree.setId(menu.getId()); tree.setText(menu.getName()); for(RoleMenu rm :rmList){ if(rm.getMenuId() != null){ 第 页 /共 172页 if(rm.getMenuId().getId().equals(menu.getId())){ tree.setChecked(true); break; } } } tree.setState(has_child(menu)?"closed":"open"); treeList.add(tree); } return JSONConvert.listToJSON(treeList); } private boolean has_child(Menu menu){ List menuList = menuDAO.findBy("parentId", menu); return (menuList!=null && menuList.size()>0)?true:false; } public String saveMenus(MenuDTO menuDTO){ String status = Utils.STATUS_SUCCESS; String[] ids = menuDTO.getIds().split(","); List rmList = roleMenuDAO.findByHQL(" from RoleMenu rm where rm.roleId.id=?", menuDTO.getRoleId()); for(RoleMenu rm:rmList){ roleMenuDAO.delete(rm); } for(String menuId:ids){ if(!menuId.equals("")){ RoleMenu rm = new RoleMenu(); Role r = new Role(); Menu m = new Menu(); r.setId(menuDTO.getRoleId()); m.setId(menuId); rm.setRoleId(r); rm.setMenuId(m); roleMenuDAO.save(rm); } } return status; } 第 页 /共 172页 /** * 获取信息模板列表 * @return */ public JSONObject getMsgTemplateList(MsgTemplateDTO msgTemplateDTO){ Map _queryMap = new HashMap(); _queryMap.put("MsgTemplate", MsgTemplate.class.getName()); _queryMap.put("title", StringUtils.isNotEmpty(msgTemplateDTO.getTitle())? "%"+ msgTemplateDTO.getTitle() + "%":null); Dictionary companyType = msgTemplateDTO.getCompanyType(); _queryMap.put("companyType", companyType==null?null:(StringUtils.isNotEmpty(companyType.getId())?companyType.getId():null)); Dictionary indexType = msgTemplateDTO.getIndexType(); _queryMap.put("indexType", indexType==null?null:(StringUtils.isNotEmpty(indexType.getId())?indexType.getId():null)); List _MsgTemplateList = null; System.out.println("msgTemplateDTO.getRows() = " + msgTemplateDTO.getRows()); if(msgTemplateDTO.getRows() == null){ _MsgTemplateList = msgTemplateDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "msg_template_list", _queryMap); }else{ _MsgTemplateList = msgTemplateDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "msg_template_list", msgTemplateDTO.getPage(), msgTemplateDTO.getRows(), _queryMap); } long count = msgTemplateDAO.findCountByNamedQuery( StatementTemplate.Type.DYNAMIC, "msg_template_list", _queryMap); JSONObject _msgTemplatesJSON = JSONConvert.listToJSONForEasyUI(count,_MsgTemplateList); 第 页 /共 172页 return _msgTemplatesJSON; } public String addMsgTemplate(MsgTemplate msgTemplate){ String status = Utils.STATUS_FAIL; msgTemplate.setCreateDate(new Date()); if(msgTemplateDAO.save(msgTemplate)){ status = Utils.STATUS_SUCCESS; } return status; } /** * 修改信息模板 */ public String updateMsgTemplate(MsgTemplate msgTemplate){ String status = Utils.STATUS_FAIL; MsgTemplate _msgTemplate = msgTemplateDAO.get(msgTemplate.getCode()); _msgTemplate.setCode(msgTemplate.getCode()); _msgTemplate.setTitle(msgTemplate.getTitle()); _msgTemplate.setCompanyType(msgTemplate.getCompanyType()); _msgTemplate.setContent(msgTemplate.getContent()); _msgTemplate.setIndexType(msgTemplate.getIndexType()); _msgTemplate.setType(msgTemplate.getType()); _msgTemplate.setUrl(msgTemplate.getUrl()); _msgTemplate.setYearQuater(msgTemplate.getYearQuater()); _msgTemplate.setUpdateDate(new Date()); if(msgTemplateDAO.update(_msgTemplate)){ status = Utils.STATUS_SUCCESS; } return status; } public String deleteMsgTemplate(MsgTemplateDTO msgTemplateDTO){ String status = Utils.STATUS_SUCCESS; String[] ids = msgTemplateDTO.getIds().split(","); for(String id:ids){ if(!msgTemplateDAO.delete(id)){ return Utils.STATUS_FAIL; } } 第 页 /共 172页 return status; } public JSONObject getMsgTemplateByCode(MsgTemplate msgTemplate){ MsgTemplate _msgTemplate = msgTemplateDAO.get(msgTemplate.getCode()); return JSONConvert.objectToJSON(_msgTemplate); } public IMsgTemplateDAO getMsgTemplateDAO() { return msgTemplateDAO; } public void setMsgTemplateDAO(IMsgTemplateDAO msgTemplateDAO) { this.msgTemplateDAO = msgTemplateDAO; } public JSONArray getMsgTemplateArray(MsgTemplateDTO msgTemplateDTO) { Map _queryMap = new HashMap(); _queryMap.put("MsgTemplate", MsgTemplate.class.getName()); _queryMap.put("title", StringUtils.isNotEmpty(msgTemplateDTO.getTitle())?msgTemplateDTO.getTitle() + "%":null); Dictionary companyType = msgTemplateDTO.getCompanyType(); _queryMap.put("companyType", companyType==null?null:(StringUtils.isNotEmpty(companyType.getId())?companyType.getId():null)); Dictionary indexType = msgTemplateDTO.getIndexType(); _queryMap.put("indexType", indexType==null?null:(StringUtils.isNotEmpty(indexType.getId())?indexType.getId():null)); List _MsgTemplateList = null; System.out.println("msgTemplateDTO.getRows() = " + msgTemplateDTO.getRows()); _MsgTemplateList = msgTemplateDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "msg_template_list", _queryMap); return JSONConvert.listToJSON(_MsgTemplateList); } public JSONObject getRoleList(RoleDTO roleDTO) { 第 页 /共 172页 Map _queryMap = new HashMap(); _queryMap.put("Role", Role.class.getName()); _queryMap.put("name", StringUtils.isNotEmpty(roleDTO.getName())?"%" + roleDTO.getName() + "%":null); _queryMap.put("sort", roleDTO.getSort()); _queryMap.put("order", roleDTO.getOrder()); List _roleList = roleDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "role_list", roleDTO.getPage(), roleDTO.getRows(), _queryMap); long count = roleDAO.findCountByNamedQuery( StatementTemplate.Type.DYNAMIC, "role_list", _queryMap); JSONObject _rolesJSON = JSONConvert.listToJSONForEasyUI(count,_roleList); return _rolesJSON; } public String addRole(Role role) { String status = Utils.STATUS_FAIL; Role _role = roleDAO.findUniqueBy("name",role.getName()); if(_role != null){ status = Utils.STATUS_EXIST; }else{ if(roleDAO.save(role)){ status = Utils.STATUS_SUCCESS; } } return status; } public JSONArray getRoleForSelect(RoleDTO roleDTO){ List roleList = roleDAO.getAll(); 第 页 /共 172页 return JSONConvert.listToJSON(roleList); } public String deleteRole(RoleDTO roleDTO) { String status = Utils.STATUS_SUCCESS; String[] ids = roleDTO.getIds().split(","); for(String id:ids){ if(!roleDAO.delete(id)){ return Utils.STATUS_FAIL; } } return status; } public JSONObject getRoleById(Role role) { Role _role = roleDAO.get(role.getId()); return JSONConvert.objectToJSON(_role); } public String updateRole(Role role) { String status = Utils.STATUS_FAIL; Map _queryMap = new HashMap(); _queryMap.put("Role", Role.class.getName()); _queryMap.put("id", role.getId()); _queryMap.put("name", role.getName()); List roleList = roleDAO.findByNamedQuery( StatementTemplate.Type.DYNAMIC, "role_hasOtherroleById", _queryMap); if(roleList!=null && roleList.size() > 0){ status = Utils.STATUS_EXIST; }else{ Role _role = roleDAO.get(role.getId()); _role.setId(role.getId()); _role.setName(role.getName()); _role.setRemark(role.getRemark()); if(roleDAO.update(_role)){ status = Utils.STATUS_SUCCESS; } 第 页 /共 172页 } return status; } /** * 查询语句名称缓存,不允许重复 */ private Set nameCache = new HashSet(); public void setMappingResources(String[] mappingResources) { this.mappingResources = mappingResources; } public Map getNamedHQLQueries() { return namedHQLQueries; } public Map getNamedSQLQueries() { return namedSQLQueries; } public void init() throws IOException { namedHQLQueries = new HashMap(); namedSQLQueries = new HashMap(); boolean flag = this.resourceLoader instanceof ResourcePatternResolver; for (String _resource : mappingResources) { if (flag) { Resource[] resources = ((ResourcePatternResolver) this.resourceLoader).getResources(_resource); buildMap(resources); } else { Resource resource = resourceLoader.getResource(_resource); buildMap(resource); } } //clear name cache nameCache.clear(); } 第 页 /共 172页 public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } private void buildMap(Resource[] resources) throws IOException { if (resources == null) { return; } for (Resource resource : resources) { buildMap(resource); } } private void buildMap(Resource resource) { InputSource inputSource = null; try { inputSource = new InputSource(resource.getInputStream()); XmlDocument metadataXml = MappingReader.INSTANCE.readMappingDocument(entityResolver, inputSource, new OriginImpl("file", resource.getFilename())); if (isDynamicStatementXml(metadataXml)) { final Document doc = metadataXml.getDocumentTree(); final Element dynamicHibernateStatement = doc.getRootElement(); Iterator rootChildren = dynamicHibernateStatement.elementIterator(); while (rootChildren.hasNext()) { final Element element = (Element) rootChildren.next(); final String elementName = element.getName(); if ("sql-query".equals(elementName)) { putStatementToCacheMap(resource, element, namedSQLQueries); } else if ("hql-query".equals(elementName)) { putStatementToCacheMap(resource, element, namedHQLQueries); } } } } catch (Exception e) { LOGGER.error(e.toString()); } finally { if (inputSource != null && inputSource.getByteStream() != 第 页 /共 172页 null) { try { inputSource.getByteStream().close(); } catch (IOException e) { LOGGER.error(e.toString()); } } } } private void putStatementToCacheMap(Resource resource, final Element element, Map statementMap) throws IOException { String sqlQueryName = element.attribute("name").getText(); Validate.notEmpty(sqlQueryName); if (nameCache.contains(sqlQueryName)) { throw new RuntimeException("重复的sql-query/hql-query语句定义在文件:" + resource.getURI() + "中,必须保证name的唯一."); } nameCache.add(sqlQueryName); String queryText = element.getText(); statementMap.put(sqlQueryName, queryText); } private static boolean isDynamicStatementXml(XmlDocument xmlDocument) { return "dynamic-hibernate-statement".equals(xmlDocument.getDocumentTree().getRootElement().getName()); } public InputSource resolveEntity(String publicId, String systemId) { InputSource source = null; // returning null triggers default behavior if ( systemId != null ) { LOGGER.debug( "trying to resolve system-id [" + systemId + "]" ); if ( systemId.startsWith( HOP_DYNAMIC_STATEMENT ) ) { LOGGER.debug( "recognized hop dyanmic statement namespace; attempting to resolve on classpath under com/nsc/common/dao/" ); source = resolveOnClassPath( publicId, systemId, HOP_DYNAMIC_STATEMENT ); } 第 页 /共 172页 } return source; } private InputSource resolveOnClassPath(String publicId, String systemId, String namespace) { InputSource source = null; String path = "com/nsc/common/hibernate/" + systemId.substring( namespace.length() ); InputStream dtdStream = resolveInHibernateNamespace( path ); if ( dtdStream == null ) { LOGGER.debug( "unable to locate [" + systemId + "] on classpath" ); if ( systemId.substring( namespace.length() ).indexOf( "2.0" ) > -1 ) { LOGGER.error( "Don't use old DTDs, read the Hibernate 3.x Migration Guide!" ); } } else { LOGGER.debug( "located [" + systemId + "] in classpath" ); source = new InputSource( dtdStream ); source.setPublicId( publicId ); source.setSystemId( systemId ); } return source; } protected InputStream resolveInHibernateNamespace(String path) { return this.getClass().getClassLoader().getResourceAsStream( path ); } protected InputStream resolveInLocalNamespace(String path) { try { return ConfigHelper.getUserResourceAsStream( path ); } catch ( Throwable t ) { return null; } } /** * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 第 页 /共 172页 * *@param clazz * clazz The class to introspect * @param index * the Index of the generic ddeclaration,start from 0. * @return the index generic declaration, or Object.class if cannot be * determined */ @SuppressWarnings("unchecked") public static Class getSuperClassGenricType(final Class clazz, final int index) { //返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。 Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { return Object.class; } //返回表示此类型实际类型参数的 Type 对象的数组。 Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { return Object.class; } if (!(params[index] instanceof Class)) { return Object.class; } return (Class) params[index]; } /** * 获取当前登录用户 * @return */ public User getCurrentUser(){ ActionContext ac = ActionContext.getContext(); Object user = ac.getSession().get(Utils.USER_SESSION); if(user == null){ return null; } return (User)user; 第 页 /共 172页 } /** * 生成验证码 * @param response */ public void getAuthentiCode(HttpServletResponse response){ ActionContext ace = ActionContext.getContext(); Map session = ace.getSession(); java.util.Random random = new java.util.Random(); response.addHeader("Pragma", "No-cache"); response.addHeader("Cache-Control", "no-cache"); response.addDateHeader("expires", 0); int width = 65; int height = 22; BufferedImage pic = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); Graphics gc = pic.getGraphics(); //gc.setColor(getRandColor(100, 250));//设定背景颜色 gc.setColor(new Color(150, 240, 249)); gc.fillRect(0, 0, width, height); String[] rNum = {"2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; gc.setColor(Color.black); String rt = ""; for (int i = 0; i < 4; i++) { String temp = rNum[random.nextInt(56)]; rt = rt + temp; gc.setFont(new Font("Times New Roman",Font.PLAIN, 20)); gc.drawString(temp, 13 * i + 6, 16); } gc.dispose(); rt = rt.toLowerCase(); 第 页 /共 172页 session.put(Utils.LOGIN_AUTHENTI_CODE, rt); OutputStream os = null; try { os = response.getOutputStream(); ImageIO.write(pic, "JPEG", os); } catch (IOException e) { e.printStackTrace(); } finally { try { if(os != null) { os.flush(); os.close(); os=null; } } catch (IOException e) { e.printStackTrace(); } try { response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } } } /** * 获取随机颜色 * @param fc * @param bc * @return */ private Color getRandColor(int fc, int bc) { java.util.Random rd = new java.util.Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int red = fc + rd.nextInt(bc - fc); int green = fc + rd.nextInt(bc - fc); int blue = fc + rd.nextInt(bc - fc); return new Color(red, green, blue); } 第 页 /共 172页 /** * 增加缓存服务器节点 * @author zdr */ @Override public String execute() throws Exception { cacheService = new CacheServerServiceImpl(); CacheServer cacheServer=new CacheServer(); String serverId=getRequest().getParameter("serverId").trim(); String serverName=getRequest().getParameter("serverName").trim(); String serverIp=getRequest().getParameter("serverIp").trim(); String serverPort=getRequest().getParameter("serverPort").trim(); String serverContext=getRequest().getParameter("serverContext").trim(); String orgCode=getRequest().getParameter("orgCode").trim(); String serverState=getRequest().getParameter("serverStat").trim(); String remark=getRequest().getParameter("remark").trim(); if(serverState == null){ serverState = "0"; } LogService ls=new LogServiceImpl(); String createOperator=ls.getSession().getAttribute("userName").toString(); Calendar cal = Calendar.getInstance(); // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String createDate=formatter.format(cal.getTime()); Date createdate=cal.getTime(); cacheServer.setServerID(serverId); cacheServer.setServerName(serverName); cacheServer.setServerIP(serverIp); cacheServer.setServerPort(serverPort); cacheServer.setServerContext(serverContext); cacheServer.setORGCode(orgCode); cacheServer.setServerState(Integer.parseInt(serverState)); cacheServer.setCreateOperator(createOperator); cacheServer.setCreateDate(createdate); cacheServer.setRemark(remark); 第 页 /共 172页 //System.out.println(remark); cacheService.addCacheServer(cacheServer); this.getRequest().setAttribute("message", "操作成功!!"); this.getRequest().setAttribute("url", this.getRequest().getContextPath()+"/cache/cache!findCacheServer.action"); return "message"; } /** * 管理服务器节点首页 * @author zdr * @return * @throws Exception */ public String findCacheServer() throws Exception { cacheService = new CacheServerServiceImpl(); List cacheList=null; String startPage=getRequest().getParameter("startPage"); String serverIp=getRequest().getParameter("serverIp"); if(startPage==null||startPage.equals("0")) { startPage="1"; } if(serverIp==null) { serverIp=""; } int pageSize=10; int numPage=cacheService.getFsCacheServerCount(serverIp);// 总数 int pageCount=0; pageCount = (numPage % pageSize == 0) ? (numPage / pageSize) : (numPage / pageSize + 1); if (Integer.valueOf(startPage) >= pageCount) { startPage = String.valueOf(pageCount); } cacheList=cacheService.getFsCacheServerList(serverIp,startPage, pageSize); 第 页 /共 172页 getRequest().setAttribute("serverIps", serverIp); getRequest().setAttribute("startPage", startPage); getRequest().setAttribute("pageCount", pageCount); getRequest().setAttribute("cacheList", cacheList); return "mgr"; } /** * 进入更新单个服务器页面 * @author zdr * @return * @throws Exception */ public String updateFindCacheServer() throws Exception { cacheService = new CacheServerServiceImpl(); String serverId=getRequest().getParameter("serverId"); //String startPage=getRequest().getParameter("startPage"); CacheServer cacheServer=cacheService.loadCacheServer(serverId); getRequest().setAttribute("cacheServer", cacheServer); orgCode = cacheServer.getORGCode(); orgCodeMap=new TreeMap(); UserService userService=new UserServiceImpl(); List listOrg=new ArrayList(); listOrg=userService.getAllOrg(); if(listOrg.size()!=0){ for(Organization org:listOrg){ orgCodeMap.put(org.getOrgCode(),org.getOrgName()); } } return "updateFind"; } /** * 更新服务器节点信息 第 页 /共 172页 * @author zdr * @return * @throws Exception */ public String updateCacheServer() throws Exception { cacheService = new CacheServerServiceImpl(); CacheServer cacheServer=new CacheServer(); String serverId=getRequest().getParameter("serverId").trim(); String serverName=getRequest().getParameter("serverName").trim(); String serverIp=getRequest().getParameter("serverIp").trim(); String serverPort=getRequest().getParameter("serverPort").trim(); String serverContext=getRequest().getParameter("serverContext").trim(); String orgCode=getRequest().getParameter("orgCode").trim(); String serverState=getRequest().getParameter("serverStat").trim(); String createOperator=getRequest().getParameter("createOperator").trim(); String createDate=getRequest().getParameter("createDate").trim(); String remark = getRequest().getParameter("remark"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date createTime=format.parse(createDate); LogService ls=new LogServiceImpl(); String modifyOperator=ls.getSession().getAttribute("userName").toString(); Calendar cal = Calendar.getInstance(); Date modifyDate=cal.getTime(); cacheServer.setServerID(serverId); cacheServer.setServerName(serverName); cacheServer.setServerIP(serverIp); cacheServer.setServerPort(serverPort); cacheServer.setServerContext(serverContext); cacheServer.setORGCode(orgCode); cacheServer.setServerState(Integer.parseInt(serverState)); 第 页 /共 172页 cacheServer.setCreateOperator(createOperator); cacheServer.setCreateDate(createTime); cacheServer.setLastModifyOperator(modifyOperator); cacheServer.setLastModifyDate(modifyDate); cacheServer.setRemark(remark); cacheService.updateCacheServer(cacheServer); this.getRequest().setAttribute("message", "操作成功!!"); this.getRequest().setAttribute("url", this.getRequest().getContextPath()+"/cache/cache!findCacheServer.action"); return "message"; } /** * 删除服务器节点信息 * @author zdr * @return * @throws Exception */ public String deleteServer() throws Exception { cacheService = new CacheServerServiceImpl(); String serverId=getRequest().getParameter("serverId"); String startPage=getRequest().getParameter("startPage"); CacheServer cacheServer=cacheService.loadCacheServer(serverId); cacheService.deleteCacheServer(cacheServer); getRequest().setAttribute("startPage",startPage); return "delete"; } /** * 服务器监控状态查看 * @author zdr * @return * @throws Exception */ public String findCacheMonitor() throws Exception { cacheService = new CacheServerServiceImpl(); 第 页 /共 172页 List cacheMonitorList=new ArrayList(); String startPage=getRequest().getParameter("startPage"); String serverId=getRequest().getParameter("serverId"); if(startPage==null||startPage.equals("0")) { startPage="1"; } if(serverId==null) { serverId=""; } int pageSize=10; int numPage=cacheService.getCacheMonitorCount(serverId);// 总数 int pageCount=0; pageCount = (numPage % pageSize == 0) ? (numPage / pageSize) : (numPage / pageSize + 1); if (Integer.valueOf(startPage) >= pageCount) { startPage = String.valueOf(pageCount); } cacheMonitorList=cacheService.getCacheMonitorList(serverId,startPage, pageSize); getRequest().setAttribute("serverId", serverId); getRequest().setAttribute("startPage", startPage); getRequest().setAttribute("pageCount", pageCount); getRequest().setAttribute("cacheMonitorList", cacheMonitorList); return "monitor"; } /** * 增加缓存策略节点 * @author zdr */ 第 页 /共 172页 @Override public String execute() throws Exception { cachePlotService = new CachePlotServiceImpl(); CachePlot cachePlot=new CachePlot(); CachePlotID cacheId=new CachePlotID(); String serverId=getRequest().getParameter("serverId").trim(); String appcode=getRequest().getParameter("appCode").trim(); String isRCache=getRequest().getParameter("isRCache").trim(); String isQCache=getRequest().getParameter("isQCache").trim(); String rCacheLife=getRequest().getParameter("RCacheLife"); String queryCacheLife=getRequest().getParameter("queryCacheLife"); //增加容错功能 if(rCacheLife==null || rCacheLife.trim() == "" ){ rCacheLife = "0"; } if(queryCacheLife==null || queryCacheLife.trim() == "" ){ queryCacheLife = "0"; } String remark=getRequest().getParameter("remark").trim(); LogService ls=new LogServiceImpl(); String createOperator=ls.getSession().getAttribute("userName").toString(); Calendar cal = Calendar.getInstance(); Date createdate=cal.getTime(); cacheId.setServerID(serverId); cacheId.setAppCode(appcode); cachePlot.setCachePlotID(cacheId); cachePlot.setIsReceiveCache(Integer.parseInt(isRCache)); cachePlot.setIsQueryCache(Integer.parseInt(isQCache)); cachePlot.setReceiveCacheLife(Integer.parseInt(rCacheLife)); cachePlot.setQueryCacheLife(Integer.parseInt(queryCacheLife)); cachePlot.setRemark(remark); cachePlot.setCreateOperator(createOperator); cachePlot.setCreateDate(createdate); cachePlotService.addCachePlot(cachePlot); this.getRequest().setAttribute("message", "操作成功!"); this.getRequest().setAttribute("url", this.getRequest().getContextPath()+"/cachePlot/cachePlot!findCachePlot.action"); return "message"; 第 页 /共 172页 } /** * 管理缓存策略节点首页 * @author zdr * @return * @throws Exception */ public String findCachePlot() throws Exception { cachePlotService = new CachePlotServiceImpl(); List cachePlotList=null; String startPage=getRequest().getParameter("startPage"); String appCode=getRequest().getParameter("appCode"); if(startPage==null||startPage.equals("0")) { startPage="1"; } if(appCode==null) { appCode=""; } int pageSize=10; int numPage=cachePlotService.getFsCachePlotCount(appCode);// 总数 int pageCount=0; pageCount = (numPage % pageSize == 0) ? (numPage / pageSize) : (numPage / pageSize + 1); if (Integer.valueOf(startPage) >= pageCount) { startPage = String.valueOf(pageCount); } cachePlotList=cachePlotService.getFsCachePlotList(appCode,startPage, pageSize); getRequest().setAttribute("appCodes", appCode); getRequest().setAttribute("startPage", startPage); getRequest().setAttribute("pageCount", pageCount); getRequest().setAttribute("cachePlotList", cachePlotList); 第 页 /共 172页 CacheServerService cacheService = new CacheServerServiceImpl(); FsAppcodeDefService appcodeService = new FsAppcodeDefServiceImpl(); Map cacheServerMap = new HashMap(); Map appCodeNameMap = new HashMap(); if(cachePlotList!=null && cachePlotList.size()>0){ for (Iterator iterator = cachePlotList.iterator(); iterator.hasNext();) { CachePlot cachePlot = (CachePlot) iterator.next(); if (cachePlot !=null) { CacheServer cacheServer = cacheService.loadCacheServer(cachePlot.getCachePlotID().getServerID()); if (cacheServer != null) { cacheServerMap.put(cachePlot.getCachePlotID().getServerID(), cacheServer.getServerName()); } FsAppcodeDef appcodeDef = appcodeService.getAppCodeDef(cachePlot.getCachePlotID().getAppCode()); if (appcodeDef != null) { appCodeNameMap.put(cachePlot.getCachePlotID().getAppCode(), appcodeDef.getAppName()); } } } } getRequest().setAttribute("cacheServerName", cacheServerMap); getRequest().setAttribute("appCodeName", appCodeNameMap); return "mgr"; } /** 第 页 /共 172页 * 进入更新单个缓存策略页面 * @author zdr * @return * @throws Exception */ public String updateFindCachePlot() throws Exception { cachePlotService = new CachePlotServiceImpl(); //zt String transPlotId = scanIds[0]; String serverId = transPlotId.substring(0,transPlotId.indexOf("@@@")); String appCode = transPlotId.substring(transPlotId.indexOf("@@@") + 3); // String arr=getRequest().getParameter("arr"); // String[] twoString=arr.split("_"); // String serverId=twoString[0]; // String appCode=twoString[1]; // //String startPage=getRequest().getParameter("startPage"); CachePlot cachePlot=cachePlotService.findCachePlot(serverId,appCode); getRequest().setAttribute("cachePlot", cachePlot); this.setAppCode(cachePlot.getCachePlotID().getAppCode()); //zt this.setServerId(cachePlot.getCachePlotID().getServerID()); return "updateFind"; } //另外书写的更新缓存策略 public String updateFindCachePlotToList() throws Exception { cachePlotService = new CachePlotServiceImpl(); String arr=getRequest().getParameter("arr"); String[] twoString=arr.split("_"); String serverId=twoString[0]; String appCode=twoString[1]; //String startPage=getRequest().getParameter("startPage"); CachePlot cachePlot=cachePlotService.findCachePlot(serverId,appCode); getRequest().setAttribute("cachePlot", cachePlot); 第 页 /共 172页 this.setAppCode(cachePlot.getCachePlotID().getAppCode()); getRequest().setAttribute("urladdress", this.getRequest().getContextPath()+"/cachePlot!findCachePlot.action"); return "updateFind"; } /** * 更新缓存策略信息 * @author zdr * @return * @throws Exception */ public String updateCachePlot() throws Exception { cachePlotService = new CachePlotServiceImpl(); CachePlot cachePlot = new CachePlot(); CachePlotID cacheId=new CachePlotID(); String serverId=getRequest().getParameter("serverId").trim(); String appcode=getRequest().getParameter("appCode").trim(); String isRCache=getRequest().getParameter("isRCache").trim(); String isQCache=getRequest().getParameter("isQCache").trim(); String rCacheLife=getRequest().getParameter("RCacheLife"); if(rCacheLife == null){ rCacheLife = "0"; } String queryCacheLife=getRequest().getParameter("queryCacheLife"); if(queryCacheLife == null){ queryCacheLife= "0"; } String remark=getRequest().getParameter("remark").trim(); String createOperator=getRequest().getParameter("createOperator").trim(); String createDate=getRequest().getParameter("createDate").trim(); LogService ls=new LogServiceImpl(); String modifyOperator=ls.getSession().getAttribute("userName").toString(); Calendar cal = Calendar.getInstance(); Date modifyDate=cal.getTime(); 第 页 /共 172页 cacheId.setServerID(serverId); cacheId.setAppCode(appcode); cachePlot.setCachePlotID(cacheId); cachePlot.setIsReceiveCache(Integer.parseInt(isRCache)); cachePlot.setIsQueryCache(Integer.parseInt(isQCache)); cachePlot.setReceiveCacheLife(Integer.parseInt(rCacheLife)); cachePlot.setQueryCacheLife(Integer.parseInt(queryCacheLife)); cachePlot.setRemark(remark); cachePlot.setCreateOperator(createOperator); if(!createDate.equals("null")){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date createTime=format.parse(createDate); cachePlot.setCreateDate(createTime); } cachePlot.setLastModifyOperator(modifyOperator); cachePlot.setLastModifyDate(modifyDate); cachePlotService.updateCachePlot(cachePlot); this.getRequest().setAttribute("message", "操作成功!!"); this.getRequest().setAttribute("url", this.getRequest().getContextPath()+"/cachePlot/cachePlot!findCachePlot.action"); return "message"; }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 2 人已下载

下载文档