├── .classpath ├── .gitignore ├── .project ├── .settings ├── .jsdtscope ├── org.eclipse.core.resources.prefs ├── org.eclipse.jdt.core.prefs ├── org.eclipse.m2e.core.prefs ├── org.eclipse.wst.common.component ├── org.eclipse.wst.common.project.facet.core.xml ├── org.eclipse.wst.jsdt.ui.superType.container ├── org.eclipse.wst.jsdt.ui.superType.name └── org.eclipse.wst.validation.prefs ├── pom.xml ├── readme.md └── src └── main ├── java └── org │ └── coody │ ├── framework │ ├── box │ │ ├── adapt │ │ │ └── ParamsAdapt.java │ │ ├── annotation │ │ │ ├── Around.java │ │ │ ├── InitBean.java │ │ │ ├── JsonSerialize.java │ │ │ ├── OutBean.java │ │ │ ├── PathBinding.java │ │ │ └── Transacted.java │ │ ├── cache │ │ │ └── LocalCache.java │ │ ├── constant │ │ │ └── BoxConstant.java │ │ ├── container │ │ │ ├── BeanContainer.java │ │ │ ├── MappingContainer.java │ │ │ └── TransactedThreadContainer.java │ │ ├── iface │ │ │ └── InitFace.java │ │ ├── init │ │ │ ├── BoxRute.java │ │ │ └── BoxServletListen.java │ │ ├── jdbc │ │ │ ├── JdbcHandle.java │ │ │ ├── annotation │ │ │ │ ├── Column.java │ │ │ │ └── Table.java │ │ │ ├── entity │ │ │ │ ├── JDBCEntity.java │ │ │ │ ├── Pager.java │ │ │ │ └── Where.java │ │ │ └── util │ │ │ │ └── JdbcUtil.java │ │ ├── mvc │ │ │ └── DispatServlet.java │ │ ├── proyx │ │ │ └── CglibProxy.java │ │ └── wrapper │ │ │ └── AspectWrapper.java │ ├── entity │ │ ├── BaseModel.java │ │ ├── BeanEntity.java │ │ └── Record.java │ └── util │ │ ├── AspectUtil.java │ │ ├── ClassUtil.java │ │ ├── DateUtils.java │ │ ├── EncryptUtil.java │ │ ├── JSONWriter.java │ │ ├── JUUIDUtil.java │ │ ├── MatchUtil.java │ │ ├── PrintException.java │ │ ├── PropertUtil.java │ │ ├── RequestUtil.java │ │ └── StringUtil.java │ └── web │ ├── comm │ ├── annotation │ │ ├── CacheWipe.java │ │ ├── CacheWipes.java │ │ └── CacheWrite.java │ ├── aspect │ │ ├── CacheAspect.java │ │ └── TransactedAspect.java │ ├── base │ │ └── JdbcTemplate.java │ ├── constant │ │ └── CacheFinal.java │ ├── enm │ │ └── RespEnum.java │ └── entity │ │ └── MsgEntity.java │ ├── controller │ ├── GeneralController.java │ └── IcopController.java │ ├── dao │ ├── IcopDao.java │ └── UserDao.java │ ├── domain │ ├── IcopTest.java │ └── UserInfo.java │ ├── service │ ├── IcopService.java │ └── UserService.java │ └── servlet │ └── LoadUserList.java ├── resources ├── config │ └── c3p0.properties └── log4j.xml └── webapp ├── WEB-INF ├── jsp │ └── index.jsp ├── lib │ ├── c3p0-0.9.1.2.jar │ ├── cglib-nodep-3.1.jar │ ├── fastjson-1.2.31.jar │ ├── log4j-1.2.17.jar │ └── mysql-connector-java-5.1.13.jar └── web.xml └── index.jsp /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | coody-icop 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.wst.common.project.facet.core.builder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator 25 | 26 | 27 | 28 | 29 | org.eclipse.m2e.core.maven2Builder 30 | 31 | 32 | 33 | 34 | 35 | org.eclipse.jem.workbench.JavaEMFNature 36 | org.eclipse.wst.common.modulecore.ModuleCoreNature 37 | org.eclipse.jdt.core.javanature 38 | org.eclipse.m2e.core.maven2Nature 39 | org.eclipse.wst.common.project.facet.core.nature 40 | org.eclipse.wst.jsdt.core.jsNature 41 | 42 | 43 | -------------------------------------------------------------------------------- /.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding/=UTF-8 3 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=1.8 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 13 | org.eclipse.jdt.core.compiler.source=1.8 14 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | org.coody.framework 5 | coody-icop 6 | war 7 | 1.0 8 | coody-icop 9 | http://maven.apache.org 10 | 11 | 12 | 13 | com.alibaba 14 | fastjson 15 | 1.2.46 16 | 17 | 18 | org.apache.tomcat 19 | servlet-api 20 | 6.0.53 21 | 22 | 23 | jstl 24 | jstl 25 | 1.2 26 | 27 | 28 | c3p0 29 | c3p0 30 | 0.9.1.2 31 | 32 | 33 | cglib 34 | cglib 35 | 3.2.6 36 | 37 | 38 | log4j 39 | log4j 40 | 1.2.17 41 | 42 | 43 | 44 | junit 45 | junit 46 | 3.8.1 47 | test 48 | 49 | 50 | 51 | CoodyIcop 52 | 53 | 54 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | 更新记录: 2 | 3 | 2018-02-24:初步研发,实现IOC+AOP 4 | 5 | 2018-02-25:拓展MVC,基于MVC结合ICO+AOP实现轻量化无依赖类spring开发模式 6 | 7 | 2018-02-26:整改为maven模式,并整合自写ORM框架配合aop实现事物管理。 8 | 9 | 10 | ======================================================= 11 | 12 | 1. 项目背景: 13 | 14 | 由于笔者近期参与的一些项目体系未使用到任何框架,而笔者对spring体系特别向往,故此研发本项目。 15 | 16 | 2. 功能说明: 17 | 18 | 本项目实现注解形式的bean加载、依赖注入、切面等功能。简单实现mvc。 19 | 20 | 3. 项目特点: 21 | 22 | 本项目使用cglib。秉承轻量、易用、简单、高效等原则。依赖jar:cglib-nodep-3.1.jar fastjson-1.2.31.jar log4j-1.2.17.jar 依赖jar包其余版本自行测试。 23 | 24 | 4. 环境说明: 25 | 26 | JDK1.8+ 27 | 28 | 5.目录结构: 29 | 30 | ![Image text](https://static.oschina.net/uploads/space/2018/0225/215135_sePy_3094707.png) 31 | 32 | 6. 程序架构: 33 | 34 | 由于在撰写本文背景下无作图环境,故此略去架构图。以下提供一些结构说明 35 | 36 | 1、包说明 37 | 38 | org.coody.framework.entity常用实体包。 39 | 40 | org.coody.framework.util 常用工具包 41 | 42 | org.coody.framework.box 核心实现包 43 | 44 | org.coody.framework.box.adapt 适配器包 45 | 46 | org.coody.framework.box.annotation 注解包 47 | 48 | org.coody.framework.box.container 容器包 49 | 50 | org.coody.framework.box.constant 常量包 51 | 52 | org.coody.framework.box.iface 接口包 53 | 54 | org.coody.framework.box.init 初始化入口包 55 | 56 | org.coody.framework.box.mvc MVC实现包 57 | 58 | org.coody.framework.box.proyx 动态代理包 59 | 60 | org.coody.framework.box.wrapper 包装类 61 | 62 | 2、类说明-注解 63 | 64 | org.coody.framework.box.annotation.Around环绕通知注解标识,用于切面实现 65 | 66 | org.coody.framework.box.annotation.InitBean初始化Bean。类似于spring的Service等注解,标记一个bean类 67 | 68 | org.coody.framework.box.annotation.JsonSerialize序列化JSON输出,用于controller方法标识。类似于spring的ResponseBody注解 69 | 70 | org.coody.framework.box.annotation.OutBean 输出Bean。类似于Resource/AutoWired注解 71 | 72 | org.coody.framework.box.annotation.PathBinding 输出Bean。类似于Resource/AutoWired注 73 | 74 | 3、类说明-适配器 75 | 76 | org.coody.framework.box.adapt.ParamsAdapt 参数适配器,用于MVC下参数的装载(目前只实现request、response、session三个参数的自动装载) 77 | 78 | 4、类说明-容器 79 | 80 | org.coody.framework.box.container.BeanContainer 容器,用于存储bean,类似于spring的application 81 | 82 | org.coody.framework.box.container.MappingContainer Mvc映射地址容器 83 | 84 | 5、类说明-接口 85 | 86 | org.coody.framework.box.iface.InitFace 初始化接口,凡是实现该接口的bean需实现init方法。在容器启动完成后执行。 87 | 88 | 6、类说明-启动器 89 | 90 | org.coody.framework.box.init.BoxRute 容器入口。通过该类的init(packet)方法指定扫描包路径 91 | 92 | org.coody.framework.box.init.BoxServletListen 监听器,配置在webxml用于引导容器初始化 93 | 94 | 7、类说明-mvc分发器 95 | 96 | org.coody.framework.box.mvc.DispatServlet 类似于spring的DispatServlet 97 | 98 | 8、类说明-代理工具 99 | 100 | org.coody.framework.box.proyx.CglibProxy 基于cglib字节码创建子类的实现 101 | 102 | 9、类说明-包装类 103 | 104 | org.coody.framework.box.wrapper.AspectWrapper 本处命名可能不尽规范。本类用于多切面的调度和适配 105 | 106 | 7. 实现效果: 107 | ![Image text](https://static.oschina.net/uploads/space/2018/0225/215613_79vh_3094707.png) 108 | 109 | ![Image text](https://static.oschina.net/uploads/space/2018/0225/215847_nlKD_3094707.png) 110 | 111 | 112 | 113 | 114 | 8. 版权说明: 115 | 116 | 在本项目源代码中,已有测试demo,包括mvc、切面等示例 117 | 118 | 作者:Coody 119 | 120 | 反馈邮箱:644556636@qq.com 121 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/adapt/ParamsAdapt.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.adapt; 2 | 3 | import java.util.Map; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | import javax.servlet.http.HttpSession; 8 | 9 | import org.coody.framework.util.StringUtil; 10 | 11 | /** 12 | * 参数适配器 13 | * @author admin 14 | * 15 | */ 16 | public class ParamsAdapt { 17 | 18 | 19 | public static Object[] adaptParams(Class []paramTypes,Map paras,HttpServletRequest request,HttpServletResponse response,HttpSession session){ 20 | if(StringUtil.isNullOrEmpty(paramTypes)){ 21 | return null; 22 | } 23 | if(StringUtil.isNullOrEmpty(paras)){ 24 | Object [] params=new Object[paramTypes.length]; 25 | for(int i=0;i paraType=paramTypes[i]; 27 | if(paraType.isAssignableFrom(request.getClass())){ 28 | params[i]=request; 29 | continue; 30 | } 31 | if(paraType.isAssignableFrom(response.getClass())){ 32 | params[i]=response; 33 | continue; 34 | } 35 | if(paraType.isAssignableFrom(session.getClass())){ 36 | params[i]=session; 37 | continue; 38 | } 39 | } 40 | return params; 41 | } 42 | 43 | return new Object[paramTypes.length]; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/annotation/Around.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | @Target(ElementType.METHOD) 8 | @Retention(RetentionPolicy.RUNTIME) 9 | public @interface Around { 10 | 11 | Class[] value(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/annotation/InitBean.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.TYPE) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface InitBean { 11 | 12 | String value() default ""; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/annotation/JsonSerialize.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * JSON输出 10 | * @author admin 11 | * 12 | */ 13 | @Target({ElementType.METHOD,ElementType.TYPE}) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface JsonSerialize { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/annotation/OutBean.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.FIELD) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface OutBean { 11 | String beanName() default ""; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/annotation/PathBinding.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 地址映射 10 | * @author admin 11 | * 12 | */ 13 | @Target({ElementType.METHOD,ElementType.TYPE}) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface PathBinding { 16 | 17 | String value() default ""; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/annotation/Transacted.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target({ElementType.METHOD}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface Transacted { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/cache/LocalCache.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.cache; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.List; 6 | import java.util.Set; 7 | import java.util.Timer; 8 | import java.util.TimerTask; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | 11 | import org.coody.framework.util.StringUtil; 12 | 13 | 14 | 15 | /** 16 | * @className:CacheHandler 17 | * @description:缓存操作类,对缓存进行管理,清除方式采用Timer定时的方式 18 | * @creater:Coody 19 | * @creatTime:2014年5月7日 上午9:18:54 20 | * @remark: 21 | * @version 22 | */ 23 | @SuppressWarnings("unchecked") 24 | public class LocalCache { 25 | private static final Timer timer; 26 | private static final ConcurrentHashMap map; 27 | static Object mutex = new Object(); 28 | static { 29 | timer = new Timer(); 30 | map = new ConcurrentHashMap(); 31 | } 32 | 33 | /** 34 | * 增加缓存对象 35 | * 36 | * @param key 37 | * @param ce 38 | * @param validityTime 39 | * 有效时间 40 | */ 41 | public static void setCache(String key, Object ce, 42 | int validityTime) { 43 | map.put(key, new CacheWrapper(validityTime,ce)); 44 | timer.schedule(new TimeoutTimerTask(key), validityTime * 1000); 45 | } 46 | //获取缓存KEY列表 47 | public static Set getCacheKeys() { 48 | return map.keySet(); 49 | } 50 | 51 | public static List getKeysFuzz(String patton){ 52 | List list=new ArrayList(); 53 | for (String tmpKey : map.keySet()) { 54 | if (tmpKey.contains(patton)) { 55 | list.add(tmpKey); 56 | } 57 | } 58 | if(StringUtil.isNullOrEmpty(list)){ 59 | return null; 60 | } 61 | return list; 62 | } 63 | public static Integer getKeySizeFuzz(String patton){ 64 | Integer num=0; 65 | for (String tmpKey : map.keySet()) { 66 | if (tmpKey.startsWith(patton)) { 67 | num++; 68 | } 69 | } 70 | return num; 71 | } 72 | /** 73 | * 增加缓存对象 74 | * 75 | * @param key 76 | * @param ce 77 | * @param validityTime 78 | * 有效时间 79 | */ 80 | public static void setCache(String key, Object ce) { 81 | map.put(key, new CacheWrapper(ce)); 82 | } 83 | 84 | /** 85 | * 获取缓存对象 86 | * 87 | * @param key 88 | * @return 89 | */ 90 | public static T getCache(String key) { 91 | CacheWrapper wrapper=(CacheWrapper) map.get(key); 92 | if(wrapper==null){ 93 | return null; 94 | } 95 | return (T) wrapper.getValue(); 96 | } 97 | 98 | /** 99 | * 检查是否含有制定key的缓冲 100 | * 101 | * @param key 102 | * @return 103 | */ 104 | public static boolean contains(String key) { 105 | return map.containsKey(key); 106 | } 107 | 108 | /** 109 | * 删除缓存 110 | * 111 | * @param key 112 | */ 113 | public static void delCache(String key) { 114 | map.remove(key); 115 | } 116 | 117 | /** 118 | * 删除缓存 119 | * 120 | * @param key 121 | */ 122 | public static void delCacheFuzz(String key) { 123 | for (String tmpKey : map.keySet()) { 124 | if (tmpKey.contains(key)) { 125 | map.remove(tmpKey); 126 | } 127 | } 128 | } 129 | 130 | /** 131 | * 获取缓存大小 132 | * 133 | * @param key 134 | */ 135 | public static int getCacheSize() { 136 | return map.size(); 137 | } 138 | 139 | /** 140 | * 清除全部缓存 141 | */ 142 | public static void clearCache() { 143 | map.clear(); 144 | } 145 | 146 | /** 147 | * @projName:lottery 148 | * @className:TimeoutTimerTask 149 | * @description:清除超时缓存定时服务类 150 | * @creater:Coody 151 | * @creatTime:2014年5月7日上午9:34:39 152 | * @alter:Coody 153 | * @alterTime:2014年5月7日 上午9:34:39 154 | * @remark: 155 | * @version 156 | */ 157 | static class TimeoutTimerTask extends TimerTask { 158 | private String ceKey; 159 | 160 | public TimeoutTimerTask(String key) { 161 | this.ceKey = key; 162 | } 163 | @Override 164 | public void run() { 165 | CacheWrapper cacheWrapper=(CacheWrapper) map.get(ceKey); 166 | if(cacheWrapper==null||cacheWrapper.getDate()==null){ 167 | return; 168 | } 169 | if(new Date().getTime()[] beanAnnotations = new Class[] { InitBean.class, PathBinding.class }; 16 | 17 | /** 18 | * 切面存储。key注解类 value拦截器方法 19 | */ 20 | public static final Map, Method> aspectMap = new ConcurrentHashMap, Method>(); 21 | 22 | /** 23 | * 表主键列表 24 | */ 25 | public static final String table_primary_keys="table_primary_keys"; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/container/BeanContainer.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.container; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.util.Collection; 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | import org.coody.framework.box.constant.BoxConstant; 9 | import org.coody.framework.util.PropertUtil; 10 | import org.coody.framework.util.StringUtil; 11 | 12 | @SuppressWarnings({"unchecked","rawtypes"}) 13 | public class BeanContainer { 14 | 15 | private static Map beanMap=new ConcurrentHashMap(); 16 | 17 | public static T getBean(Class cla){ 18 | String beanName=getBeanName(cla); 19 | return (T) beanMap.get(beanName); 20 | } 21 | 22 | public static T getBean(String beanName){ 23 | return (T) beanMap.get(beanName); 24 | } 25 | public static void writeBean(String beanName,Object bean){ 26 | beanMap.put(beanName, bean); 27 | } 28 | public static boolean containsBean(String beanName){ 29 | return beanMap.containsKey(beanName); 30 | } 31 | public static Collection getBeans(){ 32 | return beanMap.values(); 33 | } 34 | public static String getBeanName(Class clazz){ 35 | for (Class annotationClass : BoxConstant.beanAnnotations) { 36 | Annotation initBean = clazz.getAnnotation(annotationClass); 37 | if (StringUtil.isNullOrEmpty(initBean)) { 38 | continue; 39 | } 40 | String beanName = (String) PropertUtil.getFieldValue(initBean, "value"); 41 | if (StringUtil.isNullOrEmpty(beanName)) { 42 | beanName = clazz.getName(); 43 | } 44 | return beanName; 45 | } 46 | return null; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/container/MappingContainer.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.container; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | 9 | import org.coody.framework.entity.BaseModel; 10 | import org.coody.framework.entity.BeanEntity; 11 | 12 | @SuppressWarnings("unchecked") 13 | public class MappingContainer { 14 | 15 | private static Map mvcMap = new ConcurrentHashMap(); 16 | 17 | public static T getMapping(String path) { 18 | return (T) mvcMap.get(path); 19 | } 20 | 21 | public static void writeMapping(MvcMapping mvcMapping) { 22 | mvcMap.put(mvcMapping.getPath(), mvcMapping); 23 | } 24 | 25 | public static boolean containsPath(String path) { 26 | return mvcMap.containsKey(path); 27 | } 28 | 29 | public static Collection getBeans() { 30 | return mvcMap.values(); 31 | } 32 | 33 | @SuppressWarnings("serial") 34 | public static class MvcMapping extends BaseModel { 35 | 36 | private String path; 37 | 38 | private Method method; 39 | 40 | private Object bean; 41 | 42 | private List paramTypes; 43 | 44 | 45 | public String getPath() { 46 | return path; 47 | } 48 | 49 | public void setPath(String path) { 50 | this.path = path; 51 | } 52 | 53 | public Method getMethod() { 54 | return method; 55 | } 56 | 57 | public void setMethod(Method method) { 58 | this.method = method; 59 | } 60 | 61 | public Object getBean() { 62 | return bean; 63 | } 64 | 65 | public void setBean(Object bean) { 66 | this.bean = bean; 67 | } 68 | 69 | public List getParamTypes() { 70 | return paramTypes; 71 | } 72 | 73 | public void setParamTypes(List paramTypes) { 74 | this.paramTypes = paramTypes; 75 | } 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/container/TransactedThreadContainer.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.container; 2 | 3 | import java.sql.Connection; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import javax.sql.DataSource; 10 | 11 | import org.coody.framework.util.StringUtil; 12 | 13 | 14 | @SuppressWarnings({ "unchecked" }) 15 | public class TransactedThreadContainer { 16 | 17 | 18 | 19 | public static ThreadLocal> threadTransactedContainer = new ThreadLocal>(); 20 | 21 | /** 22 | * 是否需要事物 23 | */ 24 | private static final String needTransacted="needTransacted"; 25 | 26 | /** 27 | * connection容器 28 | */ 29 | private static final String connectionContainer="connectionContainer"; 30 | 31 | /** 32 | * 判断是否存在事物控制 33 | * @return 34 | */ 35 | public static boolean hasTransacted(){ 36 | 37 | Map threadContainer=threadTransactedContainer.get(); 38 | if(StringUtil.isNullOrEmpty(threadContainer)){ 39 | return false; 40 | } 41 | Boolean needTransacteder=(Boolean) threadContainer.get(needTransacted); 42 | if(needTransacteder==null){ 43 | return false; 44 | } 45 | return needTransacteder; 46 | } 47 | 48 | public static void writeHasTransacted(){ 49 | Map threadContainer=threadTransactedContainer.get(); 50 | if(StringUtil.isNullOrEmpty(threadContainer)){ 51 | threadContainer=new HashMap(); 52 | } 53 | threadContainer.put(needTransacted, true); 54 | threadTransactedContainer.set(threadContainer); 55 | } 56 | 57 | public static void writeDataSource(DataSource source,Connection connection){ 58 | Map threadContainer=threadTransactedContainer.get(); 59 | if(StringUtil.isNullOrEmpty(threadContainer)){ 60 | threadContainer=new HashMap(); 61 | } 62 | Map connectionMap=(Map) threadContainer.get(connectionContainer); 63 | if(StringUtil.isNullOrEmpty(connectionMap)){ 64 | connectionMap=new HashMap(); 65 | } 66 | connectionMap.put(source, connection); 67 | threadContainer.put(connectionContainer, connectionMap); 68 | threadTransactedContainer.set(threadContainer); 69 | } 70 | 71 | /** 72 | * 从线程容器获取连接 73 | * @param source 74 | * @return 75 | */ 76 | public static Connection getConnection(DataSource source){ 77 | Map threadContainer=threadTransactedContainer.get(); 78 | if(StringUtil.isNullOrEmpty(threadContainer)){ 79 | return null; 80 | } 81 | Map connectionMap=(Map) threadContainer.get(connectionContainer); 82 | if(StringUtil.isNullOrEmpty(connectionMap)){ 83 | connectionMap=new HashMap(); 84 | } 85 | return connectionMap.get(source); 86 | } 87 | 88 | /** 89 | * 从线程容器获取所有连接 90 | * @param source 91 | * @return 92 | */ 93 | public static List getConnections(){ 94 | Map threadContainer=threadTransactedContainer.get(); 95 | if(StringUtil.isNullOrEmpty(threadContainer)){ 96 | return null; 97 | } 98 | Map connectionMap=(Map) threadContainer.get(connectionContainer); 99 | if(StringUtil.isNullOrEmpty(connectionMap)){ 100 | connectionMap=new HashMap(); 101 | } 102 | return new ArrayList(connectionMap.values()); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/iface/InitFace.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.iface; 2 | 3 | public interface InitFace { 4 | 5 | public void init(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/init/BoxRute.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.init; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.Method; 5 | import java.util.ArrayList; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | import org.apache.log4j.Logger; 11 | import org.coody.framework.box.annotation.Around; 12 | import org.coody.framework.box.annotation.InitBean; 13 | import org.coody.framework.box.annotation.OutBean; 14 | import org.coody.framework.box.annotation.PathBinding; 15 | import org.coody.framework.box.constant.BoxConstant; 16 | import org.coody.framework.box.container.BeanContainer; 17 | import org.coody.framework.box.container.MappingContainer; 18 | import org.coody.framework.box.iface.InitFace; 19 | import org.coody.framework.box.proyx.CglibProxy; 20 | import org.coody.framework.util.ClassUtil; 21 | import org.coody.framework.util.PrintException; 22 | import org.coody.framework.util.PropertUtil; 23 | import org.coody.framework.util.StringUtil; 24 | 25 | public class BoxRute { 26 | 27 | private static final Logger logger = Logger.getLogger(BoxRute.class); 28 | 29 | static CglibProxy proxy = new CglibProxy(); 30 | 31 | public static void init(String ...packets) throws Exception { 32 | Set> clazzs =new HashSet>(); 33 | 34 | for(String packet:packets){ 35 | Set> clazzsTemp=ClassUtil.getClasses(packet); 36 | clazzs.addAll(clazzsTemp); 37 | } 38 | if (StringUtil.isNullOrEmpty(clazzs)) { 39 | return; 40 | } 41 | initAspect(clazzs); 42 | initClass(clazzs); 43 | initField(); 44 | initMvc(); 45 | initRun(clazzs); 46 | } 47 | 48 | public static void initAspect(Set> clas) { 49 | if (StringUtil.isNullOrEmpty(clas)) { 50 | return; 51 | } 52 | for (Class cla : clas) { 53 | InitBean initBean = cla.getAnnotation(InitBean.class); 54 | if (StringUtil.isNullOrEmpty(initBean)) { 55 | continue; 56 | } 57 | Method[] methods = cla.getDeclaredMethods(); 58 | if (StringUtil.isNullOrEmpty(methods)) { 59 | continue; 60 | } 61 | for (Method method : methods) { 62 | Around around = method.getAnnotation(Around.class); 63 | if (around == null) { 64 | continue; 65 | } 66 | if (StringUtil.isNullOrEmpty(around.value())) { 67 | continue; 68 | } 69 | for (Class clazz : around.value()) { 70 | BoxConstant.aspectMap.put(clazz, method); 71 | } 72 | } 73 | } 74 | } 75 | 76 | public static void initClass(Set> clas) throws Exception { 77 | if (StringUtil.isNullOrEmpty(clas)) { 78 | return; 79 | } 80 | for (Class cla : clas) { 81 | String beanName = BeanContainer.getBeanName(cla); 82 | if (StringUtil.isNullOrEmpty(beanName)) { 83 | continue; 84 | } 85 | if (BeanContainer.containsBean(beanName)) { 86 | logger.error("存在重复的bean:" + beanName); 87 | continue; 88 | } 89 | BeanContainer.writeBean(beanName, proxy.getProxy(cla)); 90 | } 91 | } 92 | 93 | public static void initRun(Set> clas) { 94 | if (StringUtil.isNullOrEmpty(clas)) { 95 | return; 96 | } 97 | for (Class cla : clas) { 98 | if (!InitFace.class.isAssignableFrom(cla)) { 99 | continue; 100 | } 101 | try { 102 | InitFace face = BeanContainer.getBean(cla); 103 | if (StringUtil.isNullOrEmpty(face)) { 104 | continue; 105 | } 106 | face.init(); 107 | } catch (Exception e) { 108 | PrintException.printException(logger, e); 109 | } 110 | } 111 | } 112 | 113 | public static void initField() throws Exception { 114 | for (Object bean : BeanContainer.getBeans()) { 115 | List fields = loadFields(bean.getClass()); 116 | if (StringUtil.isNullOrEmpty(fields)) { 117 | continue; 118 | } 119 | for (Field field : fields) { 120 | OutBean writeBean = field.getAnnotation(OutBean.class); 121 | if (StringUtil.isNullOrEmpty(writeBean)) { 122 | continue; 123 | } 124 | String beanName = writeBean.beanName(); 125 | if (StringUtil.isNullOrEmpty(beanName)) { 126 | beanName = field.getType().getName(); 127 | } 128 | Object writeValue = null; 129 | field.setAccessible(true); 130 | if (!BeanContainer.containsBean(beanName)) { 131 | writeValue = proxy.getProxy(field.getClass()); 132 | BeanContainer.writeBean(beanName, writeValue); 133 | } 134 | writeValue = BeanContainer.getBean(beanName); 135 | field.set(bean, writeValue); 136 | } 137 | } 138 | } 139 | 140 | public static void initMvc() throws Exception { 141 | for (Object bean : BeanContainer.getBeans()) { 142 | if (StringUtil.isNullOrEmpty(bean)) { 143 | continue; 144 | } 145 | PathBinding classBinding = bean.getClass().getAnnotation(PathBinding.class); 146 | if (StringUtil.isNullOrEmpty(classBinding)) { 147 | continue; 148 | } 149 | Method[] methods = bean.getClass().getDeclaredMethods(); 150 | for (Method method : methods) { 151 | PathBinding methodBinding = method.getAnnotation(PathBinding.class); 152 | if (StringUtil.isNullOrEmpty(methodBinding)) { 153 | continue; 154 | } 155 | String path = formatPath(classBinding.value() + "/" + methodBinding.value()); 156 | if(MappingContainer.containsPath(path)){ 157 | logger.error("该地址已注册:"+path); 158 | continue; 159 | } 160 | MappingContainer.MvcMapping mapping=new MappingContainer.MvcMapping(); 161 | mapping.setBean(bean); 162 | mapping.setPath(path); 163 | mapping.setMethod(method); 164 | mapping.setParamTypes(PropertUtil.getMethodParas(method)); 165 | MappingContainer.writeMapping(mapping); 166 | } 167 | } 168 | } 169 | 170 | private static String formatPath(String path) { 171 | if (StringUtil.isNullOrEmpty(path)) { 172 | return null; 173 | } 174 | path = path.replace("\\", "/"); 175 | while (path.contains("//")) { 176 | path = path.replace("//", "/"); 177 | } 178 | if(!path.startsWith("/")){ 179 | path="/"+path; 180 | } 181 | return path; 182 | } 183 | 184 | public static List loadFields(Class clazz) { 185 | List fields = new ArrayList(); 186 | Field[] fieldArgs = clazz.getDeclaredFields(); 187 | for (Field f : fieldArgs) { 188 | fields.add(f); 189 | } 190 | Class superClass = clazz.getSuperclass(); 191 | if (superClass == null) { 192 | return fields; 193 | } 194 | List childFields = loadFields(superClass); 195 | if (StringUtil.isNullOrEmpty(childFields)) { 196 | return fields; 197 | } 198 | fields.addAll(childFields); 199 | return fields; 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/init/BoxServletListen.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.init; 2 | 3 | import javax.servlet.ServletContextEvent; 4 | import javax.servlet.ServletContextListener; 5 | 6 | import org.apache.log4j.Logger; 7 | import org.coody.framework.util.StringUtil; 8 | 9 | public class BoxServletListen implements ServletContextListener { 10 | 11 | Logger logger = Logger.getLogger(BoxServletListen.class); 12 | 13 | public void contextDestroyed(ServletContextEvent arg0) { 14 | System.out.println("运行contextDestroyed"); 15 | } 16 | 17 | public void contextInitialized(ServletContextEvent event) { 18 | try { 19 | String packet = event.getServletContext().getInitParameter("scanPacket"); 20 | if (StringUtil.isNullOrEmpty(packet)) { 21 | logger.error("启动参数:scanPacket为空"); 22 | return; 23 | } 24 | String[] packets = packet.split(","); 25 | BoxRute.init(packets); 26 | } catch (Exception e) { 27 | // TODO Auto-generated catch block 28 | e.printStackTrace(); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/jdbc/annotation/Column.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.jdbc.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 用于标记domain类的字段。 10 | * @author Administrator 11 | * 12 | */ 13 | @Target(ElementType.FIELD) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface Column { 16 | /** 17 | * 字段在数据库对应的列名 18 | * @return 19 | */ 20 | String value() default ""; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/jdbc/annotation/Table.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.jdbc.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 用于domain实体类标记对应表名 10 | * @author Administrator 11 | * 12 | */ 13 | @Target(ElementType.TYPE) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface Table { 16 | String value() default ""; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/jdbc/entity/JDBCEntity.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.jdbc.entity; 2 | 3 | 4 | public class JDBCEntity { 5 | 6 | private String sql; 7 | 8 | private Object[]params; 9 | 10 | public JDBCEntity(String sql,Object[] params){ 11 | this.sql=sql; 12 | this.params=params; 13 | } 14 | 15 | public String getSql() { 16 | return sql; 17 | } 18 | 19 | public void setSql(String sql) { 20 | this.sql = sql; 21 | } 22 | public Object[] getParams() { 23 | return params; 24 | } 25 | 26 | public void setParams(Object[] params) { 27 | this.params = params; 28 | } 29 | 30 | 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/jdbc/entity/Pager.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.jdbc.entity; 2 | 3 | import java.util.List; 4 | 5 | import org.coody.framework.entity.BaseModel; 6 | 7 | @SuppressWarnings("serial") 8 | public class Pager extends BaseModel { 9 | 10 | private Integer totalRows; 11 | private Integer pageSize = 10; 12 | private Integer currentPage; 13 | private Integer totalPage=1; 14 | private Integer startRow; 15 | private Integer formNumber; 16 | private Integer viewBegin=1; 17 | private Integer viewEnd=1; 18 | private List data; 19 | 20 | 21 | 22 | public Integer getViewBegin() { 23 | return viewBegin; 24 | } 25 | 26 | 27 | public void setViewBegin(Integer viewBegin) { 28 | this.viewBegin = viewBegin; 29 | } 30 | 31 | 32 | public Integer getViewEnd() { 33 | return viewEnd; 34 | } 35 | 36 | 37 | public void setViewEnd(Integer viewEnd) { 38 | this.viewEnd = viewEnd; 39 | } 40 | 41 | 42 | public Pager(Integer pageSize) { 43 | super(); 44 | this.currentPage = 1; 45 | this.startRow = 0; 46 | this.pageSize = pageSize; 47 | } 48 | 49 | 50 | public Pager(Integer pageSize, Integer currentPage) { 51 | super(); 52 | if(currentPage==null||currentPage<1){ 53 | currentPage=1; 54 | } 55 | if(pageSize==null||pageSize>100){ 56 | pageSize=20; 57 | } 58 | this.pageSize = pageSize; 59 | this.currentPage = currentPage; 60 | } 61 | 62 | 63 | public Pager() { 64 | this.currentPage = 1; 65 | this.startRow = 0; 66 | } 67 | 68 | @SuppressWarnings("unchecked") 69 | public List getData() { 70 | return (List) data; 71 | } 72 | 73 | public void setData(List data) { 74 | this.data = data; 75 | } 76 | 77 | public Integer getCurrentPage() { 78 | return currentPage; 79 | } 80 | 81 | public void setCurrentPage(Integer currPage) { 82 | if(currPage==null||currPage<1){ 83 | currPage=1; 84 | } 85 | this.currentPage = currPage; 86 | } 87 | 88 | public Integer getPageSize() { 89 | return pageSize; 90 | } 91 | 92 | public void setPageSize(Integer pageSize) { 93 | if(pageSize==null){ 94 | pageSize=20; 95 | } 96 | if(pageSize>100){ 97 | pageSize=100; 98 | } 99 | this.pageSize = pageSize; 100 | } 101 | 102 | public Integer getStartRow() { 103 | return startRow != 0 ? startRow : (currentPage - 1) * pageSize; 104 | } 105 | 106 | public void setStartRow(Integer startRow) { 107 | this.startRow = startRow; 108 | } 109 | 110 | public Integer getTotalPage() { 111 | return totalPage; 112 | } 113 | 114 | public void setTotalPage(Integer totalPage) { 115 | this.totalPage = totalPage; 116 | } 117 | 118 | public Integer getTotalRows() { 119 | return totalRows; 120 | } 121 | 122 | public void setTotalRows(Integer totalRows) { 123 | this.totalRows = totalRows; 124 | try { 125 | this.totalPage = totalRows / pageSize; 126 | Integer mod = totalRows % pageSize; 127 | if (mod > 0) { 128 | this.totalPage++; 129 | } 130 | if (this.totalPage == 0) { 131 | this.totalPage = 1; 132 | } 133 | if (this.currentPage > totalPage) { 134 | this.currentPage = totalPage; 135 | } 136 | this.startRow = (currentPage - 1) * pageSize; 137 | if (this.startRow < 0) { 138 | startRow = 0; 139 | } 140 | if (this.currentPage == 0 || this.currentPage < 0) { 141 | currentPage = 1; 142 | } 143 | } catch (Exception e) { 144 | } 145 | if(currentPage>2){ 146 | viewBegin=currentPage-2; 147 | } 148 | viewEnd=totalPage; 149 | if((totalPage-currentPage)>2){ 150 | viewEnd=currentPage+2; 151 | } 152 | } 153 | 154 | public Integer getFormNumber() { 155 | return formNumber; 156 | } 157 | 158 | public void setFormNumber(Integer formNumber) { 159 | this.formNumber = formNumber; 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/jdbc/entity/Where.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.jdbc.entity; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import org.coody.framework.entity.BaseModel; 8 | 9 | 10 | @SuppressWarnings("serial") 11 | public class Where extends BaseModel { 12 | private List wheres = new ArrayList(); 13 | 14 | /** 15 | * 设置参数 16 | * 17 | * @param fieldName 18 | * 字段名 19 | * @param symbol 20 | * 操作符 21 | * @param fieldValues 22 | * 字段值 23 | */ 24 | public Where set(String fieldName, String symbol, Object... fieldValues) { 25 | ThisWhere thisWhere = new ThisWhere(); 26 | thisWhere.setFieldName(fieldName); 27 | thisWhere.setSymbol(symbol); 28 | if (fieldValues != null) { 29 | List values=new ArrayList(); 30 | for (Object obj:fieldValues) { 31 | if(obj instanceof Collection){ 32 | for (Object o:(Collection)obj) { 33 | values.add(o); 34 | } 35 | continue; 36 | } 37 | if(obj.getClass().isArray()){ 38 | for (Object o:(Object[])obj) { 39 | values.add(o); 40 | } 41 | continue; 42 | } 43 | values.add(obj); 44 | } 45 | if(values.size()>1){ 46 | thisWhere.setSymbol("in"); 47 | } 48 | thisWhere.setFieldValues(values); 49 | } 50 | wheres.add(thisWhere); 51 | return this; 52 | } 53 | 54 | /** 55 | * 设置参数,默认条件为等于 56 | * 57 | * @param fieldName 58 | * 字段名 59 | * @param fieldValue 60 | * 字段值 61 | */ 62 | public Where set(String fieldName, Object fieldValue) { 63 | return set(fieldName, "=", fieldValue); 64 | } 65 | 66 | public List getWheres() { 67 | return wheres; 68 | } 69 | 70 | public void setWheres(List wheres) { 71 | this.wheres = wheres; 72 | } 73 | 74 | public void clear(){ 75 | wheres.clear(); 76 | } 77 | 78 | public static class ThisWhere { 79 | private String fieldName; 80 | private String symbol; 81 | private List fieldValues; 82 | 83 | public String getFieldName() { 84 | return fieldName; 85 | } 86 | 87 | public void setFieldName(String fieldName) { 88 | this.fieldName = fieldName; 89 | } 90 | 91 | public String getSymbol() { 92 | return symbol; 93 | } 94 | 95 | public void setSymbol(String symbol) { 96 | this.symbol = symbol; 97 | } 98 | 99 | public List getFieldValues() { 100 | return fieldValues; 101 | } 102 | 103 | public void setFieldValues(List fieldValues) { 104 | this.fieldValues = fieldValues; 105 | } 106 | } 107 | 108 | } 109 | 110 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/jdbc/util/JdbcUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.jdbc.util; 2 | 3 | import java.beans.BeanInfo; 4 | import java.beans.Introspector; 5 | import java.beans.PropertyDescriptor; 6 | import java.lang.annotation.Annotation; 7 | import java.text.MessageFormat; 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | import org.coody.framework.box.jdbc.annotation.Column; 14 | import org.coody.framework.box.jdbc.annotation.Table; 15 | import org.coody.framework.box.jdbc.entity.JDBCEntity; 16 | import org.coody.framework.box.jdbc.entity.Pager; 17 | import org.coody.framework.box.jdbc.entity.Where; 18 | import org.coody.framework.entity.BeanEntity; 19 | import org.coody.framework.util.PropertUtil; 20 | import org.coody.framework.util.StringUtil; 21 | 22 | 23 | public class JdbcUtil { 24 | 25 | 26 | 27 | 28 | 29 | 30 | /** 31 | * 是否反驼峰表名 32 | */ 33 | private static final boolean isUnParseTable=true; 34 | /** 35 | * 是否反驼峰字段名 36 | */ 37 | private static final boolean isUnParseField=false; 38 | 39 | 40 | /** 41 | * 获取模型对应的数据库表名 42 | * 43 | * @param obj 44 | * @return 45 | */ 46 | public static String getTableName(Object obj) { 47 | try { 48 | Class clazz=obj.getClass(); 49 | if(obj instanceof Class){ 50 | clazz=(Class) obj; 51 | } 52 | String modelName=clazz.getSimpleName(); 53 | if(isUnParseTable){ 54 | return unParsParaName(modelName); 55 | } 56 | return modelName; 57 | } catch (Exception e) { 58 | 59 | } 60 | return null; 61 | } 62 | /** 63 | * 根据字段名获取数据库列名 64 | * @param fieldName 65 | * @return 66 | */ 67 | private static String getColumnName(String fieldName){ 68 | if(!isUnParseField){ 69 | return fieldName; 70 | } 71 | return unParsParaName(fieldName); 72 | } 73 | /** 74 | * 下划线命名转驼峰式 75 | * 76 | * @param paraName 77 | * @return 78 | */ 79 | private static String parsParaName(String paraName) { 80 | if (paraName == null) { 81 | return null; 82 | } 83 | if (paraName.indexOf("_") > -1) { 84 | String[] paraNames = paraName.split("_"); 85 | if (paraNames.length > 1) { 86 | StringBuilder sb = new StringBuilder(); 87 | sb.append(paraNames[0]); 88 | for (int i = 1; i < paraNames.length; i++) { 89 | sb.append(firstUpcase(paraNames[i])); 90 | } 91 | return sb.toString(); 92 | } 93 | } 94 | return paraName; 95 | } 96 | 97 | /** 98 | * 驼峰式命名转下划线 99 | * 100 | * @param paraName 101 | * @return 102 | */ 103 | public static String unParsParaName(String paraName) { 104 | char[] chrs = paraName.toCharArray(); 105 | StringBuilder sb = new StringBuilder(); 106 | for (int i = 0; i < chrs.length; i++) { 107 | char chr = chrs[i]; 108 | if (i != 0 && Character.isUpperCase(chr)) { 109 | sb.append("_"); 110 | } 111 | sb.append(String.valueOf(chr).toLowerCase()); 112 | } 113 | return sb.toString(); 114 | } 115 | /** 116 | * 根据数据库列名获取对象字段名 117 | */ 118 | public static String getFieldName(String columnName){ 119 | if(isUnParseField){ 120 | return parsParaName(columnName); 121 | } 122 | return columnName; 123 | } 124 | /** 125 | * 获取模型对应的数据库表名 126 | * 127 | * @param obj 128 | * @return 129 | */ 130 | public static String getTableName(Class clazz) { 131 | try { 132 | Table table = (Table) clazz.getAnnotation(Table.class); 133 | if (!StringUtil.isNullOrEmpty(table)) { 134 | if (!StringUtil.isNullOrEmpty(table.value())) { 135 | return table.value(); 136 | } 137 | } 138 | return getTableName(clazz.getSimpleName()); 139 | } catch (Exception e) { 140 | 141 | } 142 | return null; 143 | } 144 | /** 145 | * 获取模型对于数据库字段名 146 | * 147 | * @param field 148 | * @return 149 | */ 150 | public static String getColumnName(BeanEntity field) { 151 | Annotation[] annots = field.getFieldAnnotations(); 152 | if (StringUtil.isNullOrEmpty(annots)) { 153 | return getColumnName(field.getFieldName()); 154 | } 155 | for (Annotation annot : annots) { 156 | if (annot instanceof Column) { 157 | String fieldName = ((Column) annot).value(); 158 | if (!StringUtil.isNullOrEmpty(fieldName)) { 159 | return fieldName; 160 | } 161 | } 162 | } 163 | return getColumnName(field.getFieldName()); 164 | } 165 | 166 | 167 | /** 168 | * 对象转为map 169 | * 170 | * @param obj 171 | * @return 172 | */ 173 | public static Map objToSqlParaMap(Object obj) { 174 | try { 175 | BeanInfo sourceBean = Introspector.getBeanInfo(obj.getClass(), 176 | java.lang.Object.class); 177 | PropertyDescriptor[] sourceProperty = sourceBean 178 | .getPropertyDescriptors(); 179 | if (sourceProperty == null) { 180 | return null; 181 | } 182 | Map map = new HashMap( 183 | sourceProperty.length * 2); 184 | for (PropertyDescriptor tmp : sourceProperty) { 185 | map.put(getColumnName(tmp.getName()), tmp.getReadMethod() 186 | .invoke(obj)); 187 | } 188 | return map; 189 | } catch (Exception e) { 190 | 191 | return null; 192 | } 193 | } 194 | 195 | /** 196 | * 首个字符串大写 197 | * 198 | * @param s 199 | * @return 200 | */ 201 | public static String firstUpcase(String s) { 202 | if (Character.isUpperCase(s.charAt(0))) { 203 | return s; 204 | } 205 | return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))) 206 | .append(s.substring(1)).toString(); 207 | } 208 | 209 | 210 | 211 | 212 | /** 213 | * 解析分页条件 214 | * 215 | * @param pager 216 | * @return 217 | */ 218 | public static String parsPagerSQL(Pager pager) { 219 | // 封装分页条件 220 | if (StringUtil.isNullOrEmpty(pager.getCurrentPage())) { 221 | pager.setCurrentPage(1); 222 | } 223 | if (StringUtil.isNullOrEmpty(pager.getPageSize())) { 224 | pager.setPageSize(10); 225 | } 226 | Integer startRows = (pager.getCurrentPage() - 1) * pager.getPageSize(); 227 | return MessageFormat.format(" limit {0},{1} ", 228 | String.valueOf(startRows), String.valueOf(pager.getPageSize())); 229 | } 230 | 231 | /** 232 | * 解析对象条件、where条件、分页条件 233 | * 234 | * @param obj 235 | * 对象条件 236 | * @param where 237 | * where条件 238 | * @param pager 239 | * 分页条件 240 | * @return 241 | */ 242 | public static JDBCEntity parseSQL(Object obj, Where where, Pager pager, 243 | String orderField, Boolean isDesc) { 244 | if (obj == null) { 245 | return null; 246 | } 247 | // 获取表名 248 | String tableName = getTableName(obj); 249 | StringBuilder sb = new StringBuilder(MessageFormat.format( 250 | "select * from {0} where 1=1 ", tableName)); 251 | List params=new ArrayList(); 252 | // 封装对象内置条件,默认以等于 253 | if (!(obj instanceof java.lang.Class)) { 254 | List prpres = PropertUtil.getBeanFields(obj); 255 | if (prpres == null || prpres.isEmpty()) { 256 | return null; 257 | } 258 | for (BeanEntity entity : prpres) { 259 | if (entity.getFieldValue() == null) { 260 | continue; 261 | } 262 | sb.append(MessageFormat.format(" and {0}=? ", 263 | JdbcUtil.getColumnName(entity))); 264 | params.add(entity.getFieldValue()); 265 | } 266 | } 267 | // 封装where条件 268 | if (!StringUtil.isNullOrEmpty(where) 269 | && !StringUtil.isNullOrEmpty(where.getWheres())) { 270 | List wheres = where.getWheres(); 271 | for (Where.ThisWhere childWhere : wheres) { 272 | sb.append(MessageFormat.format(" and {0} {1} ", 273 | childWhere.getFieldName(), childWhere.getSymbol())); 274 | if (StringUtil.isNullOrEmpty(childWhere.getFieldValues())) { 275 | continue; 276 | } 277 | String inParaSql = StringUtil.getInPara(childWhere 278 | .getFieldValues().size()); 279 | sb.append(MessageFormat.format(" ({0}) ", inParaSql)); 280 | for (Object value : childWhere.getFieldValues()) { 281 | params.add(value); 282 | } 283 | } 284 | } 285 | // 封装排序条件 286 | if (!StringUtil.isNullOrEmpty(orderField)) { 287 | sb.append(MessageFormat.format(" order by {0}", orderField)); 288 | if (isDesc != null && isDesc) { 289 | sb.append(" desc "); 290 | } 291 | } 292 | // 封装分页条件 293 | if (!StringUtil.isNullOrEmpty(pager)) { 294 | sb.append(parsPagerSQL(pager)); 295 | } 296 | return new JDBCEntity(sb.toString(), params.toArray()); 297 | } 298 | 299 | /** 300 | * map转为对象 301 | * 302 | * @param cla 303 | * @param sourceMap 304 | * @return 305 | */ 306 | @SuppressWarnings("unchecked") 307 | public static T parseBean(Class cla, Map sourceMap) { 308 | if (StringUtil.findNull(cla, sourceMap) > -1) { 309 | return null; 310 | } 311 | try { 312 | List entitys = PropertUtil.getBeanFields(cla); 313 | Object obj = cla.newInstance(); 314 | for (BeanEntity entity : entitys) { 315 | Object value = sourceMap.get(getFieldName(entity.getFieldName())); 316 | PropertUtil.setProperties(obj, entity.getFieldName(), value); 317 | } 318 | return (T) obj; 319 | } catch (Exception e) { 320 | 321 | return null; 322 | } 323 | } 324 | 325 | /** 326 | * map转为对象 327 | * 328 | * @param cla 329 | * @param sourceMap 330 | * @return 331 | */ 332 | @SuppressWarnings("unchecked") 333 | public static List parseBeans(Class cla, List> sourceMaps) { 334 | if (StringUtil.findNull(cla, sourceMaps) > -1) { 335 | return null; 336 | } 337 | List lines=new ArrayList(); 338 | for(Map line:sourceMaps){ 339 | try { 340 | lines.add((T) parseBean(cla, line)); 341 | } catch (Exception e) { 342 | // TODO: handle exception 343 | } 344 | } 345 | if(StringUtil.isNullOrEmpty(lines)){ 346 | return null; 347 | } 348 | return lines; 349 | } 350 | 351 | 352 | } 353 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/mvc/DispatServlet.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.mvc; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServlet; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.apache.log4j.Logger; 11 | import org.coody.framework.box.adapt.ParamsAdapt; 12 | import org.coody.framework.box.annotation.JsonSerialize; 13 | import org.coody.framework.box.container.MappingContainer; 14 | import org.coody.framework.util.StringUtil; 15 | 16 | import com.alibaba.fastjson.JSON; 17 | 18 | @SuppressWarnings("serial") 19 | public class DispatServlet extends HttpServlet{ 20 | 21 | Logger logger=Logger.getLogger(DispatServlet.class); 22 | 23 | public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 24 | request.setCharacterEncoding("UTF-8"); 25 | response.setCharacterEncoding("UTF-8"); 26 | String path=request.getServletPath(); 27 | logger.debug("收到请求:"+path); 28 | if(!MappingContainer.containsPath(path)){ 29 | response.getWriter().print("page not found"); 30 | response.setStatus(404); 31 | return; 32 | } 33 | MappingContainer.MvcMapping mapping=MappingContainer.getMapping(path); 34 | try { 35 | Object[] params=ParamsAdapt.adaptParams(mapping.getMethod().getParameterTypes(), null, request, response, request.getSession()); 36 | Object result=mapping.getMethod().invoke(mapping.getBean(), params); 37 | if(result==null){ 38 | return; 39 | } 40 | JsonSerialize jsonSerialize=mapping.getMethod().getAnnotation(JsonSerialize.class); 41 | if(jsonSerialize!=null){ 42 | response.setContentType("application/Json"); 43 | String json=JSON.toJSONString(result); 44 | response.getWriter().print(json); 45 | return; 46 | } 47 | String viewFileName=StringUtil.toString(result); 48 | if(StringUtil.isNullOrEmpty(viewFileName)){ 49 | response.getWriter().print("page not found"); 50 | response.setStatus(404); 51 | return; 52 | } 53 | String viewPath=getServletConfig().getInitParameter("viewPath"); 54 | String respFile=viewPath+"/"+viewFileName; 55 | request.getRequestDispatcher(respFile).forward(request, response); 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } 59 | } 60 | 61 | public void init(){} 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/proyx/CglibProxy.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.proyx; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Method; 5 | import java.util.ArrayList; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | import java.util.concurrent.ConcurrentHashMap; 11 | 12 | import org.coody.framework.box.constant.BoxConstant; 13 | import org.coody.framework.box.container.BeanContainer; 14 | import org.coody.framework.box.wrapper.AspectWrapper; 15 | import org.coody.framework.util.PropertUtil; 16 | import org.coody.framework.util.StringUtil; 17 | 18 | import net.sf.cglib.proxy.Enhancer; 19 | import net.sf.cglib.proxy.MethodInterceptor; 20 | import net.sf.cglib.proxy.MethodProxy; 21 | 22 | public class CglibProxy implements MethodInterceptor { 23 | 24 | 25 | /** 26 | * key拦截方法,value拦截器的方法 27 | */ 28 | public static final Map> interceptMap = new ConcurrentHashMap>(); 29 | 30 | public Object getProxy(Class clazz) throws InstantiationException, IllegalAccessException { 31 | Method[] methods = clazz.getDeclaredMethods(); 32 | if (StringUtil.isNullOrEmpty(methods)) { 33 | return clazz.newInstance(); 34 | } 35 | boolean needAspect = false; 36 | for (Method method : methods) { 37 | Annotation[] arounds = method.getAnnotations(); 38 | for (Annotation around : arounds) { 39 | if (!BoxConstant.aspectMap.containsKey(around.annotationType())) { 40 | continue; 41 | } 42 | needAspect = true; 43 | Method aspectMethod = BoxConstant.aspectMap.get(around.annotationType()); 44 | if (interceptMap.containsKey(method)) { 45 | interceptMap.get(method).add(aspectMethod); 46 | continue; 47 | } 48 | Set aspectMethods = new HashSet(); 49 | aspectMethods.add(aspectMethod); 50 | interceptMap.put(method, aspectMethods); 51 | } 52 | } 53 | if (!needAspect) { 54 | return clazz.newInstance(); 55 | } 56 | Enhancer enhancer = new Enhancer(); 57 | // 设置需要创建子类的类 58 | enhancer.setSuperclass(clazz); 59 | enhancer.setCallback(this); 60 | // 通过字节码技术动态创建子类实例 61 | return enhancer.create(); 62 | } 63 | 64 | // 拦截父类所有方法的调用 65 | public Object intercept(Object bean, Method method, Object[] params, MethodProxy proxy) throws Throwable { 66 | if (!interceptMap.containsKey(method)) { 67 | return proxy.invokeSuper(bean, params); 68 | } 69 | List invokeMethods = new ArrayList(interceptMap.get(method)); 70 | Method invokeMethod = invokeMethods.get(0); 71 | invokeMethods.remove(0); 72 | Class clazz = PropertUtil.getClass(invokeMethod); 73 | Object invokeBean = BeanContainer.getBean(clazz); 74 | AspectWrapper wrapper = new AspectWrapper(); 75 | wrapper.setBean(bean); 76 | wrapper.setMethod(method); 77 | wrapper.setParams(params); 78 | wrapper.setProxy(proxy); 79 | wrapper.setClazz(bean.getClass()); 80 | AspectWrapper childWrapper = parseAspect(bean,wrapper, invokeMethods); 81 | if (childWrapper != null) { 82 | wrapper.setBean(invokeBean); 83 | wrapper.setChildAspect(childWrapper); 84 | } 85 | return invokeMethod.invoke(invokeBean, wrapper); 86 | } 87 | 88 | private AspectWrapper parseAspect(Object lastBean,AspectWrapper baseWrapper, List invokeMethods) { 89 | if (StringUtil.isNullOrEmpty(invokeMethods)) { 90 | return null; 91 | } 92 | Method currentAspectMethod = invokeMethods.get(0); 93 | invokeMethods.remove(0); 94 | AspectWrapper wrapper = new AspectWrapper(); 95 | wrapper.setBean(baseWrapper.getBean()); 96 | wrapper.setMethod(baseWrapper.getMethod()); 97 | wrapper.setParams(baseWrapper.getParams()); 98 | wrapper.setProxy(baseWrapper.getProxy()); 99 | wrapper.setClazz(baseWrapper.getClazz()); 100 | wrapper.setCurrentAspectMethod(currentAspectMethod); 101 | AspectWrapper childWrapper = parseAspect(lastBean,baseWrapper, invokeMethods); 102 | if (childWrapper != null) { 103 | wrapper.setChildAspect(childWrapper); 104 | return wrapper; 105 | } 106 | wrapper.setBean(lastBean); 107 | return wrapper; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/box/wrapper/AspectWrapper.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.box.wrapper; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import org.coody.framework.entity.BaseModel; 6 | 7 | import net.sf.cglib.proxy.MethodProxy; 8 | 9 | @SuppressWarnings("serial") 10 | public class AspectWrapper extends BaseModel{ 11 | 12 | private Object bean; 13 | private Method method; 14 | private MethodProxy proxy; 15 | private Class clazz; 16 | private Object[] params; 17 | private Method currentAspectMethod; 18 | private AspectWrapper childAspect; 19 | 20 | 21 | 22 | 23 | public Class getClazz() { 24 | return clazz; 25 | } 26 | public void setClazz(Class clazz) { 27 | this.clazz = clazz; 28 | } 29 | public Method getCurrentAspectMethod() { 30 | return currentAspectMethod; 31 | } 32 | public void setCurrentAspectMethod(Method currentAspectMethod) { 33 | this.currentAspectMethod = currentAspectMethod; 34 | } 35 | public AspectWrapper getChildAspect() { 36 | return childAspect; 37 | } 38 | public void setChildAspect(AspectWrapper childAspect) { 39 | this.childAspect = childAspect; 40 | } 41 | public Object getBean() { 42 | return bean; 43 | } 44 | public void setBean(Object bean) { 45 | this.bean = bean; 46 | } 47 | public Method getMethod() { 48 | return method; 49 | } 50 | public void setMethod(Method method) { 51 | this.method = method; 52 | } 53 | public MethodProxy getProxy() { 54 | return proxy; 55 | } 56 | public void setProxy(MethodProxy proxy) { 57 | this.proxy = proxy; 58 | } 59 | public Object[] getParams() { 60 | return params; 61 | } 62 | public void setParams(Object[] params) { 63 | this.params = params; 64 | } 65 | 66 | public Object invoke() throws Throwable{ 67 | if(childAspect!=null){ 68 | return childAspect.getCurrentAspectMethod().invoke(bean, childAspect); 69 | } 70 | return proxy.invokeSuper(bean, params); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/entity/BaseModel.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | import org.coody.framework.util.PropertUtil; 8 | import org.coody.framework.util.StringUtil; 9 | 10 | import com.alibaba.fastjson.annotation.JSONField; 11 | 12 | @SuppressWarnings("serial") 13 | public class BaseModel implements Serializable{ 14 | 15 | 16 | @SuppressWarnings("unchecked") 17 | @JSONField(serialize=false) 18 | public T initModel(){ 19 | List beanEntitys=PropertUtil.getBeanFields(this); 20 | try { 21 | for(BeanEntity field:beanEntitys){ 22 | if(!StringUtil.isNullOrEmpty(field.getFieldValue())){ 23 | continue; 24 | } 25 | if(Number.class.isAssignableFrom(field.getFieldType())){ 26 | PropertUtil.setProperties(this, field.getFieldName(),PropertUtil.parseValue(0, field.getFieldType())); 27 | } 28 | if(Date.class.isAssignableFrom(field.getFieldType())){ 29 | PropertUtil.setProperties(this, field.getFieldName(), new Date() ); 30 | } 31 | if(String.class.isAssignableFrom(field.getFieldType())){ 32 | PropertUtil.setProperties(this, field.getFieldName(), ""); 33 | } 34 | } 35 | } catch (Exception e) { 36 | } 37 | return (T) this; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/entity/BeanEntity.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.entity; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Field; 5 | 6 | import org.coody.framework.util.StringUtil; 7 | 8 | @SuppressWarnings("serial") 9 | public class BeanEntity extends BaseModel{ 10 | 11 | private String fieldName; 12 | private Object fieldValue; 13 | private Class fieldType; 14 | private Annotation[] fieldAnnotations; 15 | private Field sourceField; 16 | 17 | public Annotation getAnnotation(Class clazz){ 18 | if(StringUtil.isNullOrEmpty(fieldAnnotations)){ 19 | return null; 20 | } 21 | for (Annotation annotation:fieldAnnotations) { 22 | if(clazz.isAssignableFrom(annotation.annotationType())){ 23 | return annotation; 24 | } 25 | } 26 | return null; 27 | } 28 | public Field getSourceField() { 29 | return sourceField; 30 | } 31 | public void setSourceField(Field sourceField) { 32 | this.sourceField = sourceField; 33 | } 34 | public String getFieldName() { 35 | return fieldName; 36 | } 37 | public void setFieldName(String fieldName) { 38 | this.fieldName = fieldName; 39 | } 40 | public Object getFieldValue() { 41 | return fieldValue; 42 | } 43 | public void setFieldValue(Object fieldValue) { 44 | this.fieldValue = fieldValue; 45 | } 46 | public Class getFieldType() { 47 | return fieldType; 48 | } 49 | public void setFieldType(Class fieldType) { 50 | this.fieldType = fieldType; 51 | } 52 | public Annotation[] getFieldAnnotations() { 53 | return fieldAnnotations; 54 | } 55 | public void setFieldAnnotations(Annotation[] fieldAnnotations) { 56 | this.fieldAnnotations = fieldAnnotations; 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/entity/Record.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.entity; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | import org.coody.framework.util.PropertUtil; 9 | 10 | public class Record implements Map { 11 | private Map map = new HashMap(); 12 | 13 | public Record() { 14 | } 15 | 16 | public Record(Map map) { 17 | if (map == null) { 18 | return; 19 | } 20 | this.map = map; 21 | } 22 | 23 | public int size() { 24 | return map.size(); 25 | } 26 | 27 | public boolean isEmpty() { 28 | return map.isEmpty(); 29 | } 30 | 31 | public boolean containsKey(Object key) { 32 | return map.containsKey(key); 33 | } 34 | 35 | public Object get(Object key) { 36 | return map.get(key); 37 | } 38 | 39 | public Object put(String key, Object value) { 40 | return map.put(key, value); 41 | } 42 | 43 | public Object remove(Object key) { 44 | return map.remove(key); 45 | } 46 | 47 | public void putAll(Map m) { 48 | map.putAll(m); 49 | } 50 | 51 | public Set keySet() { 52 | return map.keySet(); 53 | } 54 | 55 | public Collection values() { 56 | return map.values(); 57 | } 58 | 59 | public Set> entrySet() { 60 | return map.entrySet(); 61 | } 62 | 63 | public boolean containsValue(Object value) { 64 | return map.containsValue(value); 65 | } 66 | 67 | public void clear() { 68 | map.clear(); 69 | } 70 | 71 | public Map getMap() { 72 | return map; 73 | } 74 | 75 | public void setMap(Map map) { 76 | this.map = map; 77 | } 78 | 79 | public Object parsBean(Class cla) { 80 | return PropertUtil.mapToModel(map,cla); 81 | } 82 | } 83 | 84 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/AspectUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.coody.framework.entity.BeanEntity; 8 | import org.coody.web.comm.constant.CacheFinal; 9 | 10 | public class AspectUtil { 11 | 12 | public static ThreadLocal> moduleThread = new ThreadLocal>(); 13 | 14 | public static String getFieldKey(Class clazz, Method method, Object[] paras, String key, String[] fields) { 15 | if (StringUtil.isNullOrEmpty(key)) { 16 | key = getMethodKey(clazz, method); 17 | key = key.replace(".", "_"); 18 | key = key.replace(",", "_"); 19 | } 20 | StringBuilder paraKey = new StringBuilder(); 21 | for (String field : fields) { 22 | Object paraValue = AspectUtil.getMethodPara(method, field, paras); 23 | if (StringUtil.isNullOrEmpty(paraValue)) { 24 | paraValue = ""; 25 | } 26 | paraKey.append("_").append(JSONWriter.write(paraValue)); 27 | } 28 | key = key + "_" + EncryptUtil.md5Code(paraKey.toString()); 29 | return key; 30 | } 31 | 32 | // 将对象内所有字段名、字段值拼接成字符串,用于缓存Key 33 | public static String getBeanKey(Object... obj) { 34 | if (StringUtil.isNullOrEmpty(obj)) { 35 | return ""; 36 | } 37 | String str = JSONWriter.write(obj); 38 | return EncryptUtil.md5Code(str); 39 | } 40 | 41 | public static String getMethodKey(Class clazz, Method method) { 42 | StringBuilder sb = new StringBuilder(); 43 | sb.append(clazz.getName()).append(".").append(method.getName()); 44 | Class[] paraTypes = method.getParameterTypes(); 45 | sb.append("("); 46 | if (!StringUtil.isNullOrEmpty(paraTypes)) { 47 | for (int i = 0; i < paraTypes.length; i++) { 48 | sb.append(paraTypes[i].getName()); 49 | if (i < paraTypes.length - 1) { 50 | sb.append(","); 51 | } 52 | } 53 | } 54 | sb.append(")"); 55 | return CacheFinal.AUTO_CACHE_KEY + "-" + sb.toString(); 56 | } 57 | 58 | public static Object getMethodPara(Method method, String fieldName, Object[] args) { 59 | List beanEntitys = PropertUtil.getMethodParas(method); 60 | if (StringUtil.isNullOrEmpty(beanEntitys)) { 61 | return ""; 62 | } 63 | String[] fields = fieldName.split("\\."); 64 | BeanEntity entity = (BeanEntity) PropertUtil.getByList(beanEntitys, "fieldName", fields[0]); 65 | if (StringUtil.isNullOrEmpty(entity)) { 66 | return ""; 67 | } 68 | Object para = args[beanEntitys.indexOf(entity)]; 69 | if (fields.length > 1 && para != null) { 70 | for (int i = 1; i < fields.length; i++) { 71 | para = PropertUtil.getFieldValue(para, fields[i]); 72 | } 73 | } 74 | return para; 75 | } 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/ClassUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.io.File; 4 | import java.io.FileFilter; 5 | import java.io.IOException; 6 | import java.net.JarURLConnection; 7 | import java.net.URL; 8 | import java.net.URLDecoder; 9 | import java.util.Enumeration; 10 | import java.util.LinkedHashSet; 11 | import java.util.Set; 12 | import java.util.jar.JarEntry; 13 | import java.util.jar.JarFile; 14 | 15 | public class ClassUtil { 16 | 17 | /** 18 | * 从包package中获取所有的Class 19 | * 20 | * @param pack 21 | * @return 22 | */ 23 | public static Set> getClasses(String pack) { 24 | 25 | // 第一个class类的集合 26 | Set> classes = new LinkedHashSet>(); 27 | // 是否循环迭代 28 | boolean recursive = true; 29 | // 获取包的名字 并进行替换 30 | String packageName = pack; 31 | String packageDirName = packageName.replace('.', '/'); 32 | // 定义一个枚举的集合 并进行循环来处理这个目录下的things 33 | Enumeration dirs; 34 | try { 35 | dirs = Thread.currentThread().getContextClassLoader().getResources( 36 | packageDirName); 37 | // 循环迭代下去 38 | while (dirs.hasMoreElements()) { 39 | // 获取下一个元素 40 | URL url = dirs.nextElement(); 41 | // 得到协议的名称 42 | String protocol = url.getProtocol(); 43 | // 如果是以文件的形式保存在服务器上 44 | if ("file".equals(protocol)) { 45 | // 获取包的物理路径 46 | String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); 47 | // 以文件的方式扫描整个包下的文件 并添加到集合中 48 | findAndAddClassesInPackageByFile(packageName, filePath, 49 | recursive, classes); 50 | } else if ("jar".equals(protocol)) { 51 | // 如果是jar包文件 52 | // 定义一个JarFile 53 | JarFile jar; 54 | try { 55 | // 获取jar 56 | jar = ((JarURLConnection) url.openConnection()) 57 | .getJarFile(); 58 | // 从此jar包 得到一个枚举类 59 | Enumeration entries = jar.entries(); 60 | // 同样的进行循环迭代 61 | while (entries.hasMoreElements()) { 62 | // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 63 | JarEntry entry = entries.nextElement(); 64 | String name = entry.getName(); 65 | // 如果是以/开头的 66 | if (name.charAt(0) == '/') { 67 | // 获取后面的字符串 68 | name = name.substring(1); 69 | } 70 | // 如果前半部分和定义的包名相同 71 | if (name.startsWith(packageDirName)) { 72 | int idx = name.lastIndexOf('/'); 73 | // 如果以"/"结尾 是一个包 74 | if (idx != -1) { 75 | // 获取包名 把"/"替换成"." 76 | packageName = name.substring(0, idx) 77 | .replace('/', '.'); 78 | } 79 | // 如果可以迭代下去 并且是一个包 80 | if ((idx != -1) || recursive) { 81 | // 如果是一个.class文件 而且不是目录 82 | if (name.endsWith(".class") 83 | && !entry.isDirectory()) { 84 | // 去掉后面的".class" 获取真正的类名 85 | String className = name.substring( 86 | packageName.length() + 1, name 87 | .length() - 6); 88 | try { 89 | // 添加到classes 90 | classes.add(Class 91 | .forName(packageName + '.' 92 | + className)); 93 | } catch (ClassNotFoundException e) { 94 | // log 95 | // .error("添加用户自定义视图类错误 找不到此类的.class文件"); 96 | e.printStackTrace(); 97 | } 98 | } 99 | } 100 | } 101 | } 102 | } catch (IOException e) { 103 | // log.error("在扫描用户定义视图时从jar包获取文件出错"); 104 | e.printStackTrace(); 105 | } 106 | } 107 | } 108 | } catch (IOException e) { 109 | e.printStackTrace(); 110 | } 111 | 112 | return classes; 113 | } 114 | 115 | /** 116 | * 以文件的形式来获取包下的所有Class 117 | * 118 | * @param packageName 119 | * @param packagePath 120 | * @param recursive 121 | * @param classes 122 | */ 123 | public static void findAndAddClassesInPackageByFile(String packageName, 124 | String packagePath, final boolean recursive, Set> classes) { 125 | // 获取此包的目录 建立一个File 126 | File dir = new File(packagePath); 127 | // 如果不存在或者 也不是目录就直接返回 128 | if (!dir.exists() || !dir.isDirectory()) { 129 | // log.warn("用户定义包名 " + packageName + " 下没有任何文件"); 130 | return; 131 | } 132 | // 如果存在 就获取包下的所有文件 包括目录 133 | File[] dirfiles = dir.listFiles(new FileFilter() { 134 | // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) 135 | public boolean accept(File file) { 136 | return (recursive && file.isDirectory()) 137 | || (file.getName().endsWith(".class")); 138 | } 139 | }); 140 | // 循环所有文件 141 | for (File file : dirfiles) { 142 | // 如果是目录 则继续扫描 143 | if (file.isDirectory()) { 144 | findAndAddClassesInPackageByFile(packageName + "." 145 | + file.getName(), file.getAbsolutePath(), recursive, 146 | classes); 147 | } else { 148 | // 如果是java类文件 去掉后面的.class 只留下类名 149 | String className = file.getName().substring(0, 150 | file.getName().length() - 6); 151 | try { 152 | // 添加到集合中去 153 | //classes.add(Class.forName(packageName + '.' + className)); 154 | //经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净 155 | classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); 156 | } catch (ClassNotFoundException e) { 157 | // log.error("添加用户自定义视图类错误 找不到此类的.class文件"); 158 | e.printStackTrace(); 159 | } 160 | } 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/DateUtils.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | 7 | /** 8 | * 日期类型与字符串类型相互转换 9 | */ 10 | public class DateUtils { 11 | 12 | 13 | /** 14 | * yyyy-MM-dd hh:mm:ss 15 | */ 16 | public static String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; 17 | 18 | public static String DATE_PATTERN = "yyyy-MM-dd"; 19 | 20 | public static String getWeek(Date date) { 21 | final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; 22 | Calendar calendar = Calendar.getInstance(); 23 | calendar.setTime(date); 24 | int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1; 25 | if (dayOfWeek < 0) 26 | dayOfWeek = 0; 27 | return dayNames[dayOfWeek]; 28 | } 29 | 30 | /** 31 | * 获取当前日期 32 | * 33 | * @return 34 | */ 35 | public static String getDateString() { 36 | return toString(new Date(), "yyyy-MM-dd"); 37 | } 38 | 39 | /** 40 | * 时间增减 41 | * 42 | * @param date 43 | * @param changeDay 44 | * @return 45 | */ 46 | public static Date changeDay(Date date, Integer changeDay) { 47 | Calendar c = Calendar.getInstance(); 48 | c.setTime(date); 49 | c.add(Calendar.DATE, changeDay); 50 | return c.getTime(); 51 | } 52 | 53 | /** 54 | * 获取某日开始时间 55 | * 56 | * @return 57 | */ 58 | public static Date getDayFirstTime(Date date) { 59 | Calendar todayStart = Calendar.getInstance(); 60 | todayStart.setTime(date); 61 | todayStart.set(Calendar.HOUR_OF_DAY, 0); 62 | todayStart.set(Calendar.MINUTE, 0); 63 | todayStart.set(Calendar.SECOND, 0); 64 | todayStart.set(Calendar.MILLISECOND, 0); 65 | return todayStart.getTime(); 66 | } 67 | 68 | public static Date getDayFirstTime() { 69 | return getDayFirstTime(new Date()); 70 | } 71 | 72 | /** 73 | * 获取某日结束时间 74 | * 75 | * @param date 76 | * @return 77 | */ 78 | public static Date getDayLastTime(Date date) { 79 | Calendar todayEnd = Calendar.getInstance(); 80 | todayEnd.setTime(date); 81 | todayEnd.set(Calendar.HOUR_OF_DAY, 23); 82 | todayEnd.set(Calendar.MINUTE, 59); 83 | todayEnd.set(Calendar.SECOND, 59); 84 | todayEnd.set(Calendar.MILLISECOND, 999); 85 | return todayEnd.getTime(); 86 | } 87 | 88 | /** 89 | * 时间转字符串 90 | * 91 | * @param date 92 | * @param format 93 | * @return 94 | */ 95 | public static String toString(Date date, String format) { 96 | if (date == null) { 97 | return null; 98 | } 99 | SimpleDateFormat sfDate = new SimpleDateFormat(format); 100 | return sfDate.format(date); 101 | } 102 | 103 | public static String toString(Date date) { 104 | return toString(date, DATETIME_PATTERN); 105 | } 106 | 107 | /** 108 | * 转换为时间 109 | */ 110 | public static Date toDate(Object value) { 111 | if (value == null) { 112 | return null; 113 | } 114 | try { 115 | Class clazz = value.getClass(); 116 | if (clazz.isPrimitive()) { 117 | if (value.toString().length() == 13) { 118 | return new Date(Long.valueOf(value.toString())); 119 | } 120 | } 121 | if (MatchUtil.isMatcher(value.toString(), "\\d{13}")) { 122 | value = new Date(Long.valueOf(value.toString())); 123 | return (Date) value; 124 | } 125 | if (MatchUtil.isMatcher(value.toString(), "\\d{8}")) { 126 | value = new SimpleDateFormat("yyyyMMdd").parse(value.toString()); 127 | return (Date) value; 128 | } 129 | if (MatchUtil.isMatcher(value.toString(), "\\d{14}")) { 130 | value = new SimpleDateFormat("yyyyMMddHHmmss").parse(value.toString()); 131 | return (Date) value; 132 | } 133 | if (MatchUtil.isMatcher(value.toString(), "\\d{17}")) { 134 | value = new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(value.toString()); 135 | return (Date) value; 136 | } 137 | if (MatchUtil.isMatcher(value.toString(), "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")) { 138 | value = new SimpleDateFormat("yyyy-MM-dd").parse(value.toString()); 139 | return (Date) value; 140 | } 141 | if (MatchUtil.isMatcher(value.toString(), 142 | "^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D*")) { 143 | value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value.toString()); 144 | return (Date) value; 145 | } 146 | return (Date) value; 147 | } catch (Exception e) { 148 | return null; 149 | } 150 | } 151 | 152 | public static String getDayCode() { 153 | return toString(getDayFirstTime(), DATE_PATTERN); 154 | } 155 | 156 | public static String getWeekCode() { 157 | return toString(getWeekFirstTime(), DATE_PATTERN); 158 | } 159 | 160 | public static Date getWeekFirstTime() { 161 | return getWeekFirstTime(new Date()); 162 | } 163 | 164 | public static Date getWeekFirstTime(Date date) { 165 | Calendar currentDate = Calendar.getInstance(); 166 | currentDate.setTime(date); 167 | currentDate.setFirstDayOfWeek(Calendar.MONDAY); 168 | currentDate.set(Calendar.HOUR_OF_DAY, 0); 169 | currentDate.set(Calendar.MINUTE, 0); 170 | currentDate.set(Calendar.SECOND, 0); 171 | currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); 172 | return (Date) currentDate.getTime(); 173 | } 174 | 175 | public static Date getMonthFirstTime() { 176 | return getMonthFirstTime(new Date()); 177 | } 178 | 179 | public static String getMonthCode() { 180 | return toString(getMonthFirstTime(), DATE_PATTERN); 181 | } 182 | 183 | public static Date getMonthFirstTime(Date date) { 184 | Calendar currentDate = Calendar.getInstance(); 185 | currentDate.setTime(date); 186 | currentDate.set(Calendar.DAY_OF_MONTH, 1); 187 | currentDate.set(Calendar.HOUR_OF_DAY, 0); 188 | currentDate.set(Calendar.MINUTE, 0); 189 | currentDate.set(Calendar.SECOND, 0); 190 | return currentDate.getTime(); 191 | } 192 | 193 | 194 | } 195 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/EncryptUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.net.URLEncoder; 4 | import java.security.MessageDigest; 5 | 6 | 7 | 8 | public final class EncryptUtil { 9 | 10 | 11 | 12 | public final static String CHARSET = "UTF-8"; 13 | 14 | private EncryptUtil() { 15 | throw new Error("Utility classes should not instantiated!"); 16 | } 17 | 18 | 19 | public static String md5Code(String pwd) { 20 | try { 21 | MessageDigest md = MessageDigest.getInstance("MD5"); 22 | md.update(pwd.getBytes(CHARSET)); 23 | byte b[] = md.digest(); 24 | 25 | int i; 26 | 27 | StringBuffer buf = new StringBuffer(""); 28 | for (int offset = 0; offset < b.length; offset++) { 29 | i = b[offset]; 30 | if (i < 0) 31 | i += 256; 32 | if (i < 16) 33 | buf.append("0"); 34 | buf.append(Integer.toHexString(i)); 35 | } 36 | return buf.toString(); 37 | 38 | } catch (Exception e) { 39 | 40 | } 41 | return ""; 42 | } 43 | 44 | private static String textCode(String s, String key) { 45 | String str = ""; 46 | int ch; 47 | if (key.length() == 0) { 48 | return s; 49 | } else if (!s.equals(null)) { 50 | for (int i = 0, j = 0; i < s.length(); i++, j++) { 51 | if (j > key.length() - 1) { 52 | j = j % key.length(); 53 | } 54 | ch = s.codePointAt(i) + key.codePointAt(j); 55 | if (ch > 65535) { 56 | ch = ch % 65535;// ch - 33 = (ch - 33) % 95 ; 57 | } 58 | str += (char) ch; 59 | } 60 | } 61 | return str; 62 | 63 | } 64 | 65 | @SuppressWarnings("unused") 66 | private static String textDeCode(String s, String key) { 67 | String str = ""; 68 | int ch; 69 | if (key.length() == 0) { 70 | return s; 71 | } else if (!s.equals(key)) { 72 | for (int i = 0, j = 0; i < s.length(); i++, j++) { 73 | if (j > key.length() - 1) { 74 | j = j % key.length(); 75 | } 76 | ch = (s.codePointAt(i) + 65535 - key.codePointAt(j)); 77 | if (ch > 65535) { 78 | ch = ch % 65535;// ch - 33 = (ch - 33) % 95 ; 79 | } 80 | str += (char) ch; 81 | } 82 | } 83 | return str; 84 | } 85 | 86 | public static String customEnCode(String str) { 87 | try { 88 | str = md5Code(str); 89 | str = textCode(str, str); 90 | str = str.substring(1, str.length() - 1); 91 | str = URLEncoder.encode(str, "UTF-8").replace("%", "") 92 | .toLowerCase(); 93 | str = md5Code(str); 94 | return str; 95 | } catch (Exception e) { 96 | return ""; 97 | } 98 | 99 | } 100 | 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/JSONWriter.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.lang.reflect.Array; 4 | import java.text.CharacterIterator; 5 | import java.text.SimpleDateFormat; 6 | import java.text.StringCharacterIterator; 7 | import java.util.Date; 8 | import java.util.Iterator; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | import org.coody.framework.entity.BaseModel; 13 | import org.coody.framework.entity.BeanEntity; 14 | 15 | /** 16 | * @remark json工具类,此工具类修改过N次。改的脖子好痛啊,总算走向成熟。 17 | * @author Coody 18 | * @email 644556636@qq.com 19 | * @blog 54sb.org 20 | */ 21 | public class JSONWriter { 22 | static char[] hex = "0123456789ABCDEF".toCharArray(); 23 | 24 | public static String write(Object object) { 25 | return value(object); 26 | } 27 | 28 | public static String write(long n) { 29 | return write(new Long(n)); 30 | } 31 | 32 | public static String write(double d) { 33 | return write(new Double(d)); 34 | } 35 | 36 | public static String write(char c) { 37 | return write(new Character(c)); 38 | } 39 | 40 | public static String write(boolean b) { 41 | return write(Boolean.valueOf(b)); 42 | } 43 | 44 | private static String value(Object object) { 45 | if (object == null) { 46 | return add("\"\""); 47 | } 48 | if (object instanceof Class) { 49 | return string(object); 50 | } 51 | if (object instanceof Boolean) { 52 | return bool(((Boolean) object).booleanValue()); 53 | } 54 | if (object instanceof Number) { 55 | return add(object); 56 | } 57 | if (object instanceof String) { 58 | return string(object); 59 | } 60 | if (object instanceof Character) { 61 | return string(object); 62 | } 63 | if (object instanceof java.util.Date) { 64 | return date(object); 65 | } 66 | if (object instanceof java.sql.Date) { 67 | return date(new Date(((java.sql.Date) object).getTime())); 68 | } 69 | if (object instanceof java.sql.Time) { 70 | return date(new Date(((java.sql.Time) (object)).getTime())); 71 | } 72 | if (object instanceof java.util.Date) { 73 | return date(new Date(((java.util.Date) (object)).getTime())); 74 | } 75 | if (object instanceof Map) { 76 | return map((Map) object); 77 | } 78 | if (object.getClass().isArray()) { 79 | return array(object); 80 | } 81 | if (object instanceof Iterable) { 82 | return array(((Iterable) object).iterator()); 83 | } 84 | if (object instanceof BaseModel) { 85 | return bean(object); 86 | } 87 | System.err.println(object.getClass().getName()+" Is Not BaseModel"); 88 | return ""; 89 | } 90 | 91 | private static String bean(Object object) { 92 | try { 93 | StringBuilder buf = new StringBuilder(); 94 | List list = PropertUtil.getBeanFields(object); 95 | if (StringUtil.isNullOrEmpty(list)) { 96 | return ""; 97 | } 98 | buf.append(add("{")); 99 | BeanEntity entity = null; 100 | String tmp = null; 101 | if (!StringUtil.isNullOrEmpty(list)) { 102 | for (int i = 0; i < list.size(); i++) { 103 | try { 104 | entity = list.get(i); 105 | if (StringUtil.isNullOrEmpty(entity) 106 | || StringUtil.isNullOrEmpty(entity.getFieldName())|| StringUtil.isNullOrEmpty(entity.getFieldValue())) { 107 | continue; 108 | } 109 | tmp = add(entity.getFieldName(), entity.getFieldValue()); 110 | if (StringUtil.isNullOrEmpty(tmp)) { 111 | continue; 112 | } 113 | buf.append(tmp); 114 | if (i >= list.size() - 1) { 115 | continue; 116 | } 117 | buf.append(add(',')); 118 | } catch (Exception e) { 119 | // TODO: handle exception 120 | } 121 | } 122 | buf = removeLastStr(buf, ','); 123 | } 124 | buf.append(add("}")); 125 | return buf.toString(); 126 | } catch (Exception e) { 127 | return ""; 128 | } 129 | 130 | } 131 | 132 | private static StringBuilder removeLastStr(StringBuilder buf, char value) { 133 | try { 134 | if (buf.charAt(buf.length() - 1) == value) { 135 | buf.deleteCharAt(buf.length() - 1); 136 | } 137 | 138 | } catch (Exception e) { 139 | } 140 | return buf; 141 | } 142 | 143 | private static String add(String name, Object value) { 144 | 145 | try { 146 | StringBuilder buf = new StringBuilder(); 147 | String context = value(value); 148 | String field = add(name); 149 | if (StringUtil.isNullOrEmpty(field)) { 150 | return ""; 151 | } 152 | if (StringUtil.isNullOrEmpty(context)) { 153 | context = "\"\""; 154 | } 155 | buf.append(add('"')); 156 | buf.append(field); 157 | buf.append(add("\":")); 158 | buf.append(context); 159 | return buf.toString(); 160 | } catch (Exception e) { 161 | } 162 | return ""; 163 | } 164 | 165 | private static String map(Map map) { 166 | try { 167 | StringBuilder buf = new StringBuilder(); 168 | buf.append(add("{")); 169 | Iterator it = map.keySet().iterator(); 170 | Object key = null; 171 | String keyC = null, value = null; 172 | while (it.hasNext()) { 173 | try { 174 | key = it.next(); 175 | if (map.get(key) == null) { 176 | continue; 177 | } 178 | keyC = value(key); 179 | value = value(map.get(key)); 180 | if (StringUtil.findNull(keyC, value) > -1) { 181 | continue; 182 | } 183 | buf.append(keyC); 184 | buf.append(add(":")); 185 | buf.append(value); 186 | if (it.hasNext()) { 187 | buf.append(add(",")); 188 | } 189 | } catch (Exception e) { 190 | } 191 | } 192 | buf.append(add("}")); 193 | return buf.toString(); 194 | } catch (Exception e) { 195 | } 196 | return ""; 197 | } 198 | 199 | private static String array(Iterator it) { 200 | StringBuilder buf = new StringBuilder(); 201 | try { 202 | buf.append(add("[")); 203 | String value = null; 204 | while (it.hasNext()) { 205 | try { 206 | value = value(it.next()); 207 | if (StringUtil.isNullOrEmpty(value)) { 208 | continue; 209 | } 210 | buf.append(value); 211 | if (it.hasNext()) { 212 | buf.append(add(",")); 213 | } 214 | } catch (Exception e) { 215 | } 216 | 217 | } 218 | buf.append(add("]")); 219 | return buf.toString(); 220 | } catch (Exception e) { 221 | // TODO: handle exception 222 | } 223 | return ""; 224 | } 225 | 226 | private static String array(Object object) { 227 | StringBuilder buf = new StringBuilder(); 228 | try { 229 | String value = null; 230 | buf.append(add("[")); 231 | int length = Array.getLength(object); 232 | for (int i = 0; i < length; ++i) { 233 | try { 234 | value = value(Array.get(object, i)); 235 | if (StringUtil.isNullOrEmpty(value)) { 236 | continue; 237 | } 238 | buf.append(value); 239 | if (i < length - 1) { 240 | add(','); 241 | } 242 | } catch (Exception e) { 243 | } 244 | } 245 | buf.append(add("]")); 246 | return buf.toString(); 247 | } catch (Exception e) { 248 | } 249 | return ""; 250 | } 251 | 252 | private static String bool(boolean b) { 253 | return add(b ? "true" : "false"); 254 | } 255 | 256 | private static String date(Object obj) { 257 | StringBuilder buf = new StringBuilder(); 258 | try { 259 | String value = add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 260 | .format((Date) obj)); 261 | if (StringUtil.isNullOrEmpty(value)) { 262 | return ""; 263 | } 264 | buf.append(add('"')); 265 | buf.append(value); 266 | buf.append(add('"')); 267 | return buf.toString(); 268 | } catch (Exception e) { 269 | } 270 | return ""; 271 | } 272 | 273 | @SuppressWarnings("unused") 274 | private static String sqldate(Object obj) { 275 | StringBuilder buf = new StringBuilder(); 276 | try { 277 | String value = add(new SimpleDateFormat("yyyy-MM-dd") 278 | .format((Date) obj)); 279 | if (StringUtil.isNullOrEmpty(value)) { 280 | return ""; 281 | } 282 | buf.append(add('"')); 283 | buf.append(value); 284 | buf.append(add('"')); 285 | return buf.toString(); 286 | } catch (Exception e) { 287 | } 288 | return ""; 289 | } 290 | 291 | @SuppressWarnings("unused") 292 | private static String sqltime(Object obj) { 293 | StringBuilder buf = new StringBuilder(); 294 | try { 295 | String value = add(new SimpleDateFormat("HH:mm:ss.SSS") 296 | .format((Date) obj)); 297 | if (StringUtil.isNullOrEmpty(value)) { 298 | return ""; 299 | } 300 | buf.append(add('"')); 301 | buf.append(value); 302 | buf.append(add('"')); 303 | return buf.toString(); 304 | } catch (Exception e) { 305 | } 306 | return ""; 307 | } 308 | 309 | private static String string(Object obj) { 310 | try { 311 | StringBuilder buf = new StringBuilder(); 312 | buf.append(add('"')); 313 | CharacterIterator it = new StringCharacterIterator(obj.toString()); 314 | 315 | for (char c = it.first(); c != CharacterIterator.DONE; c = it 316 | .next()) { 317 | try { 318 | if (c == '"') { 319 | buf.append(add("\\\"")); 320 | } else if (c == '\\') { 321 | buf.append(add("\\\\")); 322 | } else if (c == '\b') { 323 | buf.append(add("\\b")); 324 | } else if (c == '\f') { 325 | buf.append(add("\\f")); 326 | } else if (c == '\n') { 327 | buf.append(add("\\n")); 328 | } else if (c == '\r') { 329 | buf.append(add("\\r")); 330 | } else if (c == '\t') { 331 | buf.append(add("\\t")); 332 | } else if (Character.isISOControl(c)) { 333 | buf.append(unicode(c)); 334 | } else { 335 | buf.append(add(c)); 336 | } 337 | } catch (Exception e) { 338 | } 339 | } 340 | buf.append(add('"')); 341 | return buf.toString(); 342 | } catch (Exception e) { 343 | } 344 | return ""; 345 | } 346 | 347 | private static String add(Object obj) { 348 | return obj.toString(); 349 | } 350 | 351 | private static String add(char c) { 352 | return String.valueOf(c); 353 | } 354 | 355 | private static String unicode(char c) { 356 | try { 357 | StringBuilder buf = new StringBuilder(); 358 | buf.append(add("\\u")); 359 | int n = c; 360 | for (int i = 0; i < 4; ++i) { 361 | try { 362 | int digit = (n & 0xf000) >> 12; 363 | 364 | buf.append(add(hex[digit])); 365 | n <<= 4; 366 | } catch (Exception e) { 367 | } 368 | 369 | } 370 | return buf.toString(); 371 | } catch (Exception e) { 372 | } 373 | return ""; 374 | } 375 | 376 | /** 377 | * 格式化 378 | * @param jsonStr 379 | * @return 380 | * @author lizhgb 381 | * @Date 2015-10-14 下午1:17:35 382 | */ 383 | public static String formatJson(String jsonStr) { 384 | if (null == jsonStr || "".equals(jsonStr)) return ""; 385 | StringBuilder sb = new StringBuilder(); 386 | char last = '\0'; 387 | char current = '\0'; 388 | int indent = 0; 389 | for (int i = 0; i < jsonStr.length(); i++) { 390 | last = current; 391 | current = jsonStr.charAt(i); 392 | switch (current) { 393 | case '{': 394 | case '[': 395 | sb.append(current); 396 | sb.append('\n'); 397 | indent++; 398 | addIndentBlank(sb, indent); 399 | break; 400 | case '}': 401 | case ']': 402 | sb.append('\n'); 403 | indent--; 404 | addIndentBlank(sb, indent); 405 | sb.append(current); 406 | break; 407 | case ',': 408 | sb.append(current); 409 | if (last != '\\') { 410 | sb.append('\n'); 411 | addIndentBlank(sb, indent); 412 | } 413 | break; 414 | default: 415 | sb.append(current); 416 | } 417 | } 418 | 419 | return sb.toString(); 420 | } 421 | 422 | /** 423 | * 添加space 424 | * @param sb 425 | * @param indent 426 | * @author lizhgb 427 | * @Date 2015-10-14 上午10:38:04 428 | */ 429 | private static void addIndentBlank(StringBuilder sb, int indent) { 430 | for (int i = 0; i < indent; i++) { 431 | sb.append('\t'); 432 | } 433 | } 434 | 435 | } 436 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/JUUIDUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.util.UUID; 4 | 5 | public class JUUIDUtil { 6 | 7 | public synchronized static String createUuid() { 8 | String str = UUID.randomUUID().toString().replace("-", ""); 9 | return str; 10 | } 11 | 12 | public static void main(String[] args) { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/MatchUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | public class MatchUtil { 11 | 12 | 13 | public static Boolean isMatcher(String val, String matcher) { 14 | Pattern p = Pattern.compile(matcher); 15 | Matcher m = p.matcher(val); 16 | return m.matches(); 17 | } 18 | 19 | 20 | 21 | public static Boolean isParaMatch(String val,String mateher){ 22 | try { 23 | if(StringUtil.isNullOrEmpty(val)){ 24 | return false; 25 | } 26 | List paraNames=getParams(mateher); 27 | mateher=parseMatchContext(mateher, paraNames); 28 | return isMatcher(val, mateher); 29 | } catch (Exception e) { 30 | 31 | return false; 32 | } 33 | } 34 | 35 | public static String parseMatchContext(String matchContext,List paraNames){ 36 | String exportPat="(.*)"; 37 | for(String para:paraNames){ 38 | matchContext=matchContext.replace("${"+para+"}", exportPat); 39 | } 40 | return matchContext; 41 | } 42 | 43 | public static List matchResults(String context,String matchContext){ 44 | String exportPat="(.*)"; 45 | String [] pattenTrunk=matchContext.split("\\(\\.\\*\\)"); 46 | List results=new ArrayList(); 47 | for(int i=0;i matchParamMap(String context,String matchContext){ 59 | List paraNames=getParams(matchContext); 60 | matchContext=parseMatchContext(matchContext, paraNames); 61 | List results=matchResults(context, matchContext); 62 | HashMap map=new HashMap(); 63 | for(int i=0;i getParams(String context){ 77 | String patten="\\$\\{([A-Za-z0-9_]+)\\}"; 78 | return matchExport(context, patten); 79 | } 80 | 81 | 82 | public static String matchExportFirst(String context,String patten){ 83 | List results=matchExport(context, patten); 84 | if(StringUtil.isNullOrEmpty(results)){ 85 | return null; 86 | } 87 | return results.get(0); 88 | } 89 | public static List matchExport(String context,String patten){ 90 | try { 91 | Integer index = 0; 92 | Pattern pattern = Pattern.compile(patten, Pattern.DOTALL); 93 | Matcher matcher = pattern.matcher(context); 94 | List results=new ArrayList(); 95 | while (matcher.find(index)) { 96 | String tmp = matcher.group(1); 97 | index = matcher.end(); 98 | if (StringUtil.isNullOrEmpty(tmp)) { 99 | continue; 100 | } 101 | results.add(tmp); 102 | } 103 | return results; 104 | } catch (Exception e) { 105 | return null; 106 | } 107 | } 108 | 109 | static String a="abcdefghijklmnopqrsvaaaaaaaaaaa\r\n\rdjskfhj\t...?df[pigodfpgk()"; 110 | 111 | static String b="${para0}bc${para1}efg${para2}ijkl${para3}nop${para4}rs${para1}"; 112 | 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/PrintException.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.PrintStream; 5 | 6 | import org.apache.log4j.Logger; 7 | 8 | public class PrintException { 9 | 10 | /** 11 | * 获取Exception的堆栈新息。用于显示出错来源时使用。 12 | * 13 | * @param e Exception对象 14 | * @param length 需要的信息长度,如果 <=0,表示全部信息 15 | * @return String 返回该Exception的堆栈新息 16 | * @author AIXIANG 17 | */ 18 | public static String getErrorStack(Throwable e ) { 19 | String error = null; 20 | if (e != null) { 21 | try { 22 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 23 | PrintStream ps = new PrintStream(baos); 24 | e.printStackTrace(ps); 25 | error = baos.toString(); 26 | baos.close(); 27 | ps.close(); 28 | } catch (Exception e1) { 29 | error = e.toString(); 30 | } 31 | } 32 | return error; 33 | } 34 | 35 | public static void printException(Logger logger,Throwable e){ 36 | String error=getErrorStack(e); 37 | logger.info(error); 38 | logger.error(error); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/PropertUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.Method; 6 | import java.lang.reflect.Modifier; 7 | import java.lang.reflect.Parameter; 8 | import java.security.InvalidParameterException; 9 | import java.text.ParseException; 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.Collections; 13 | import java.util.Date; 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | import java.util.TreeMap; 18 | import java.util.concurrent.ConcurrentHashMap; 19 | 20 | import org.coody.framework.entity.BeanEntity; 21 | import org.coody.framework.entity.Record; 22 | 23 | @SuppressWarnings("unchecked") 24 | public class PropertUtil { 25 | 26 | private static Map, List> fieldMap = new ConcurrentHashMap, List>(); 27 | private static Map, List> methodMap = new ConcurrentHashMap, List>(); 28 | private static Map> paramMap = new ConcurrentHashMap>(); 29 | 30 | public static void reload() { 31 | fieldMap.clear(); 32 | methodMap.clear(); 33 | } 34 | 35 | /** 36 | * 获取对象多个字段的值 37 | * 38 | * @param obj 39 | * @param fieldNames 40 | * @return 41 | */ 42 | public static List getFieldValues(Object obj, String... fieldNames) { 43 | if (StringUtil.isNullOrEmpty(obj)) { 44 | return null; 45 | } 46 | List values = new ArrayList(fieldNames.length * 2); 47 | for (String fieldName : fieldNames) { 48 | values.add(getFieldValue(obj, fieldName)); 49 | } 50 | if (StringUtil.isNullOrEmpty(values)) { 51 | return null; 52 | } 53 | return values; 54 | } 55 | 56 | /** 57 | * 从对象中获取目标方法 58 | * 59 | * @param methods 60 | * 方法数组 61 | * @param methodName 62 | * 方法名称 63 | * @param paras 64 | * 参数列表 65 | * @return 66 | */ 67 | public static Method getTargeMethod(Method[] methods, String methodName, Object... paras) { 68 | for (Method m : methods) { 69 | if (isTargeMethod(m, methodName, paras)) { 70 | return m; 71 | } 72 | } 73 | return null; 74 | } 75 | 76 | /** 77 | * 判断目标是否是当前方法 78 | * 79 | * @param method 80 | * 当前方法 81 | * @param methodName 82 | * 目标方法名 83 | * @param paras 84 | * 目标方法参数列表 85 | * @return 86 | */ 87 | private static boolean isTargeMethod(Method method, String methodName, Object... paras) { 88 | if (!method.getName().equals(methodName)) { 89 | return false; 90 | } 91 | Class[] clas = method.getParameterTypes(); 92 | if (StringUtil.isNullOrEmpty(clas) && StringUtil.isNullOrEmpty(paras)) { 93 | return true; 94 | } 95 | if (StringUtil.isNullOrEmpty(clas) || StringUtil.isNullOrEmpty(paras)) { 96 | return false; 97 | } 98 | if (clas.length != paras.length) { 99 | return false; 100 | } 101 | for (int i = 0; i < clas.length; i++) { 102 | if (paras[i] == null) { 103 | continue; 104 | } 105 | if (!clas[i].isAssignableFrom(paras[i].getClass())) { 106 | return false; 107 | } 108 | } 109 | return true; 110 | } 111 | 112 | public static T copyPropertys(Object source, Object targe) { 113 | if (StringUtil.isNullOrEmpty(source)) { 114 | return (T) targe; 115 | } 116 | List entitys = getBeanFields(source); 117 | if (StringUtil.isNullOrEmpty(entitys)) { 118 | return (T) targe; 119 | } 120 | for (BeanEntity entity : entitys) { 121 | try { 122 | setFieldValue(targe, entity.getFieldName(), entity.getFieldValue()); 123 | } catch (Exception e) { 124 | } 125 | } 126 | return (T) targe; 127 | } 128 | 129 | /** 130 | * 对象相同字段组成新list 131 | * 132 | * @param list 133 | * @param cla 134 | * @return 135 | */ 136 | @SuppressWarnings({ "rawtypes" }) 137 | public static List getNewList(List list, Class cla) { 138 | if (StringUtil.findNull(list, cla) > -1) { 139 | return null; 140 | } 141 | List ls = new ArrayList(); 142 | for (Object obj : list) { 143 | try { 144 | Object newObj = cla.newInstance(); 145 | newObj = copyPropertys(obj, newObj); 146 | ls.add((T) newObj); 147 | } catch (Exception e) { 148 | } 149 | } 150 | return ls; 151 | } 152 | 153 | /** 154 | * Map转对象 155 | */ 156 | @SuppressWarnings({ "rawtypes" }) 157 | public static T mapToModel(Map map, Class clazz) { 158 | if (StringUtil.isNullOrEmpty(map)) { 159 | return null; 160 | } 161 | try { 162 | T value = (T) clazz.newInstance(); 163 | List entitys = getBeanFields(clazz); 164 | if (StringUtil.isNullOrEmpty(entitys)) { 165 | return null; 166 | } 167 | for (BeanEntity entity : entitys) { 168 | try { 169 | entity.getSourceField().setAccessible(true); 170 | entity.getSourceField().set(value, 171 | parseValue(map.get(entity.getFieldName()), entity.getFieldType())); 172 | } catch (Exception e) { 173 | } 174 | } 175 | return value; 176 | } catch (Exception e) { 177 | } 178 | return null; 179 | } 180 | 181 | /** 182 | * 获取某个对象的class 183 | * 184 | * @param obj 185 | * @return 186 | */ 187 | public static Class getObjClass(Object obj) { 188 | if (StringUtil.isNullOrEmpty(obj)) { 189 | return null; 190 | } 191 | if (obj instanceof Class) { 192 | return (Class) obj; 193 | } 194 | return obj.getClass(); 195 | } 196 | 197 | /** 198 | * 获取class的字段对象 199 | * 200 | * @param clazz 201 | * @param fieldName 202 | * @return 203 | */ 204 | public static Field getField(Class clazz, String fieldName) { 205 | List fields = loadFields(clazz); 206 | if (StringUtil.isNullOrEmpty(fields)) { 207 | return null; 208 | } 209 | for (Field f : fields) { 210 | if (f.getName().equals(fieldName)) { 211 | return f; 212 | } 213 | } 214 | return null; 215 | } 216 | 217 | /** 218 | * 一个神奇的方法:获取对象字段集合 219 | * 220 | * @param obj 221 | * @return 222 | */ 223 | public static List getBeanFields(Object obj) { 224 | if (StringUtil.isNullOrEmpty(obj)) { 225 | return null; 226 | } 227 | Class cla = getObjClass(obj); 228 | List infos = getClassFields(cla); 229 | if (StringUtil.isNullOrEmpty(infos)) { 230 | return infos; 231 | } 232 | if (obj instanceof java.lang.Class) { 233 | return infos; 234 | } 235 | for (BeanEntity info : infos) { 236 | try { 237 | Field f = info.getSourceField(); 238 | f.setAccessible(true); 239 | Object value = f.get(obj); 240 | info.setFieldValue(value); 241 | } catch (Exception e) { 242 | 243 | } 244 | } 245 | return infos; 246 | } 247 | 248 | /** 249 | * 一个神奇的方法:获取class字段集合 250 | * 251 | * @param cla 252 | * @return 253 | */ 254 | public static List getClassFields(Class cla) { 255 | try { 256 | List fields = loadFields(cla); 257 | List infos = new ArrayList(); 258 | for (Field f : fields) { 259 | if (f.getName().equalsIgnoreCase("serialVersionUID")) { 260 | continue; 261 | } 262 | BeanEntity tmp = new BeanEntity(); 263 | tmp.setSourceField(f); 264 | tmp.setFieldAnnotations(f.getAnnotations()); 265 | tmp.setFieldName(f.getName()); 266 | tmp.setFieldType(f.getType()); 267 | infos.add(tmp); 268 | } 269 | return infos; 270 | } catch (Exception e) { 271 | 272 | return null; 273 | } 274 | } 275 | 276 | /** 277 | * 一个神奇的方法:从一个List提取字段名统一的分组 278 | * 279 | * @param objs 280 | * @param fieldName 281 | * @param fieldValue 282 | * @return 283 | */ 284 | @SuppressWarnings({ "rawtypes" }) 285 | public static List getGroup(List objs, String fieldName, Object fieldValue) { 286 | if (StringUtil.isNullOrEmpty(objs)) { 287 | return null; 288 | } 289 | Map map = PropertUtil.listToMaps(objs, fieldName); 290 | if (StringUtil.isNullOrEmpty(map)) { 291 | return null; 292 | } 293 | return map.get(fieldValue); 294 | } 295 | 296 | /** 297 | * 从一个集合获取某指定字段值第一个对象 298 | * 299 | * @param objs 300 | * @param fieldName 301 | * @param fieldValue 302 | * @return 303 | */ 304 | @SuppressWarnings({ "rawtypes" }) 305 | public static T getByList(List objs, String fieldName, Object fieldValue) { 306 | if (StringUtil.findNull(objs, fieldName, fieldValue) > -1) { 307 | return null; 308 | } 309 | Map map = PropertUtil.listToMap(objs, fieldName); 310 | if (StringUtil.isNullOrEmpty(map)) { 311 | return null; 312 | } 313 | return (T) map.get(fieldValue); 314 | } 315 | 316 | /** 317 | * 获取对象某个字段值 318 | * 319 | * @param obj 320 | * @param fieldName 321 | * @return 322 | */ 323 | private static Object getFieldValueCurr(Object obj, String fieldName) { 324 | if (StringUtil.isNullOrEmpty(obj)) { 325 | return null; 326 | } 327 | Field f = getField(obj.getClass(), fieldName); 328 | if (StringUtil.isNullOrEmpty(f)) { 329 | return null; 330 | } 331 | f.setAccessible(true); 332 | try { 333 | return f.get(obj); 334 | } catch (Exception e) { 335 | 336 | return null; 337 | } 338 | } 339 | 340 | /** 341 | * 获取字段值,支持点属性 342 | * 343 | * @param bean 344 | * @param paraName 345 | * @return 346 | */ 347 | public static Object getFieldValue(Object bean, String paraName) { 348 | if (StringUtil.isNullOrEmpty(bean)) { 349 | return null; 350 | } 351 | List beanEntitys = PropertUtil.getBeanFields(bean); 352 | if (StringUtil.isNullOrEmpty(beanEntitys)) { 353 | return null; 354 | } 355 | if (!paraName.contains(".")) { 356 | return PropertUtil.getFieldValueCurr(bean, paraName); 357 | } 358 | List fields = new ArrayList(Arrays.asList(paraName.split("\\."))); 359 | Object beanTmp = PropertUtil.getFieldValue(bean, fields.get(0)); 360 | fields.remove(0); 361 | return getFieldValue(beanTmp, StringUtil.collectionMosaic(fields, ".")); 362 | } 363 | 364 | /** 365 | * 获取方法的类 366 | * 367 | * @param method 368 | * @return 369 | */ 370 | public static Class getClass(Method method) { 371 | Class cla = (Class) PropertUtil.getFieldValue(method, "clazz"); 372 | return cla; 373 | } 374 | 375 | /** 376 | * 获取List对象某个字段的值组成新List 377 | * 378 | * @param objs 379 | * @param fieldName 380 | * @return 381 | */ 382 | public static List getFieldValues(List objs, String fieldName) { 383 | if (StringUtil.isNullOrEmpty(objs)) { 384 | return null; 385 | } 386 | List list = new ArrayList(); 387 | Object value; 388 | for (Object obj : objs) { 389 | value = getFieldValue(obj, fieldName); 390 | list.add(value); 391 | } 392 | if (StringUtil.isNullOrEmpty(objs)) { 393 | return null; 394 | } 395 | return (List) list; 396 | } 397 | 398 | /** 399 | * 获取对象字段列表 400 | * 401 | * @param cla 402 | * @return 403 | */ 404 | public static List getFieldNames(Class cla) { 405 | Field[] fields = cla.getDeclaredFields(); 406 | List fieldNames = new ArrayList(); 407 | for (Field field : fields) { 408 | fieldNames.add(field.getName()); 409 | } 410 | return fieldNames; 411 | } 412 | 413 | /** 414 | * 设置字段值 415 | * 416 | * @param obj 417 | * 实例对象 418 | * @param propertyName 419 | * 属性名 420 | * @param value 421 | * 新的字段值 422 | * @return 423 | * @throws IllegalAccessException 424 | * @throws IllegalArgumentException 425 | */ 426 | public static void setFieldValue(Object object, String propertyName, Object value) 427 | throws IllegalArgumentException, IllegalAccessException { 428 | Field field = getField(object.getClass(), propertyName); 429 | if (StringUtil.isNullOrEmpty(field)) { 430 | 431 | return; 432 | } 433 | setFieldValue(object, field, value); 434 | } 435 | 436 | /** 437 | * 设置字段值 438 | * 439 | * @param obj 440 | * 实例对象 441 | * @param propertyName 442 | * 属性名 443 | * @param value 444 | * 新的字段值 445 | * @return 446 | * @throws IllegalAccessException 447 | * @throws IllegalArgumentException 448 | */ 449 | public static void setFieldValue(Object object, Field field, Object value) 450 | throws IllegalArgumentException, IllegalAccessException { 451 | field.setAccessible(true); 452 | if (field.getType().isEnum()) { 453 | setFieldValue(field, "name", value); 454 | Object enmValue = field.get(object); 455 | setFieldValue(enmValue, "name", value); 456 | return; 457 | } 458 | if (Modifier.isFinal(field.getModifiers())) { 459 | int modifiers = field.getModifiers(); 460 | try { 461 | Field modifiersField = Field.class.getDeclaredField("modifiers"); 462 | try { 463 | modifiersField.setAccessible(true); 464 | modifiersField.set(field, field.getModifiers() & ~Modifier.FINAL); 465 | Object obj = parseValue(value, field.getType()); 466 | field.set(object, obj); 467 | } catch (IllegalAccessException e) { 468 | 469 | if (!StringUtil.isNullOrEmpty(PropertUtil.getFieldValue(field, "fieldAccessor"))) { 470 | setProperties(field, "fieldAccessor.isReadOnly", false); 471 | setProperties(field, "fieldAccessor.isFinal", false); 472 | setProperties(field, "fieldAccessor.field", field); 473 | } 474 | if (!StringUtil.isNullOrEmpty(PropertUtil.getFieldValue(field, "overrideFieldAccessor"))) { 475 | setProperties(field, "overrideFieldAccessor.isReadOnly", false); 476 | setProperties(field, "overrideFieldAccessor.isFinal", false); 477 | setProperties(field, "overrideFieldAccessor.field", field); 478 | } 479 | 480 | setFieldValue(field, "root", field); 481 | setFieldValue(object, field, value); 482 | } catch (Exception e) { 483 | 484 | } finally { 485 | if (modifiers != field.getModifiers()) { 486 | modifiersField.set(field, modifiers); 487 | } 488 | } 489 | } catch (Exception e) { 490 | // TODO: handle exception 491 | } 492 | return; 493 | } 494 | Object obj = parseValue(value, field.getType()); 495 | field.set(object, obj); 496 | } 497 | 498 | /** 499 | * 设置字段值 500 | * 501 | * @param obj 502 | * 实例对象 503 | * @param propertyName 504 | * 属性名 505 | * @param value 506 | * 新的字段值 507 | * @return 508 | * @throws IllegalAccessException 509 | * @throws IllegalArgumentException 510 | * @throws InstantiationException 511 | */ 512 | public static void setProperties(Object object, String propertyName, Object value) 513 | throws IllegalArgumentException, IllegalAccessException, InstantiationException { 514 | if (StringUtil.isNullOrEmpty(object)) { 515 | return; 516 | } 517 | List beanEntitys = PropertUtil.getBeanFields(object); 518 | if (StringUtil.isNullOrEmpty(beanEntitys)) { 519 | return; 520 | } 521 | if (!propertyName.contains(".")) { 522 | setFieldValue(object, propertyName, value); 523 | return; 524 | } 525 | List fields = new ArrayList(Arrays.asList(propertyName.split("\\."))); 526 | String fieldName = fields.get(0); 527 | BeanEntity currField = PropertUtil.getByList(beanEntitys, "fieldName", fieldName); 528 | if (currField == null || (currField.getFieldValue() == null && value == null)) { 529 | return; 530 | } 531 | Object beanTmp = currField.getFieldValue(); 532 | if (beanTmp == null) { 533 | beanTmp = currField.getFieldType().newInstance(); 534 | } 535 | fields.remove(0); 536 | setProperties(beanTmp, StringUtil.collectionMosaic(fields, "."), value); 537 | setProperties(object, fieldName, beanTmp); 538 | } 539 | 540 | /** 541 | * 设置集合对象某字段值 542 | * 543 | * @param objs 544 | * @param fieldName 545 | * @param fieldsValue 546 | * @return 547 | */ 548 | public static List setFieldValues(List objs, String fieldName, Object fieldsValue) { 549 | if (StringUtil.isNullOrEmpty(objs)) { 550 | return null; 551 | } 552 | try { 553 | for (Object obj : objs) { 554 | try { 555 | if (StringUtil.isNullOrEmpty(obj)) { 556 | continue; 557 | } 558 | setProperties(obj, fieldName, fieldsValue); 559 | } catch (Exception e) { 560 | 561 | } 562 | } 563 | } catch (Exception e) { 564 | 565 | } 566 | return objs; 567 | } 568 | 569 | /** 570 | * 一个神奇的方法:一个List根据某个字段排序 571 | * 572 | * @param objs 573 | * @param fieldName 574 | * @return 575 | */ 576 | @SuppressWarnings({ "rawtypes" }) 577 | public static List doSeq(List objs, String fieldName) { 578 | if (StringUtil.isNullOrEmpty(objs)) { 579 | return null; 580 | } 581 | Map maps = listToMaps(objs, fieldName); 582 | if (StringUtil.isNullOrEmpty(maps)) { 583 | return null; 584 | } 585 | List list = new ArrayList(); 586 | for (Object key : maps.keySet()) { 587 | try { 588 | list.addAll(maps.get(key)); 589 | } catch (Exception e) { 590 | 591 | } 592 | } 593 | return list; 594 | } 595 | 596 | /** 597 | * 一个神奇的方法:一个List根据某个字段排序 598 | * 599 | * @param objs 600 | * @param fieldName 601 | * @param isDesc 602 | * @return 603 | */ 604 | public static List doSeqDesc(List objs, String fieldName) { 605 | List list = doSeq(objs, fieldName); 606 | if (StringUtil.isNullOrEmpty(list)) { 607 | return null; 608 | } 609 | Collections.reverse(list); 610 | return list; 611 | } 612 | 613 | /** 614 | * 一个List转为Map,fieldName作为Key,所有字段值相同的组成List作为value 615 | * 616 | * @param objs 617 | * @param fieldName 618 | * @return 619 | */ 620 | @SuppressWarnings({ "rawtypes" }) 621 | public static Map listToMaps(List objs, String fieldName) { 622 | if (StringUtil.isNullOrEmpty(objs)) { 623 | return null; 624 | } 625 | Map map = new TreeMap(); 626 | List list; 627 | for (Object obj : objs) { 628 | try { 629 | Object fieldValue = getFieldValue(obj, fieldName); 630 | if (map.containsKey(fieldValue)) { 631 | map.get(fieldValue).add(obj); 632 | continue; 633 | } 634 | list = new ArrayList(); 635 | list.add(obj); 636 | map.put(fieldValue, list); 637 | } catch (Exception e) { 638 | 639 | } 640 | } 641 | if (StringUtil.isNullOrEmpty(map)) { 642 | return null; 643 | } 644 | return map; 645 | } 646 | 647 | /** 648 | * List转为Map。fieldName作为Key,对象作为Value 649 | * 650 | * @param objs 651 | * @param fieldName 652 | * @return 653 | */ 654 | public static Map beanToMap(Object obj) { 655 | if (StringUtil.isNullOrEmpty(obj)) { 656 | return null; 657 | } 658 | Map map = new HashMap(); 659 | List entitys = PropertUtil.getBeanFields(obj); 660 | for (BeanEntity entity : entitys) { 661 | if (StringUtil.isNullOrEmpty(entity.getFieldValue())) { 662 | continue; 663 | } 664 | map.put(entity.getFieldName(), entity.getFieldValue()); 665 | } 666 | if (StringUtil.isNullOrEmpty(map)) { 667 | return null; 668 | } 669 | return map; 670 | } 671 | 672 | /** 673 | * List转为Map。fieldName作为Key,对象作为Value 674 | * 675 | * @param objs 676 | * @param fieldName 677 | * @return 678 | */ 679 | public static Map listToMap(List objs, String fieldName) { 680 | if (StringUtil.isNullOrEmpty(objs)) { 681 | return null; 682 | } 683 | Map map = new TreeMap(); 684 | for (Object obj : objs) { 685 | try { 686 | Object fieldValue = getFieldValue(obj, fieldName); 687 | map.put(fieldValue, obj); 688 | } catch (Exception e) { 689 | 690 | } 691 | } 692 | if (StringUtil.isNullOrEmpty(map)) { 693 | return null; 694 | } 695 | return map; 696 | } 697 | 698 | public static List loadMethods(Class clazz) { 699 | List methods = methodMap.get(clazz); 700 | if (!StringUtil.isNullOrEmpty(methods)) { 701 | return methods; 702 | } 703 | methods = new ArrayList(Arrays.asList(clazz.getDeclaredMethods())); 704 | if (!StringUtil.isNullOrEmpty(clazz.getSuperclass())) { 705 | methods.addAll(loadMethods(clazz.getSuperclass())); 706 | } 707 | methodMap.put(clazz, methods); 708 | return methods; 709 | } 710 | 711 | /** 712 | * 加载枚举的信息 713 | * 714 | * @param clazz 715 | * @return 716 | */ 717 | public static T loadEnumByField(Class clazz, String fieldName, Object value) { 718 | if (!clazz.isEnum()) { 719 | throw new InvalidParameterException(); 720 | } 721 | try { 722 | T[] enumConstants = clazz.getEnumConstants(); 723 | for (T ec : enumConstants) { 724 | Object currValue = getFieldValue(ec, fieldName); 725 | if (value == currValue || currValue.equals(value)) { 726 | return ec; 727 | } 728 | } 729 | return null; 730 | } catch (Exception e) { 731 | 732 | } 733 | return null; 734 | } 735 | 736 | /** 737 | * 加载枚举的信息 738 | * 739 | * @param clazz 740 | * @return 741 | */ 742 | public static Map loadEnumRecord(Class clazz) { 743 | if (!clazz.isEnum()) { 744 | throw new InvalidParameterException(); 745 | } 746 | try { 747 | T[] enumConstants = clazz.getEnumConstants(); 748 | Field[] fields = clazz.getDeclaredFields(); 749 | if (StringUtil.isNullOrEmpty(fields)) { 750 | return null; 751 | } 752 | List fieldList = new ArrayList(); 753 | for (Field field : fields) { 754 | try { 755 | if (!(clazz.isAssignableFrom(field.getType())) 756 | && !(("[L" + clazz.getName() + ";").equals(field.getType().getName()))) { 757 | fieldList.add(field); 758 | } 759 | } catch (Exception e) { 760 | } 761 | } 762 | if (StringUtil.isNullOrEmpty(fieldList)) { 763 | return null; 764 | } 765 | Map records = new HashMap(); 766 | for (T ec : enumConstants) { 767 | Record record = new Record(); 768 | for (Field field : fieldList) { 769 | Object value = getFieldValue(ec, field.getName()); 770 | record.put(field.getName(), value); 771 | } 772 | records.put(ec.toString(), record); 773 | } 774 | return records; 775 | } catch (Exception e) { 776 | } 777 | return null; 778 | } 779 | 780 | public static void setEnumFieldName(Class clazz, String fieldName, String newFieldName) { 781 | if (!clazz.isEnum()) { 782 | throw new InvalidParameterException(); 783 | } 784 | if (StringUtil.hasNull(fieldName, newFieldName)) { 785 | return; 786 | } 787 | try { 788 | Object[] enumConstants = clazz.getEnumConstants(); 789 | Field[] fields = clazz.getDeclaredFields(); 790 | if (StringUtil.isNullOrEmpty(fields)) { 791 | return; 792 | } 793 | List fieldList = new ArrayList(); 794 | for (Field field : fields) { 795 | try { 796 | if (!(clazz.isAssignableFrom(field.getType())) 797 | && !(("[L" + clazz.getName() + ";").equals(field.getType().getName()))) { 798 | fieldList.add(field); 799 | } 800 | } catch (Exception e) { 801 | } 802 | } 803 | if (StringUtil.isNullOrEmpty(fieldList)) { 804 | return; 805 | } 806 | for (Object ec : enumConstants) { 807 | if (!ec.toString().equals(fieldName)) { 808 | continue; 809 | } 810 | setFieldValue(ec, "name", newFieldName); 811 | } 812 | return; 813 | } catch (Exception e) { 814 | 815 | } 816 | return; 817 | } 818 | 819 | public static void setEnumValue(Class clazz, String fieldName, Map valueMaps) { 820 | if (!clazz.isEnum()) { 821 | throw new InvalidParameterException(); 822 | } 823 | if (StringUtil.isNullOrEmpty(valueMaps)) { 824 | return; 825 | } 826 | try { 827 | Object[] enumConstants = clazz.getEnumConstants(); 828 | Field[] fields = clazz.getDeclaredFields(); 829 | if (StringUtil.isNullOrEmpty(fields)) { 830 | return; 831 | } 832 | List fieldList = new ArrayList(); 833 | for (Field field : fields) { 834 | try { 835 | if (!(clazz.isAssignableFrom(field.getType())) 836 | && !(("[L" + clazz.getName() + ";").equals(field.getType().getName()))) { 837 | fieldList.add(field); 838 | } 839 | } catch (Exception e) { 840 | } 841 | } 842 | if (StringUtil.isNullOrEmpty(fieldList)) { 843 | return; 844 | } 845 | for (Object ec : enumConstants) { 846 | if (!ec.toString().equals(fieldName)) { 847 | continue; 848 | } 849 | for (Field field : fieldList) { 850 | for (String key : valueMaps.keySet()) { 851 | if (!key.equals(field.getName())) { 852 | continue; 853 | } 854 | setFieldValue(ec, field, valueMaps.get(key)); 855 | } 856 | } 857 | } 858 | return; 859 | } catch (Exception e) { 860 | 861 | } 862 | return; 863 | } 864 | 865 | /** 866 | * 获取class的字段列表 867 | * 868 | * @param clazz 869 | * @return 870 | */ 871 | public static List loadFields(Class clazz) { 872 | List fields = fieldMap.get(clazz); 873 | if (!StringUtil.isNullOrEmpty(fields)) { 874 | return fields; 875 | } 876 | fields = new ArrayList(); 877 | Field[] fieldArgs = clazz.getDeclaredFields(); 878 | for (Field f : fieldArgs) { 879 | fields.add(f); 880 | } 881 | Class superClass = clazz.getSuperclass(); 882 | if (superClass != null) { 883 | fields.addAll(loadFields(superClass)); 884 | } 885 | fieldMap.put(clazz, fields); 886 | return fields; 887 | } 888 | 889 | /** 890 | * 将对象某些字段置空 891 | * 892 | * @param obj 893 | * @param fieldNames 894 | */ 895 | public static void removeFields(Object obj, String... fieldNames) { 896 | if (StringUtil.isNullOrEmpty(obj)) { 897 | return; 898 | } 899 | List fields = PropertUtil.getBeanFields(obj); 900 | Map map = (Map) listToMap(fields, "fieldName"); 901 | for (String tmp : fieldNames) { 902 | try { 903 | if (map.containsKey(tmp)) { 904 | BeanEntity entity = map.get(tmp); 905 | PropertUtil.setProperties(obj, entity.getFieldName(), null); 906 | } 907 | } catch (Exception e) { 908 | 909 | } 910 | 911 | } 912 | } 913 | 914 | /** 915 | * 清理其余字段,仅保留对象某些字段 916 | * 917 | * @param obj 918 | * @param fieldNames 919 | */ 920 | public static void accepFields(Object obj, String... fieldNames) { 921 | if (StringUtil.isNullOrEmpty(obj)) { 922 | return; 923 | } 924 | List fields = PropertUtil.getBeanFields(obj); 925 | Map map = (Map) listToMap(fields, "fieldName"); 926 | for (String tmp : fieldNames) { 927 | try { 928 | if (!map.containsKey(tmp)) { 929 | BeanEntity entity = map.get(tmp); 930 | PropertUtil.setProperties(obj, entity.getFieldName(), null); 931 | } 932 | } catch (Exception e) { 933 | 934 | } 935 | 936 | } 937 | } 938 | 939 | /** 940 | * value值转换为对应的类型 941 | * 942 | * @param value 943 | * @param clazz 944 | * @return 945 | * @throws ParseException 946 | */ 947 | public static Object parseValue(Object value, Class clazz) { 948 | try { 949 | if (value == null) { 950 | if (clazz.isPrimitive()) { 951 | if (boolean.class.isAssignableFrom(clazz)) { 952 | return false; 953 | } 954 | if (byte.class.isAssignableFrom(clazz)) { 955 | return 0; 956 | } 957 | if (char.class.isAssignableFrom(clazz)) { 958 | return 0; 959 | } 960 | if (short.class.isAssignableFrom(clazz)) { 961 | return 0; 962 | } 963 | if (int.class.isAssignableFrom(clazz)) { 964 | return 0; 965 | } 966 | if (float.class.isAssignableFrom(clazz)) { 967 | return 0f; 968 | } 969 | if (long.class.isAssignableFrom(clazz)) { 970 | return 0l; 971 | } 972 | if (double.class.isAssignableFrom(clazz)) { 973 | return 0d; 974 | } 975 | } 976 | return value; 977 | } 978 | if (Integer.class.isAssignableFrom(clazz) || int.class.isAssignableFrom(clazz)) { 979 | value = Integer.valueOf(value.toString()); 980 | return value; 981 | } 982 | if (Float.class.isAssignableFrom(clazz) || float.class.isAssignableFrom(clazz)) { 983 | value = Float.valueOf(value.toString()); 984 | return value; 985 | } 986 | if (Long.class.isAssignableFrom(clazz) || long.class.isAssignableFrom(clazz)) { 987 | value = Long.valueOf(value.toString()); 988 | return value; 989 | } 990 | if (Double.class.isAssignableFrom(clazz) || double.class.isAssignableFrom(clazz)) { 991 | value = Double.valueOf(value.toString()); 992 | return value; 993 | } 994 | if (Short.class.isAssignableFrom(clazz) || short.class.isAssignableFrom(clazz)) { 995 | value = Short.valueOf(value.toString()); 996 | return value; 997 | } 998 | if (Byte.class.isAssignableFrom(clazz) || byte.class.isAssignableFrom(clazz)) { 999 | value = Byte.valueOf(value.toString()); 1000 | return value; 1001 | } 1002 | if (Boolean.class.isAssignableFrom(clazz) || boolean.class.isAssignableFrom(clazz)) { 1003 | value = ("true".equals(value.toString()) || "1".equals(value.toString())) ? true : false; 1004 | return value; 1005 | } 1006 | if (String.class.isAssignableFrom(clazz)) { 1007 | value = value.toString(); 1008 | return value; 1009 | } 1010 | if (Date.class.isAssignableFrom(clazz)) { 1011 | value = DateUtils.toDate(value); 1012 | return value; 1013 | } 1014 | return value; 1015 | } catch (Exception e) { 1016 | 1017 | return null; 1018 | } 1019 | } 1020 | 1021 | /** 1022 | * 获取方法参数列表 1023 | * 1024 | * @param method 1025 | * @return 1026 | */ 1027 | public static List getMethodParas(Method method) { 1028 | try { 1029 | if (paramMap.containsKey(method)) { 1030 | return paramMap.get(method); 1031 | } 1032 | Class[] types = method.getParameterTypes(); 1033 | if (StringUtil.isNullOrEmpty(types)) { 1034 | return null; 1035 | } 1036 | List paraNames = getMethodParaNames(method); 1037 | if (StringUtil.isNullOrEmpty(paraNames)) { 1038 | return null; 1039 | } 1040 | Annotation[][] paraAnnotations = method.getParameterAnnotations(); 1041 | List entitys = new ArrayList(); 1042 | for (int i = 0; i < paraNames.size(); i++) { 1043 | BeanEntity entity = new BeanEntity(); 1044 | entity.setFieldName(paraNames.get(i)); 1045 | entity.setFieldAnnotations(paraAnnotations[i]); 1046 | entity.setFieldType(types[i]); 1047 | entitys.add(entity); 1048 | } 1049 | paramMap.put(method, entitys); 1050 | return entitys; 1051 | } catch (Exception e) { 1052 | e.printStackTrace(); 1053 | } 1054 | return null; 1055 | } 1056 | 1057 | /** 1058 | * 1059 | *

1060 | * 获取方法的参数名 1061 | *

1062 | * 1063 | * @param m 1064 | * @return 1065 | */ 1066 | public static List getMethodParaNames(Method method) { 1067 | if (StringUtil.isNullOrEmpty(method.getParameters())) { 1068 | return null; 1069 | } 1070 | List paramNames = new ArrayList(); 1071 | for (Parameter parameter : method.getParameters()) { 1072 | paramNames.add(parameter.getName()); 1073 | } 1074 | return paramNames; 1075 | } 1076 | 1077 | } -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/RequestUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.net.URLDecoder; 6 | import java.util.ArrayList; 7 | import java.util.Enumeration; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | import javax.servlet.http.Cookie; 13 | import javax.servlet.http.HttpServletRequest; 14 | 15 | import org.coody.framework.entity.BaseModel; 16 | import org.coody.framework.entity.BeanEntity; 17 | 18 | /** 19 | * @remark HTTP工具类。 20 | * @author Coody 21 | * @email 644556636@qq.com 22 | * @blog 54sb.org 23 | */ 24 | public class RequestUtil { 25 | 26 | 27 | public static final String user_session = "curr_login_user"; 28 | 29 | public static void setUser(HttpServletRequest request, Object user) { 30 | request.getSession().setAttribute(user_session, user); 31 | } 32 | 33 | @SuppressWarnings("unchecked") 34 | public static T getUser(HttpServletRequest request) { 35 | return (T) request.getSession().getAttribute(user_session); 36 | } 37 | 38 | 39 | public static boolean isUserLogin(HttpServletRequest request) { 40 | Object obj = getUser(request); 41 | if (!StringUtil.isNullOrEmpty(obj)) { 42 | return true; 43 | } 44 | return false; 45 | } 46 | 47 | public static void setCode(HttpServletRequest request, Object code) { 48 | request.getSession().setAttribute("sys_ver_code", code); 49 | } 50 | 51 | @SuppressWarnings("unchecked") 52 | public static T getCode(HttpServletRequest request) { 53 | return (T) request.getSession().getAttribute("sys_ver_code"); 54 | } 55 | 56 | public static String getIpAddr(HttpServletRequest request) { 57 | String ip=request.getRemoteAddr(); 58 | if(!isInvialIp(ip)){ 59 | return ip; 60 | } 61 | ip = request.getHeader("X-Real-IP"); 62 | if(!isInvialIp(ip)){ 63 | return ip; 64 | } 65 | ip = request.getHeader("X-Forwarded-For"); 66 | if(!isInvialIp(ip)){ 67 | // 多次反向代理后会有多个IP值,第一个为真实IP。 68 | int index = ip.indexOf(','); 69 | if (index != -1) { 70 | return ip.substring(0, index); 71 | } 72 | return ip; 73 | } 74 | return "未知"; 75 | } 76 | 77 | private static boolean isInvialIp(String ip){ 78 | if(ip.equals("127.0.0.1")||ip.equalsIgnoreCase("localhost")){ 79 | return true; 80 | } 81 | if (StringUtil.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { 82 | return true; 83 | } 84 | return false; 85 | } 86 | public static String getRequestUri(HttpServletRequest request) { 87 | String uri = request.getServletPath(); 88 | 89 | String projectName = request.getContextPath(); 90 | if (projectName != null && !projectName.trim().equals("")) { 91 | uri = uri.replace(projectName, "/"); 92 | } 93 | uri = uri.replace("../", "/"); 94 | while (uri.indexOf("//") > -1) { 95 | uri = uri.replace("//", "/"); 96 | } 97 | return uri; 98 | } 99 | 100 | public static String getURLSuffix(HttpServletRequest request) { 101 | String url = request.getServletPath(); 102 | String[] tab = url.split("\\."); 103 | if (tab.length > 1) { 104 | String suffix= tab[tab.length - 1]; 105 | if(!StringUtil.isNullOrEmpty(suffix)){ 106 | request.setAttribute("suffix", suffix); 107 | } 108 | return suffix; 109 | } 110 | return ""; 111 | } 112 | 113 | /** 114 | * 根据Request获取Model。排除指定参数 115 | * 116 | * @param request 117 | * 请求对象 118 | * @param obj 119 | * 实例化的Model对象 120 | * @param paraArgs 121 | * 指定参数 122 | * @return 123 | */ 124 | public static T getBeanRemove(HttpServletRequest request, 125 | String paraName, Object obj, String... paraArgs) { 126 | return getBean(request, obj, null, paraName, null, true, paraArgs); 127 | } 128 | 129 | /** 130 | * 根据Request获取Model。接受指定参数 131 | * 132 | * @param request 133 | * 请求对象 134 | * @param obj 135 | * 实例化的Model对象 136 | * @param paraArgs 137 | * 指定参数 138 | * @return 139 | */ 140 | public static T getBeanAccept(HttpServletRequest request, 141 | String paraName, Object obj, String... paraArgs) { 142 | return getBean(request, obj, null, paraName, null, false, paraArgs); 143 | } 144 | 145 | /** 146 | * 根据Request获取Model所有参数 147 | * 148 | * @param request 149 | * 请求对象 150 | * @param obj 151 | * 实例化的Model对象 152 | * @return 153 | */ 154 | public static T getBeanAll(HttpServletRequest request, String paraName, 155 | Object obj) { 156 | return getBean(request, obj, null, paraName, null, true, null); 157 | } 158 | 159 | @SuppressWarnings("unchecked") 160 | private static T getBean(HttpServletRequest request, Object obj, 161 | List fields, String baseName, String firstSuffix, 162 | Boolean isReplace, String[] paraArgs) { 163 | try { 164 | if (obj instanceof Class) { 165 | obj = ((Class) obj).newInstance(); 166 | } 167 | firstSuffix = StringUtil.isNullOrEmpty(firstSuffix) ? "" 168 | : (firstSuffix + "."); 169 | isReplace = StringUtil.isNullOrEmpty(isReplace) ? false : isReplace; 170 | baseName = StringUtil.isNullOrEmpty(baseName) ? "" 171 | : (baseName + "."); 172 | List paras = null; 173 | if (!StringUtil.isNullOrEmpty(paraArgs)) { 174 | paras = new ArrayList(); 175 | for (String tmp : paraArgs) { 176 | if (StringUtil.isNullOrEmpty(tmp)) { 177 | continue; 178 | } 179 | String[] tab = tmp.split("\\."); 180 | for (String tmpTab : tab) { 181 | paras.add(tmpTab); 182 | } 183 | } 184 | } 185 | if (StringUtil.isNullOrEmpty(fields)) { 186 | // 获取对象字段属性 187 | fields = PropertUtil.getBeanFields(obj); 188 | } 189 | firstSuffix = (firstSuffix == null) ? "" : firstSuffix; 190 | Object childObj, paraValue = null; 191 | String paraName = null; 192 | for (BeanEntity entity : fields) { 193 | try { 194 | paraName = firstSuffix + baseName + entity.getFieldName(); 195 | if (!StringUtil.isNullOrEmpty(paras)) { 196 | if (isReplace) { 197 | if (paras.contains(paraName)) { 198 | continue; 199 | } 200 | } 201 | if (!isReplace) { 202 | if (!paras.contains(paraName)) { 203 | continue; 204 | } 205 | } 206 | } 207 | if (BaseModel.class.isAssignableFrom(entity.getFieldType())) { 208 | childObj = entity.getFieldType().newInstance(); 209 | childObj = getBean(request, childObj, null, paraName, 210 | firstSuffix, isReplace, paraArgs); 211 | PropertUtil.setProperties(obj, entity.getFieldName(), 212 | childObj); 213 | continue; 214 | } 215 | paraValue = request.getParameter(paraName); 216 | if (paraValue==null) { 217 | continue; 218 | } 219 | PropertUtil.setProperties(obj, entity.getFieldName(), 220 | paraValue); 221 | 222 | } catch (Exception e) { 223 | } 224 | } 225 | return (T) obj; 226 | } catch (Exception e) { 227 | 228 | 229 | } 230 | return null; 231 | } 232 | 233 | @SuppressWarnings("unchecked") 234 | public static void keepParas(HttpServletRequest request) { 235 | Enumeration paras = request.getParameterNames(); 236 | if (StringUtil.isNullOrEmpty(paras)) { 237 | return; 238 | } 239 | while (paras.hasMoreElements()) { 240 | try { 241 | String string = (String) paras.nextElement(); 242 | if (StringUtil.isNullOrEmpty(string)) { 243 | continue; 244 | } 245 | request.setAttribute(string.replace(".", "_"), 246 | request.getParameter(string)); 247 | } catch (Exception e) { 248 | 249 | } 250 | 251 | } 252 | } 253 | 254 | public static String getRequestURI(HttpServletRequest request) { 255 | String uri = request.getRequestURI(); 256 | String projectName = request.getContextPath(); 257 | if (projectName != null && !projectName.trim().equals("")) { 258 | uri = uri.replace(projectName, "/"); 259 | } 260 | uri = uri.replace("../", "/"); 261 | while (uri.indexOf("//") > -1) { 262 | uri = uri.replace("//", "/"); 263 | } 264 | return uri; 265 | } 266 | 267 | /** 268 | * 获取POST请求参数中数据 269 | * 270 | * @param request 271 | * @throws IOException 272 | */ 273 | public static String getPostContent(HttpServletRequest request) { 274 | String content = null; 275 | try { 276 | content = inputStream2String(request.getInputStream()); 277 | content=URLDecoder.decode(content,"UTF-8"); 278 | } catch (Exception e) { 279 | 280 | } 281 | return content; 282 | } 283 | public static String inputStream2String(InputStream in) throws IOException { 284 | StringBuffer out = new StringBuffer(); 285 | byte[] b = new byte[4096]; 286 | for (int n; (n = in.read(b)) != -1;) { 287 | out.append(new String(b, 0, n)); 288 | } 289 | return out.toString(); 290 | } 291 | 292 | public static String getRequestCookies(HttpServletRequest request) { 293 | Cookie[] cookies = request.getCookies(); 294 | if (StringUtil.isNullOrEmpty(cookies)) { 295 | return null; 296 | } 297 | StringBuilder sb = new StringBuilder(); 298 | for (Cookie cook : cookies) { 299 | sb.append(" "+cook.getName()).append("=").append(cook.getValue()) 300 | .append(";"); 301 | } 302 | return sb.toString(); 303 | } 304 | @SuppressWarnings("unchecked") 305 | public static Map getParas(HttpServletRequest request) { 306 | Map map=request.getParameterMap(); 307 | if(StringUtil.isNullOrEmpty(map)){ 308 | return null; 309 | } 310 | Map paraMap=new HashMap(); 311 | Cookie[] cooks=request.getCookies(); 312 | if(!StringUtil.isNullOrEmpty(cooks)) { 313 | for(Cookie cook:cooks){ 314 | try { 315 | paraMap.put(cook.getName(), cook.getValue()); 316 | } catch (Exception e) { 317 | 318 | } 319 | } 320 | } 321 | 322 | for (String key:map.keySet()) { 323 | String[] values=map.get(key); 324 | if(StringUtil.isNullOrEmpty(values)){ 325 | continue; 326 | } 327 | if(values.length==1){ 328 | paraMap.put(key, values[0]); 329 | continue; 330 | } 331 | paraMap.put(key, values); 332 | } 333 | return paraMap; 334 | 335 | 336 | } 337 | public static T parseRequestToBean(HttpServletRequest req,Class clazz){ 338 | Map paraMap=getParas(req); 339 | return parseMapToBean(paraMap, clazz); 340 | } 341 | public static T parseMapToBean(Map paraMap,Class clazz){ 342 | if(StringUtil.isNullOrEmpty(paraMap)){ 343 | return null; 344 | } 345 | try { 346 | T bean=clazz.newInstance(); 347 | for(String key:paraMap.keySet()){ 348 | try { 349 | PropertUtil.setProperties(bean, key, paraMap.get(key)); 350 | } catch (Exception e) { 351 | 352 | } 353 | } 354 | return bean; 355 | } catch (Exception e) { 356 | 357 | } 358 | return null; 359 | } 360 | public static String loadBasePath(HttpServletRequest request) { 361 | String path = request.getContextPath(); 362 | String basePath = request.getScheme() 363 | + "://" 364 | + request.getServerName() 365 | + (request.getServerPort() == 80 ? "" : ":" 366 | + request.getServerPort()) + path + "/"; 367 | basePath=basePath.replace("http:", ""); 368 | basePath=basePath.replace("https:", ""); 369 | request.getSession().setAttribute("basePath", basePath); 370 | request.setAttribute("basePath", basePath); 371 | return basePath; 372 | } 373 | public static void main(String[] args) { 374 | 375 | } 376 | 377 | } 378 | -------------------------------------------------------------------------------- /src/main/java/org/coody/framework/util/StringUtil.java: -------------------------------------------------------------------------------- 1 | package org.coody.framework.util; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.Collection; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | import java.util.Vector; 11 | import java.util.regex.Matcher; 12 | import java.util.regex.Pattern; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | 16 | //import oracle.sql.CLOB; 17 | 18 | public class StringUtil { 19 | 20 | 21 | public static Integer[] getIntegerParas(Object[] objs) { 22 | if (isNullOrEmpty(objs)) { 23 | return null; 24 | } 25 | Integer[] ints = new Integer[objs.length]; 26 | for (int i = 0; i < objs.length; i++) { 27 | try { 28 | ints[i] = Integer.valueOf(objs[i].toString()); 29 | } catch (Exception e) { 30 | } 31 | } 32 | return ints; 33 | } 34 | 35 | /** 36 | * 生成指定数目字符串按分隔符分割 37 | * 38 | * @param baseStr 39 | * @param mosaicChr 40 | * @param size 41 | * @return 42 | */ 43 | public static String getByMosaicChr(String baseStr, String mosaicChr, Integer size) { 44 | List list = new ArrayList(); 45 | for (int i = 0; i < size; i++) { 46 | if (isNullOrEmpty(baseStr)) { 47 | continue; 48 | } 49 | list.add(baseStr); 50 | } 51 | return collectionMosaic(list, mosaicChr); 52 | } 53 | 54 | /** 55 | * 根据分割符将字符串分割成String数组 56 | * 57 | * @param src 58 | * 源字符串 59 | * @param separator 60 | * 分隔�? 61 | * @return String数组 62 | */ 63 | public static String[] splitToStringArray(String src, String separator) { 64 | Vector splitArrays = new Vector(); 65 | int i = 0; 66 | int j = 0; 67 | while (i <= src.length()) { 68 | j = src.indexOf(separator, i); 69 | if (j < 0) { 70 | j = src.length(); 71 | } 72 | splitArrays.addElement(src.substring(i, j)); 73 | i = j + 1; 74 | } 75 | int size = splitArrays.size(); 76 | String[] array = new String[size]; 77 | System.arraycopy(splitArrays.toArray(), 0, array, 0, size); 78 | return array; 79 | } 80 | 81 | /** 82 | * 根据分割符将字符串分割成Integer数组 83 | * 84 | * @param src 85 | * 源字符串 86 | * @param separator 87 | * 分隔�? 88 | * @return Integer数组 89 | */ 90 | public static Integer[] splitToIntgArray(String src, String separator) { 91 | String[] arr = splitToStringArray(src, separator); 92 | Integer[] intArr = new Integer[arr.length]; 93 | for (int i = 0; i < arr.length; i++) { 94 | intArr[i] = Integer.valueOf(arr[i]); 95 | } 96 | return intArr; 97 | } 98 | 99 | /** 100 | * 根据分隔符将字符串分割成int数组 101 | * 102 | * @param src 103 | * 源字符串 104 | * @param separator 105 | * 分隔�? 106 | * @return int数组 107 | */ 108 | public static int[] splitToIntArray(String src, String separator) { 109 | String[] arr = splitToStringArray(src, separator); 110 | int[] intArr = new int[arr.length]; 111 | for (int i = 0; i < arr.length; i++) { 112 | intArr[i] = Integer.parseInt(arr[i]); 113 | } 114 | return intArr; 115 | } 116 | 117 | public static String getInPara(Integer size) { 118 | return getByMosaicChr("?", ",", size); 119 | 120 | } 121 | 122 | public static String textCutCenter(String allTxt, String firstTxt, String lastTxt) { 123 | try { 124 | String tmp = ""; 125 | int n1 = allTxt.indexOf(firstTxt); 126 | if (n1 == -1) { 127 | return ""; 128 | } 129 | tmp = allTxt.substring(n1 + firstTxt.length(), allTxt.length()); 130 | int n2 = tmp.indexOf(lastTxt); 131 | if (n2 == -1) { 132 | return ""; 133 | } 134 | tmp = tmp.substring(0, n2); 135 | return tmp; 136 | } catch (Exception e) { 137 | return ""; 138 | } 139 | } 140 | 141 | public static List textCutCenters(String allTxt, String firstTxt, String lastTxt) { 142 | try { 143 | List results = new ArrayList(); 144 | while (allTxt.contains(firstTxt)) { 145 | int n = allTxt.indexOf(firstTxt); 146 | allTxt = allTxt.substring(n + firstTxt.length(), allTxt.length()); 147 | n = allTxt.indexOf(lastTxt); 148 | if (n == -1) { 149 | return results; 150 | } 151 | String result = allTxt.substring(0, n); 152 | results.add(result); 153 | allTxt = allTxt.substring(n + firstTxt.length(), allTxt.length()); 154 | } 155 | return results; 156 | } catch (Exception e) { 157 | return null; 158 | } 159 | } 160 | 161 | public static String convertToUnicode(String source) { 162 | String result = ""; 163 | char[] chrs = source.toCharArray(); 164 | for (int i = 0; i < chrs.length; i++) { 165 | result += "&#" + Character.codePointAt(chrs, i); 166 | } 167 | return result; 168 | } 169 | 170 | public static Integer toInteger(Object obj) { 171 | if (isNullOrEmpty(obj)) { 172 | return null; 173 | } 174 | try { 175 | return Integer.valueOf(obj.toString()); 176 | } catch (Exception e) { 177 | return null; 178 | } 179 | } 180 | 181 | public static String toString(Object obj) { 182 | if (isNullOrEmpty(obj)) { 183 | return null; 184 | } 185 | try { 186 | return String.valueOf(obj.toString()); 187 | } catch (Exception e) { 188 | return null; 189 | } 190 | } 191 | 192 | public static Double toDouble(Object obj) { 193 | if (isNullOrEmpty(obj)) { 194 | return null; 195 | } 196 | try { 197 | return Double.valueOf(obj.toString()); 198 | } catch (Exception e) { 199 | return null; 200 | } 201 | } 202 | 203 | public static Float toFloat(Object obj) { 204 | if (isNullOrEmpty(obj)) { 205 | return null; 206 | } 207 | try { 208 | return Float.valueOf(obj.toString()); 209 | } catch (Exception e) { 210 | return null; 211 | } 212 | } 213 | 214 | public static Long toLong(Object obj) { 215 | if (isNullOrEmpty(obj)) { 216 | return null; 217 | } 218 | try { 219 | return Long.valueOf(obj.toString()); 220 | } catch (Exception e) { 221 | return null; 222 | } 223 | } 224 | 225 | public static Integer getRanDom(int start, int end) { 226 | return (int) (Math.random() * (end - start + 1)) + start; 227 | } 228 | 229 | public static float getRanDom(Float start, Float end) { 230 | String str = String.valueOf(start); 231 | String[] tabs = str.split("\\."); 232 | Integer startLength = 1; 233 | if (tabs.length == 2) { 234 | startLength = tabs[1].length(); 235 | } 236 | str = String.valueOf(end); 237 | tabs = str.split("\\."); 238 | Integer endLength = 1; 239 | if (tabs.length == 2) { 240 | endLength = tabs[1].length(); 241 | } 242 | if (endLength > startLength) { 243 | startLength = endLength; 244 | } 245 | start = (float) (start * Math.pow(10, startLength)); 246 | end = (float) (end * Math.pow(10, startLength)); 247 | return (float) (getRanDom(start.intValue(), end.intValue()) / Math.pow(10, startLength)); 248 | } 249 | 250 | public static String replaceBlank(String str) { 251 | String dest = ""; 252 | if (str != null) { 253 | Pattern p = Pattern.compile("\\s*|\t|\r|\n"); 254 | Matcher m = p.matcher(str); 255 | dest = m.replaceAll(""); 256 | } 257 | return dest; 258 | } 259 | 260 | public static Boolean isMatcher(String val, String matcher) { 261 | Pattern p = Pattern.compile(matcher); 262 | Matcher m = p.matcher(val); 263 | return m.matches(); 264 | } 265 | 266 | public static List matchExport(String context, String patten) { 267 | try { 268 | Integer index = 0; 269 | Pattern pattern = Pattern.compile(patten, Pattern.DOTALL); 270 | Matcher matcher = pattern.matcher(context); 271 | List results = new ArrayList(); 272 | while (matcher.find(index)) { 273 | String tmp = matcher.group(1); 274 | index = matcher.end(); 275 | if (isNullOrEmpty(tmp)) { 276 | continue; 277 | } 278 | results.add(tmp); 279 | } 280 | return results; 281 | } catch (Exception e) { 282 | return null; 283 | } 284 | } 285 | 286 | public static String matchExportFirst(String context, String patten) { 287 | try { 288 | Integer index = 0; 289 | Pattern pattern = Pattern.compile(patten, Pattern.DOTALL); 290 | Matcher matcher = pattern.matcher(context); 291 | while (matcher.find(index)) { 292 | String tmp = matcher.group(1); 293 | index = matcher.end(); 294 | if (isNullOrEmpty(tmp)) { 295 | continue; 296 | } 297 | return tmp; 298 | } 299 | return null; 300 | } catch (Exception e) { 301 | return null; 302 | } 303 | } 304 | public static boolean isMobile(String mobile) { 305 | if (isNullOrEmpty(mobile)) { 306 | return false; 307 | } 308 | Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[^4,\\D])|(18[0,5-9]))\\d{8}$"); 309 | Matcher m = p.matcher(mobile); 310 | return m.matches(); 311 | } 312 | 313 | public static boolean isLegal(String str) { 314 | if (isNullOrEmpty(str)) { 315 | return false; 316 | } 317 | Pattern p = Pattern.compile("[A-Za-z0-9_]{3,16}"); 318 | Matcher m = p.matcher(str); 319 | return m.matches(); 320 | } 321 | 322 | public static boolean isEmail(String email) { 323 | if (isNullOrEmpty(email)) { 324 | return false; 325 | } 326 | Pattern p = Pattern.compile( 327 | "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"); 328 | Matcher m = p.matcher(email); 329 | return m.matches(); 330 | } 331 | 332 | public static boolean isMd5(String md5) { 333 | if (isNullOrEmpty(md5)) { 334 | return false; 335 | } 336 | Pattern p = Pattern.compile("[A-Za-z0-9_]{16,40}"); 337 | Matcher m = p.matcher(md5); 338 | return m.matches(); 339 | } 340 | 341 | public static boolean isAllNull(Object... obj) { 342 | if (obj == null || obj.length == 0) { 343 | return true; 344 | } 345 | for (int i = 0; i < obj.length; i++) { 346 | if (!isNullOrEmpty(obj[i])) { 347 | return false; 348 | } 349 | } 350 | return true; 351 | } 352 | 353 | public static boolean isAllNull(List objs) { 354 | return isAllNull(objs.toArray()); 355 | } 356 | 357 | /** 358 | * 把一个数组按照分隔符拼接成字符串 359 | * 360 | * @param 数组参数 361 | * @param 分隔符 362 | * @return 363 | */ 364 | public static String collectionMosaic(Object[] objs, String mosaicChr) { 365 | if (isNullOrEmpty(objs)) { 366 | return null; 367 | } 368 | List objList = Arrays.asList(objs); 369 | return collectionMosaic(objList, mosaicChr); 370 | } 371 | 372 | /** 373 | * 把一个数组按照分隔符拼接成字符串 374 | * 375 | * @param 数组参数 376 | * @param 分隔符 377 | * @return 378 | */ 379 | public static String collectionMosaic(int[] intObjs, String mosaicChr) { 380 | Object[] objs = new Object[intObjs.length]; 381 | for (int i = 0; i < intObjs.length; i++) { 382 | objs[i] = String.valueOf(intObjs[i]); 383 | } 384 | return collectionMosaic(objs, mosaicChr); 385 | } 386 | 387 | /** 388 | * 把一个或多个字符串按照分隔符拼接成字符串 389 | * 390 | * @param 数组参数 391 | * @param 分隔符 392 | * @return 393 | */ 394 | public static String collectionMosaic(String mosaicChr, Object... objs) { 395 | List objList = Arrays.asList(objs); 396 | return collectionMosaic(objList, mosaicChr); 397 | } 398 | @SuppressWarnings({ "unchecked", "rawtypes" }) 399 | public static String collectionMosaic(Set objs, String mosaicChr) { 400 | return collectionMosaic(new ArrayList(objs), mosaicChr); 401 | } 402 | /** 403 | * 把一个集合按照分隔符拼接成字符串 404 | * 405 | * @param 集合参数 406 | * @param 分隔符 407 | * @return 字符串 408 | */ 409 | public static String collectionMosaic(List objs, String mosaicChr) { 410 | if (objs == null || objs.isEmpty()) { 411 | return null; 412 | } 413 | StringBuilder sb = new StringBuilder(); 414 | int i = 0; 415 | for (Object obj : objs) { 416 | if (isNullOrEmpty(obj)) { 417 | continue; 418 | } 419 | sb.append(obj); 420 | if (i < objs.size() - 1) { 421 | sb.append(mosaicChr); 422 | } 423 | i++; 424 | } 425 | return sb.toString(); 426 | } 427 | 428 | /** 429 | * 生成指定数目字符串按分隔符分割 430 | * 431 | * @param baseStr 432 | * @param mosaicChr 433 | * @param size 434 | * @return 435 | */ 436 | public static String getStringSByMosaicChr(String baseStr, String mosaicChr, Integer size) { 437 | List list = new ArrayList(); 438 | for (int i = 0; i < size; i++) { 439 | if (isNullOrEmpty(baseStr)) { 440 | continue; 441 | } 442 | list.add(baseStr); 443 | } 444 | return collectionMosaic(list, mosaicChr); 445 | } 446 | 447 | /** 448 | * 按照分隔符分割,得到字符串集合 449 | * 450 | * @param text 451 | * 原字符串 452 | * @param mosaiChr 453 | * 分隔符 454 | * @return list 455 | */ 456 | public static List splitByMosaic(String text, String mosaiChr) { 457 | if (text == null || mosaiChr == null) { 458 | return null; 459 | } 460 | String[] tab = text.split(mosaiChr); 461 | List list = new ArrayList(); 462 | for (int i = 0; i < tab.length; i++) { 463 | if (isNullOrEmpty(tab[i])) { 464 | continue; 465 | } 466 | list.add(tab[i]); 467 | } 468 | return list; 469 | } 470 | 471 | /** 472 | * 按照分隔符分割,得到字符串集合 473 | * 474 | * @param text 475 | * 原字符串 476 | * @param mosaiChr 477 | * 分隔符 478 | * @return list 479 | */ 480 | public static List splitByMosaicInteger(String text, String mosaiChr) { 481 | if (text == null || mosaiChr == null) { 482 | return null; 483 | } 484 | String[] tab = text.split(mosaiChr); 485 | List list = new ArrayList(); 486 | for (int i = 0; i < tab.length; i++) { 487 | if (isNullOrEmpty(tab[i])) { 488 | continue; 489 | } 490 | try { 491 | list.add(Integer.valueOf(tab[i])); 492 | } catch (Exception e) { 493 | } 494 | 495 | } 496 | return list; 497 | } 498 | 499 | /** 500 | * 按照分隔符分割,得到字符串集合 501 | * 502 | * @param text 503 | * 原字符串 504 | * @param mosaiChr 505 | * 分隔符 506 | * @return list 507 | */ 508 | public static Integer[] splitByMosaicIntegers(String text, String mosaiChr) { 509 | if (text == null || mosaiChr == null) { 510 | return null; 511 | } 512 | String[] tab = text.split(mosaiChr); 513 | Integer[] list = new Integer[tab.length]; 514 | for (int i = 0; i < tab.length; i++) { 515 | if (isNullOrEmpty(tab[i])) { 516 | continue; 517 | } 518 | try { 519 | list[i] = Integer.valueOf(tab[i]); 520 | } catch (Exception e) { 521 | } 522 | 523 | } 524 | return list; 525 | } 526 | 527 | public static List doMatcher(String context, String pat) { 528 | try { 529 | List images = new ArrayList(); 530 | Integer index = 0; 531 | Pattern pattern = Pattern.compile(pat, Pattern.DOTALL); 532 | Matcher matcher = pattern.matcher(context); 533 | String tmp = null; 534 | while (matcher.find(index)) { 535 | tmp = matcher.group(1); 536 | index = matcher.end(); 537 | if (StringUtil.isNullOrEmpty(tmp)) { 538 | continue; 539 | } 540 | images.add(tmp); 541 | } 542 | return images; 543 | } catch (Exception e) { 544 | return null; 545 | } 546 | } 547 | 548 | public static String doMatcherFirst(String context, String pat) { 549 | List strs = doMatcher(context, pat); 550 | if (StringUtil.isNullOrEmpty(strs)) { 551 | return null; 552 | } 553 | return strs.get(0); 554 | } 555 | 556 | public static boolean isNullOrEmpty(Object obj) { 557 | try { 558 | if (obj == null) 559 | return true; 560 | if (obj instanceof CharSequence) { 561 | return ((CharSequence) obj).length() == 0; 562 | } 563 | if (obj instanceof Collection) { 564 | return ((Collection) obj).isEmpty(); 565 | } 566 | if (obj instanceof Map) { 567 | return ((Map) obj).isEmpty(); 568 | } 569 | if (obj instanceof Object[]) { 570 | Object[] object = (Object[]) obj; 571 | if (object.length == 0) { 572 | return true; 573 | } 574 | boolean empty = true; 575 | for (int i = 0; i < object.length; i++) { 576 | if (!isNullOrEmpty(object[i])) { 577 | empty = false; 578 | break; 579 | } 580 | } 581 | return empty; 582 | } 583 | return false; 584 | } catch (Exception e) { 585 | return true; 586 | } 587 | 588 | } 589 | 590 | public static Integer findNull(Object... objs) { 591 | if (isNullOrEmpty(objs)) { 592 | return 0; 593 | } 594 | for (int i = 0; i < objs.length; i++) { 595 | if (isNullOrEmpty(objs[i])) { 596 | return i; 597 | } 598 | } 599 | return -1; 600 | } 601 | 602 | public static boolean hasNull(Object... objs) { 603 | return findNull(objs) > -1; 604 | } 605 | 606 | // 判断是否为数字 607 | public static Boolean isNumber(String str) { 608 | if (isNullOrEmpty(str)) { 609 | return false; 610 | } 611 | try { 612 | Integer.valueOf(str); 613 | return true; 614 | } catch (Exception e) { 615 | return false; 616 | } 617 | } 618 | 619 | public static String argsToString(String[] args) { 620 | StringBuilder sb = new StringBuilder(); 621 | for (String tmp : args) { 622 | sb.append(tmp); 623 | } 624 | return sb.toString(); 625 | } 626 | 627 | // 字符串意义分割 628 | public static String[] splitString(String str) { 629 | if (isNullOrEmpty(str)) { 630 | return null; 631 | } 632 | String[] finalStrs = new String[str.length()]; 633 | for (int i = 0; i < str.length(); i++) { 634 | finalStrs[i] = str.substring(i, i + 1); 635 | } 636 | return finalStrs; 637 | } 638 | 639 | public static String getString(Object... objs) { 640 | if (isNullOrEmpty(objs)) { 641 | return ""; 642 | } 643 | StringBuilder sb = new StringBuilder(); 644 | for (Object obj : objs) { 645 | if (isNullOrEmpty(obj)) { 646 | sb.append("null"); 647 | } 648 | sb.append(String.valueOf(obj)); 649 | } 650 | return sb.toString(); 651 | } 652 | 653 | public static String stringSort(String str) { 654 | if (isNullOrEmpty(str)) { 655 | return ""; 656 | } 657 | String[] strs = splitString(str); 658 | Arrays.sort(strs); 659 | return argsToString(strs); 660 | } 661 | 662 | /** 663 | * 集合碰撞 664 | * 665 | * @param needList 666 | * 需要的集合 667 | * @param actualList 668 | * 当前实际集合 669 | * @return 缺少的元素 670 | */ 671 | public static List collisionList(List needList, List actualList) { 672 | List list = new ArrayList(); 673 | for (Object o : needList) { 674 | if (actualList.contains(o)) { 675 | continue; 676 | } 677 | list.add(o); 678 | } 679 | if (isNullOrEmpty(list)) { 680 | return null; 681 | } 682 | return list; 683 | } 684 | 685 | public static List integerListToLong(List ids) { 686 | if (isNullOrEmpty(ids)) { 687 | return null; 688 | } 689 | List list = new ArrayList(); 690 | for (Integer id : ids) { 691 | list.add(Long.valueOf(id)); 692 | } 693 | return list; 694 | } 695 | 696 | /** 697 | * List碰撞取缺失 698 | * 699 | * @param allList 700 | * 理论应该出现的List 701 | * @param conflictList 702 | * 实际出现的List 703 | * @return 丢失的List 704 | */ 705 | public static List listConflict(List allList, List conflictList) { 706 | if (isNullOrEmpty(allList)) { 707 | return null; 708 | } 709 | if (isNullOrEmpty(conflictList)) { 710 | return allList; 711 | } 712 | List list = new ArrayList(); 713 | for (Object obj : allList) { 714 | if (conflictList.contains(obj)) { 715 | continue; 716 | } 717 | list.add(obj); 718 | } 719 | if (isNullOrEmpty(list)) { 720 | return null; 721 | } 722 | return list; 723 | } 724 | 725 | public static Integer bambooParse(Integer... prs) { 726 | Integer prSum = 0; 727 | for (Integer pr : prs) { 728 | prSum += pr; 729 | } 730 | Integer random = getRanDom(1, prSum); 731 | prSum = 0; 732 | for (int i = 0; i < prs.length; i++) { 733 | prSum += prs[i]; 734 | if (random <= prSum) { 735 | return i; 736 | } 737 | } 738 | return 0; 739 | } 740 | 741 | public static Integer SumInteger(Integer... sums) { 742 | if (isNullOrEmpty(sums)) { 743 | return -1; 744 | } 745 | Integer total = 0; 746 | for (Integer tmp : sums) { 747 | total += tmp; 748 | } 749 | return total; 750 | } 751 | 752 | /** 753 | * 概率算法 754 | * 755 | * @param chances 756 | * 各成员概率权重 757 | * @return 权重下标 758 | */ 759 | public static Integer getBambooIndex(Integer... chances) { 760 | if (isNullOrEmpty(chances)) { 761 | return -1; 762 | } 763 | Integer total = SumInteger(chances); 764 | Integer random = getRanDom(1, total); 765 | total = new Integer(0); 766 | for (int i = 0; i < chances.length; i++) { 767 | total += chances[i]; 768 | if (random <= total) { 769 | return i; 770 | } 771 | } 772 | return -1; 773 | } 774 | 775 | public static List removeEmpty(List list) { 776 | if (StringUtil.isNullOrEmpty(list)) { 777 | return null; 778 | } 779 | List newList = new ArrayList(list.size()); 780 | for (Object obj : list) { 781 | if (isNullOrEmpty(obj)) { 782 | continue; 783 | } 784 | newList.add(obj); 785 | } 786 | if (isNullOrEmpty(newList)) { 787 | return null; 788 | } 789 | return newList; 790 | } 791 | 792 | public static Integer getBambooIndex(Float... chanceSources) { 793 | if (isNullOrEmpty(chanceSources)) { 794 | return -1; 795 | } 796 | Float[] chances = Arrays.copyOf(chanceSources, chanceSources.length); 797 | Integer smallLength = 0; 798 | for (Float f : chances) { 799 | String str = String.valueOf(f); 800 | String[] tabs = str.split("\\."); 801 | if (tabs.length != 2) { 802 | continue; 803 | } 804 | smallLength = tabs[1].length(); 805 | } 806 | if (smallLength > 0) { 807 | Integer multiple = Double.valueOf(Math.pow(10, smallLength)).intValue(); 808 | for (int i = 0; i < chances.length; i++) { 809 | chances[i] = chances[i] * multiple; 810 | } 811 | } 812 | Integer[] chanceInts = new Integer[chances.length]; 813 | for (int i = 0; i < chances.length; i++) { 814 | chanceInts[i] = chances[i].intValue(); 815 | } 816 | return getBambooIndex(chanceInts); 817 | } 818 | 819 | public static Float floatCut(Float f1, Float f2) { 820 | BigDecimal b1 = new BigDecimal(Float.toString(f1)); 821 | BigDecimal b2 = new BigDecimal(Float.toString(f2)); 822 | return b1.subtract(b2).floatValue(); 823 | } 824 | 825 | /** 826 | * 获取网址后缀 827 | * 828 | * @param url 829 | * @return 830 | */ 831 | public static String getSuffix(String url) { 832 | if (isNullOrEmpty(url)) { 833 | return ""; 834 | } 835 | String[] tab = url.split("\\."); 836 | if (tab.length > 1) { 837 | return tab[tab.length - 1]; 838 | } 839 | return ""; 840 | } 841 | 842 | /** 843 | * 判断是否为android模拟器 844 | * 845 | * @param request 846 | * @return 模拟器返回true 847 | */ 848 | public static boolean isAndroidEmulator(HttpServletRequest request) { 849 | try { 850 | String userAgent = request.getHeader("user-agent"); 851 | if (!StringUtil.isNullOrEmpty(userAgent)) { 852 | if (userAgent.contains("Droid4X") || userAgent.contains("kaopu") || userAgent.contains("Windroye") 853 | || userAgent.contains("BlueStacks") || userAgent.contains("sdk Build") 854 | || userAgent.contains("TianTian")) 855 | return true; 856 | Pattern pattern = Pattern.compile(".*Lan.*Build.*"); 857 | Matcher matcher = pattern.matcher(userAgent); 858 | if (matcher.matches()) 859 | return true; 860 | return false; 861 | } 862 | } catch (Exception e) { 863 | return false; 864 | } 865 | return false; 866 | } 867 | 868 | /** 869 | * 是否存在乱码 870 | * 871 | * @param str 872 | * @return 873 | */ 874 | public static boolean isMessyCode(String str) { 875 | for (int i = 0; i < str.length(); i++) { 876 | char c = str.charAt(i); 877 | // 当从Unicode编码向某个字符集转换时,如果在该字符集中没有对应的编码,则得到0x3f(即问号字符?) 878 | // 从其他字符集向Unicode编码转换时,如果这个二进制数在该字符集中没有标识任何的字符,则得到的结果是0xfffd 879 | if ((int) c == 0xfffd) { 880 | // 存在乱码 881 | return true; 882 | } 883 | } 884 | return false; 885 | } 886 | } 887 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/annotation/CacheWipe.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.METHOD) 11 | @Repeatable(CacheWipes.class) 12 | public @interface CacheWipe { 13 | 14 | String key() ; 15 | 16 | String [] fields() default ""; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/annotation/CacheWipes.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | public @interface CacheWipes { 11 | CacheWipe[] value(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/annotation/CacheWrite.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | public @interface CacheWrite { 11 | String key() default ""; 12 | int validTime() default 10; 13 | String [] fields() default ""; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/aspect/CacheAspect.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.aspect; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import org.apache.log4j.Logger; 6 | import org.coody.framework.box.annotation.Around; 7 | import org.coody.framework.box.annotation.InitBean; 8 | import org.coody.framework.box.cache.LocalCache; 9 | import org.coody.framework.box.wrapper.AspectWrapper; 10 | import org.coody.framework.util.AspectUtil; 11 | import org.coody.framework.util.StringUtil; 12 | import org.coody.web.comm.annotation.CacheWipe; 13 | import org.coody.web.comm.annotation.CacheWipes; 14 | import org.coody.web.comm.annotation.CacheWrite; 15 | 16 | @InitBean 17 | public class CacheAspect { 18 | 19 | private final Logger logger = Logger.getLogger(this.getClass()); 20 | 21 | /** 22 | * 写缓存操作 23 | * 24 | * @param pjp 25 | * @return 26 | * @throws Throwable 27 | */ 28 | @Around(CacheWrite.class) 29 | public Object cCacheWrite(AspectWrapper aspect) throws Throwable { 30 | Class clazz = aspect.getClazz(); 31 | Method method = aspect.getMethod(); 32 | if (method == null) { 33 | return aspect.invoke(); 34 | } 35 | // 获取注解 36 | CacheWrite handle = method.getAnnotation(CacheWrite.class); 37 | if (handle == null) { 38 | return aspect.invoke(); 39 | } 40 | // 封装缓存KEY 41 | Object[] paras = aspect.getParams(); 42 | String key = handle.key(); 43 | try { 44 | if (StringUtil.isNullOrEmpty(key)) { 45 | key = AspectUtil.getMethodKey(clazz, method); 46 | } 47 | if (StringUtil.isNullOrEmpty(handle.fields())) { 48 | String paraKey = AspectUtil.getBeanKey(paras); 49 | if (!StringUtil.isNullOrEmpty(paraKey)) { 50 | key += ":"; 51 | key += paraKey; 52 | } 53 | } 54 | if (!StringUtil.isNullOrEmpty(handle.fields())) { 55 | key = AspectUtil.getFieldKey(clazz, method, paras, key, handle.fields()); 56 | } 57 | } catch (Exception e) { 58 | e.printStackTrace(); 59 | } 60 | Integer cacheTimer = ((handle.validTime() == 0) ? 24 * 3600 : handle.validTime()); 61 | // 获取缓存 62 | try { 63 | Object result = LocalCache.getCache(key); 64 | logger.debug("获取缓存:" + key + ",结果:" + result); 65 | if (!StringUtil.isNullOrEmpty(result)) { 66 | return result; 67 | } 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } 71 | Object result = aspect.invoke(); 72 | if (result != null) { 73 | try { 74 | LocalCache.setCache(key, result, cacheTimer); 75 | logger.debug("设置缓存:" + key + ",结果:" + result + ",缓存时间:" + cacheTimer); 76 | } catch (Exception e) { 77 | } 78 | } 79 | return result; 80 | } 81 | 82 | /** 83 | * 缓存清理 84 | * 85 | * @param pjp 86 | * @return 87 | * @throws Throwable 88 | */ 89 | @Around({ CacheWipe.class, CacheWipes.class }) 90 | public Object zCacheWipe(AspectWrapper aspect) throws Throwable { 91 | Class clazz = aspect.getClazz(); 92 | Method method = aspect.getMethod(); 93 | if (method == null) { 94 | return aspect.invoke(); 95 | } 96 | Object[] paras = aspect.getParams(); 97 | Object result = aspect.invoke(); 98 | CacheWipe[] handles = method.getAnnotationsByType(CacheWipe.class); 99 | if (StringUtil.isNullOrEmpty(handles)) { 100 | return result; 101 | } 102 | for (CacheWipe handle : handles) { 103 | try { 104 | String key = handle.key(); 105 | if (StringUtil.isNullOrEmpty(handle.key())) { 106 | key = (AspectUtil.getMethodKey(clazz, method)); 107 | } 108 | if (!StringUtil.isNullOrEmpty(handle.fields())) { 109 | key = AspectUtil.getFieldKey(clazz, method, paras, key, handle.fields()); 110 | } 111 | logger.debug("删除缓存:" + key); 112 | LocalCache.delCache(key); 113 | } catch (Exception e) { 114 | e.printStackTrace(); 115 | } 116 | } 117 | return result; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/aspect/TransactedAspect.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.aspect; 2 | 3 | import java.sql.Connection; 4 | import java.util.List; 5 | 6 | import org.coody.framework.box.annotation.Around; 7 | import org.coody.framework.box.annotation.InitBean; 8 | import org.coody.framework.box.annotation.Transacted; 9 | import org.coody.framework.box.container.TransactedThreadContainer; 10 | import org.coody.framework.box.wrapper.AspectWrapper; 11 | import org.coody.framework.util.StringUtil; 12 | 13 | @InitBean 14 | public class TransactedAspect { 15 | 16 | /** 17 | * 事物控制 18 | * @param wrapper 19 | * @return 20 | * @throws Throwable 21 | */ 22 | @Around(Transacted.class) 23 | public Object transacted(AspectWrapper wrapper) throws Throwable{ 24 | 25 | try{ 26 | TransactedThreadContainer.writeHasTransacted(); 27 | Object result= wrapper.invoke(); 28 | //提交事物 29 | List connections=TransactedThreadContainer.getConnections(); 30 | if(!StringUtil.isNullOrEmpty(connections)){ 31 | for(Connection conn:connections){ 32 | try{ 33 | conn.commit(); 34 | }catch (Exception e) { 35 | } 36 | } 37 | } 38 | return result; 39 | }finally { 40 | //关闭连接 41 | List connections=TransactedThreadContainer.getConnections(); 42 | if(!StringUtil.isNullOrEmpty(connections)){ 43 | for(Connection conn:connections){ 44 | try{ 45 | conn.close(); 46 | }catch (Exception e) { 47 | // TODO: handle exception 48 | } 49 | } 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/base/JdbcTemplate.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.base; 2 | 3 | import java.beans.PropertyVetoException; 4 | import java.io.IOException; 5 | 6 | import org.coody.framework.box.annotation.InitBean; 7 | import org.coody.framework.box.iface.InitFace; 8 | import org.coody.framework.box.jdbc.JdbcHandle; 9 | 10 | @InitBean 11 | public class JdbcTemplate extends JdbcHandle implements InitFace{ 12 | 13 | 14 | public void init() { 15 | try { 16 | initConfig("config/c3p0.properties"); 17 | } catch (IOException e) { 18 | e.printStackTrace(); 19 | } catch (PropertyVetoException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/constant/CacheFinal.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.constant; 2 | 3 | public class CacheFinal { 4 | 5 | /** 6 | * 默认缓存 7 | */ 8 | public static final String AUTO_CACHE_KEY="AUTO_CACHE_KEY"; 9 | /** 10 | * 用户信息 11 | */ 12 | public static final String USER_INFO="USER_INFO"; 13 | /** 14 | * 用户列表 15 | */ 16 | public static final String USER_LIST="USER_LIST"; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/enm/RespEnum.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.enm; 2 | 3 | import org.coody.framework.util.PropertUtil; 4 | 5 | /** 6 | * 消息响应码枚举 7 | * 8 | * @author deng 9 | * 10 | */ 11 | public enum RespEnum { 12 | 13 | SUCCESS(0, "操作成功"),// 成功标志 14 | COMMAND_ERROR(1, "指令有误"), 15 | SYSTEM_ERROR(2, "系统繁忙"), 16 | PARAM_ISERRPR(3,"参数有误"), 17 | NO_DATA(4,"暂无数据"), 18 | DATA_ERROR(5,"数据格式有误"), 19 | LOGIC_TABLE_NOTEXISTS(5,"逻辑表不存在"), 20 | WHERE_PARSE_ERROR(6,"条件解释有误"), 21 | OTHER(-1001,"其他错误"), 22 | ; 23 | private int code; 24 | private String msg; 25 | 26 | public int getCode() { 27 | return code; 28 | } 29 | public String getMsg() { 30 | return msg; 31 | } 32 | public void setMsg(String msg) { 33 | this.msg=msg; 34 | } 35 | RespEnum(int code, String msg) { 36 | this.code = code; 37 | this.msg = msg; 38 | } 39 | 40 | public static String getMsgByCode(Integer code){ 41 | RespEnum enm=PropertUtil.loadEnumByField(RespEnum.class, "code", code); 42 | return enm.getMsg(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/comm/entity/MsgEntity.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.comm.entity; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.coody.framework.entity.BaseModel; 7 | 8 | /** 9 | * @remark 消息机制容器。 10 | * @author Coody 11 | * @email 644556636@qq.com 12 | * @blog 54sb.org 13 | */ 14 | @SuppressWarnings("serial") 15 | public class MsgEntity extends BaseModel { 16 | 17 | public Integer code; 18 | public String msg; 19 | public Object datas; 20 | 21 | public MsgEntity(Integer code, String msg) { 22 | this.code = code; 23 | this.msg = msg; 24 | } 25 | 26 | public MsgEntity() { 27 | } 28 | 29 | public MsgEntity(Integer code, String msg, Object datas) { 30 | super(); 31 | this.code = code; 32 | this.msg = msg; 33 | this.datas = datas; 34 | } 35 | 36 | @SuppressWarnings({ "unchecked", "rawtypes" }) 37 | public void setDataField(String fieldName,Object value){ 38 | if(datas==null){ 39 | datas=new HashMap(); 40 | } 41 | if(!Map.class.isAssignableFrom(datas.getClass())){ 42 | return; 43 | } 44 | try { 45 | ((Map)datas).put(fieldName, value); 46 | } catch (Exception e) { 47 | // TODO: handle exception 48 | } 49 | } 50 | public Object getDatas() { 51 | return datas; 52 | } 53 | 54 | public void setDatas(Object datas) { 55 | this.datas = datas; 56 | } 57 | 58 | public Integer getCode() { 59 | return code; 60 | } 61 | 62 | public void setCode(Integer code) { 63 | this.code = code; 64 | } 65 | 66 | public String getMsg() { 67 | return msg; 68 | } 69 | 70 | public void setMsg(String msg) { 71 | this.msg = msg; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/controller/GeneralController.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.controller; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.coody.framework.box.annotation.JsonSerialize; 7 | import org.coody.framework.box.annotation.PathBinding; 8 | import org.coody.web.comm.entity.MsgEntity; 9 | 10 | import com.alibaba.fastjson.JSON; 11 | /** 12 | * 测试Controller 13 | * @author admin 14 | * 15 | */ 16 | @PathBinding("/") 17 | public class GeneralController { 18 | 19 | 20 | @PathBinding("/index.do") 21 | public Object index(HttpServletRequest request){ 22 | System.out.println(JSON.toJSONString(request.getParameterMap())); 23 | return "index.jsp"; 24 | } 25 | 26 | @PathBinding("/test.do") 27 | @JsonSerialize 28 | public Object test(HttpServletRequest request,HttpServletResponse response){ 29 | System.out.println(JSON.toJSONString(request.getParameterMap())); 30 | return new MsgEntity(0,"操作成功","这是test的内容"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/controller/IcopController.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.controller; 2 | 3 | import java.util.List; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.coody.framework.box.annotation.JsonSerialize; 8 | import org.coody.framework.box.annotation.OutBean; 9 | import org.coody.framework.box.annotation.PathBinding; 10 | import org.coody.framework.util.StringUtil; 11 | import org.coody.web.comm.entity.MsgEntity; 12 | import org.coody.web.domain.IcopTest; 13 | import org.coody.web.service.IcopService; 14 | 15 | @PathBinding("/icop") 16 | public class IcopController { 17 | 18 | 19 | @OutBean 20 | IcopService icopService; 21 | 22 | @PathBinding("loadIcops.do") 23 | @JsonSerialize 24 | public Object loadIcops(){ 25 | List icops=icopService.getIcops(); 26 | return icops; 27 | } 28 | /** 29 | * 删除数据 30 | * @param request 31 | * @return 32 | */ 33 | @PathBinding("delIcop.do") 34 | @JsonSerialize 35 | public Object delIcop(HttpServletRequest request){ 36 | Integer id=StringUtil.toInteger(request.getParameter("id")); 37 | Long code=icopService.delIcop(id); 38 | if(code>0){ 39 | return new MsgEntity(0,"操作成功"); 40 | } 41 | return new MsgEntity(-1,"系统出错"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/dao/IcopDao.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.coody.framework.box.annotation.InitBean; 6 | import org.coody.framework.box.annotation.OutBean; 7 | import org.coody.web.comm.base.JdbcTemplate; 8 | import org.coody.web.domain.IcopTest; 9 | 10 | @InitBean 11 | public class IcopDao { 12 | 13 | @OutBean 14 | JdbcTemplate jdbcTemplate; 15 | 16 | public IcopTest getIcop(Integer id){ 17 | return jdbcTemplate.findBeanFirst(IcopTest.class,"id",id); 18 | } 19 | 20 | 21 | public List getIcops(){ 22 | return jdbcTemplate.findBean(IcopTest.class); 23 | } 24 | 25 | public Long delIcop(Integer id){ 26 | 27 | String sql="delete from icop_test where id=? limit 1"; 28 | return jdbcTemplate.doUpdate(sql,id); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.dao; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | 9 | import org.coody.framework.box.annotation.InitBean; 10 | import org.coody.framework.box.iface.InitFace; 11 | import org.coody.framework.util.JUUIDUtil; 12 | import org.coody.framework.util.StringUtil; 13 | import org.coody.web.domain.UserInfo; 14 | 15 | @InitBean 16 | public class UserDao implements InitFace{ 17 | 18 | private static final Map dataMap=new ConcurrentHashMap(); 19 | 20 | /** 21 | * 保存或更新用户信息 22 | * @param user 23 | */ 24 | public void saveOrUpdateUser(UserInfo user){ 25 | if(StringUtil.isNullOrEmpty(user.getUserId())){ 26 | user.setUserId(JUUIDUtil.createUuid()); 27 | dataMap.put(user.getUserId(), user); 28 | return; 29 | } 30 | dataMap.put(user.getUserId(), user); 31 | } 32 | 33 | /** 34 | * 查询用户列表 35 | */ 36 | public List getUsers(){ 37 | Collection users=dataMap.values(); 38 | return new ArrayList(users); 39 | } 40 | /** 41 | * 查询用户信息 42 | */ 43 | public UserInfo getUserInfo(String userId){ 44 | return dataMap.get(userId); 45 | } 46 | /** 47 | * 删除用户 48 | * @param userId 49 | */ 50 | public void deleteUser(String userId){ 51 | dataMap.remove(userId); 52 | } 53 | 54 | /** 55 | * bean加载时执行 56 | */ 57 | public void init() { 58 | UserInfo user=new UserInfo(); 59 | user.setAge(18); 60 | user.setUserId(JUUIDUtil.createUuid()); 61 | user.setUserName("张三"); 62 | dataMap.put(user.getUserId(), user); 63 | user=new UserInfo(); 64 | user.setAge(19); 65 | user.setUserId(JUUIDUtil.createUuid()); 66 | user.setUserName("李四"); 67 | dataMap.put(user.getUserId(), user); 68 | user=new UserInfo(); 69 | user.setAge(20); 70 | user.setUserId(JUUIDUtil.createUuid()); 71 | user.setUserName("王五"); 72 | dataMap.put(user.getUserId(), user); 73 | user=new UserInfo(); 74 | user.setAge(21); 75 | user.setUserId(JUUIDUtil.createUuid()); 76 | user.setUserName("马六"); 77 | dataMap.put(user.getUserId(), user); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/domain/IcopTest.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.domain; 2 | 3 | import java.util.Date; 4 | 5 | import org.coody.framework.entity.BaseModel; 6 | 7 | @SuppressWarnings("serial") 8 | public class IcopTest extends BaseModel{ 9 | 10 | 11 | private Integer id; 12 | private String name; 13 | private Integer age; 14 | private Date createTime; 15 | private Integer sex; 16 | public Integer getId() { 17 | return id; 18 | } 19 | public void setId(Integer id) { 20 | this.id = id; 21 | } 22 | public String getName() { 23 | return name; 24 | } 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | public Integer getAge() { 29 | return age; 30 | } 31 | public void setAge(Integer age) { 32 | this.age = age; 33 | } 34 | public Date getCreateTime() { 35 | return createTime; 36 | } 37 | public void setCreateTime(Date createTime) { 38 | this.createTime = createTime; 39 | } 40 | public Integer getSex() { 41 | return sex; 42 | } 43 | public void setSex(Integer sex) { 44 | this.sex = sex; 45 | } 46 | 47 | 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/domain/UserInfo.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.domain; 2 | 3 | import org.coody.framework.entity.BaseModel; 4 | 5 | @SuppressWarnings("serial") 6 | public class UserInfo extends BaseModel{ 7 | 8 | private String userId; 9 | 10 | private String userName; 11 | 12 | private Integer age; 13 | 14 | public String getUserId() { 15 | return userId; 16 | } 17 | 18 | public void setUserId(String userId) { 19 | this.userId = userId; 20 | } 21 | 22 | public String getUserName() { 23 | return userName; 24 | } 25 | 26 | public void setUserName(String userName) { 27 | this.userName = userName; 28 | } 29 | 30 | public Integer getAge() { 31 | return age; 32 | } 33 | 34 | public void setAge(Integer age) { 35 | this.age = age; 36 | } 37 | 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/service/IcopService.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.service; 2 | 3 | import java.util.List; 4 | 5 | import org.coody.framework.box.annotation.InitBean; 6 | import org.coody.framework.box.annotation.OutBean; 7 | import org.coody.framework.box.annotation.Transacted; 8 | import org.coody.web.dao.IcopDao; 9 | import org.coody.web.domain.IcopTest; 10 | 11 | @InitBean 12 | public class IcopService { 13 | 14 | @OutBean 15 | IcopDao icopDao; 16 | 17 | public IcopTest getIcop(Integer id){ 18 | return icopDao.getIcop(id); 19 | } 20 | 21 | 22 | public List getIcops(){ 23 | return icopDao.getIcops() 24 | ; 25 | } 26 | @Transacted 27 | public Long delIcop(Integer id){ 28 | Long code= icopDao.delIcop(id); 29 | Integer i=50/0; 30 | System.out.println(i); 31 | return code; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/service/UserService.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.service; 2 | 3 | import java.util.List; 4 | 5 | import org.coody.framework.box.annotation.InitBean; 6 | import org.coody.framework.box.annotation.OutBean; 7 | import org.coody.web.comm.annotation.CacheWipe; 8 | import org.coody.web.comm.annotation.CacheWrite; 9 | import org.coody.web.comm.constant.CacheFinal; 10 | import org.coody.web.dao.UserDao; 11 | import org.coody.web.domain.UserInfo; 12 | 13 | @InitBean 14 | public class UserService { 15 | 16 | @OutBean 17 | UserDao userDao; 18 | 19 | 20 | /** 21 | * 保存或更新用户信息 22 | * @param user 23 | */ 24 | @CacheWipe(key=CacheFinal.USER_INFO,fields="user.userId") 25 | @CacheWipe(key=CacheFinal.USER_LIST) 26 | public void saveOrUpdateUser(UserInfo user){ 27 | userDao.saveOrUpdateUser(user); 28 | } 29 | 30 | /** 31 | * 查询用户列表 32 | */ 33 | @CacheWrite(key=CacheFinal.USER_LIST,validTime=3600) 34 | public List getUsers(){ 35 | return userDao.getUsers(); 36 | } 37 | 38 | /** 39 | * 删除用户 40 | * @param userId 41 | */ 42 | @CacheWipe(key=CacheFinal.USER_INFO,fields="user.userId") 43 | @CacheWipe(key=CacheFinal.USER_LIST) 44 | public void deleteUser(String userId){ 45 | userDao.deleteUser(userId); 46 | } 47 | 48 | /** 49 | * 查询用户信息 50 | */ 51 | @CacheWrite(key=CacheFinal.USER_INFO,fields="userId") 52 | public UserInfo getUserInfo(String userId){ 53 | return userDao.getUserInfo(userId); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/coody/web/servlet/LoadUserList.java: -------------------------------------------------------------------------------- 1 | package org.coody.web.servlet; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServlet; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | import org.coody.framework.box.container.BeanContainer; 12 | import org.coody.web.domain.UserInfo; 13 | import org.coody.web.service.UserService; 14 | 15 | import com.alibaba.fastjson.JSON; 16 | 17 | /** 18 | * 加载用户列表 19 | * 20 | */ 21 | @SuppressWarnings("serial") 22 | public class LoadUserList extends HttpServlet { 23 | 24 | public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 25 | service(request, response); 26 | } 27 | 28 | public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 29 | service(request, response); 30 | } 31 | 32 | public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33 | 34 | request.setCharacterEncoding("UTF-8"); 35 | response.setCharacterEncoding("UTF-8"); 36 | // 获取Bean 37 | UserService userService=BeanContainer.getBean(UserService.class); 38 | List userlist=userService.getUsers(); 39 | response.getWriter().print(JSON.toJSONString(userlist)); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/resources/config/c3p0.properties: -------------------------------------------------------------------------------- 1 | jdbc.driverClass=com.mysql.jdbc.Driver 2 | jdbc.url=jdbc\:mysql\://coody.org\:52014/xss_test?useUnicode\=true&characterEncoding\=utf-8 3 | jdbc.user=coody 4 | jdbc.password=Coody520\! -------------------------------------------------------------------------------- /src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> 2 | <% 3 | String path = request.getContextPath(); 4 | String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 | %> 6 | 7 | 8 | 9 | 10 | 11 | 12 | My JSP 'index.jsp' starting page 13 | 14 | 15 | 16 | 17 | 18 | 21 | 22 | 23 | 24 | 25 | This is my JSP page.
26 | 27 | 28 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/lib/c3p0-0.9.1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coodyer/coody-icop/77e64f5fb4a2f0b434b081273cbc2b5193b0beeb/src/main/webapp/WEB-INF/lib/c3p0-0.9.1.2.jar -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/lib/cglib-nodep-3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coodyer/coody-icop/77e64f5fb4a2f0b434b081273cbc2b5193b0beeb/src/main/webapp/WEB-INF/lib/cglib-nodep-3.1.jar -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/lib/fastjson-1.2.31.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coodyer/coody-icop/77e64f5fb4a2f0b434b081273cbc2b5193b0beeb/src/main/webapp/WEB-INF/lib/fastjson-1.2.31.jar -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/lib/log4j-1.2.17.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coodyer/coody-icop/77e64f5fb4a2f0b434b081273cbc2b5193b0beeb/src/main/webapp/WEB-INF/lib/log4j-1.2.17.jar -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.13.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coodyer/coody-icop/77e64f5fb4a2f0b434b081273cbc2b5193b0beeb/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.13.jar -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | webAppRootKey 8 | coody 9 | 10 | 11 | 12 | 13 | scanPacket 14 | org.coody.web 15 | 16 | 17 | 18 | org.coody.framework.box.init.BoxServletListen 19 | 20 | 21 | 22 | DispatServlet 23 | org.coody.framework.box.mvc.DispatServlet 24 | 25 | viewPath 26 | /WEB-INF/jsp 27 | 28 | 29 | 30 | 31 | DispatServlet 32 | *.do 33 | 34 | 35 | 36 | 37 | LoadUserList 38 | org.coody.web.servlet.LoadUserList 39 | 40 | 41 | 42 | LoadUserList 43 | /servlet/LoadUserList 44 | 45 | -------------------------------------------------------------------------------- /src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> 2 | <% 3 | String path = request.getContextPath(); 4 | String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 | %> 6 | 7 | 8 | 9 | 10 | 11 | 12 | My JSP 'index.jsp' starting page 13 | 14 | 15 | 16 | 17 | 18 | 21 | 22 | 23 | 24 | This is my JSP page.
25 | 26 | 27 | --------------------------------------------------------------------------------