注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

和申的个人主页

专注于java开发,1985wanggang

 
 
 

日志

 
 

简单的页面表单值到 dto的自动赋值  

2012-02-15 20:46:34|  分类: Java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;

/**
* 通过表达式访问对象 eg:filedObj.filedObj2.filedName
*
* @author wanggang
*
*/
public class ParameterSetHelper {

private static final Logger log = LoggerFactory.getLogger(ParameterSetHelper.class);
// Allowed names of parameters
private static String acceptedParamNames = "\\w+((\\.\\w+)|(\\[\\d+\\])|(\\(\\d+\\))|(\\['\\w+'\\])|(\\('\\w+'\\)))*";
private static Pattern acceptedPattern = Pattern.compile(acceptedParamNames);
protected static boolean isAccepted(String paramName) {
return acceptedPattern.matcher(paramName).matches();
}
/**
* 设置对象中的参数至对象(obj)中
* @param obj
* @param request
*/
public static void setParameter(Object obj,HttpServletRequest request,boolean isIgnoreEmptyValue){


@SuppressWarnings("unchecked")
Map<String, Object> params = request.getParameterMap();

for(Map.Entry<String, Object>entry :params.entrySet()){
if( isAccepted(entry.getKey())){
try {
Object value= entry.getValue();
if(value instanceof Object[] && ((Object[])value).length >= 1){
Object v = ((Object[])value)[0];
if(isIgnoreEmptyValue){
if(v == null || (v instanceof String && v.toString().trim().equals(""))){
continue;
}
}
ParameterSetHelper.setValue(obj, entry.getKey(), v);
}else{
if(isIgnoreEmptyValue){
if(value == null || (value instanceof String && value.toString().trim().equals(""))){
continue;
}
}
ParameterSetHelper.setValue(obj, entry.getKey(), value);
}

} catch (Exception e) {
if(log.isDebugEnabled()){
log.debug("setParameter error:",e);
}

}
}

}
}
/**
*
* 设置表达式中对象属性的值
*
* @param obj 待设置值的对象
* @param expression filedObj.filedObj2.filedName
* @param value
* @throws IllegalArgumentException
* @throws SecurityException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws InstantiationException
*/
public static void setValue(Object obj,String expression,Object value) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException{
String[] aa = expression.split("\\.");

for(int i = 0 ;i< aa.length -1;i++){
String a = aa[i];
Object o = getObjectGetMethod(obj, a);

if(o == null){
o = setObjectSetMethodDefault(obj, a);
}

obj = o;

}

int index = aa.length -1;
setObjectSetMethod(obj, value,aa[index]);
}

/**
* 使用表达式访问对象属性,返回指定表达式的属性的值
*
* @param obj 需要访问属性的对象名称
* @param expression 访问对象(obj)属性的表达式.eg:filedObj.filedObj2.filedName
* @return 指定表达式的属性的值
* @throws IllegalArgumentException
* @throws SecurityException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws InstantiationException
*/
public static Object getValue(Object obj,String expression) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException{
String[] aa = expression.split("\\.");

for(int i = 0 ;i< aa.length -1;i++){
String a = aa[i];
obj = getObjectGetMethod(obj, a);
if(obj== null)
return null;

}
int index = aa.length -1;
if(obj != null){
return getObjectGetMethod(obj, aa[index]);
} else{
return null;
}
}

private static Object setObjectSetMethodDefault(Object obj,String filedName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException{
Class<?> clazz = obj.getClass();
Method[] method = clazz.getMethods();
String methodName = "set" + firstLetterUpperCase(filedName);

for(Method m:method){

if(methodName.equals(m.getName())){
Class<?>[] parameters = m.getParameterTypes();
if(parameters.length == 1){
Class<?> argsClazz = parameters[0];
Object args = argsClazz.newInstance();
m.invoke(obj, args);
return args;
}
}
}
return new RuntimeException("no such method");
}

private static void setObjectSetMethod(Object obj,Object args,String filedName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Class<?> clazz = obj.getClass();
Method[] method = clazz.getMethods();
String methodName = "set" + firstLetterUpperCase(filedName);

for(Method m:method){

if(methodName.equals(m.getName())){
Class<?>[] parameters = m.getParameterTypes();
if(parameters.length == 1){
m.invoke(obj, args);
}
}
}
}


private static Object getObjectGetMethod(Object obj,String filedName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException{
Class<?> clazz = obj.getClass();
Method m = clazz.getMethod("get" + firstLetterUpperCase(filedName));

return m.invoke(obj);
}
private static String firstLetterUpperCase(String str){

if(str != null && str.length()>0){
StringBuilder sb = new StringBuilder(str);
String firstLetter = sb.substring(0, 1);
firstLetter = firstLetter.toUpperCase();
sb.replace(0, 1, firstLetter);
return sb.toString();
}
return str;
}
/* private static String firstLetterLowerCase(String str){

if(str != null && str.length()>0){
StringBuilder sb = new StringBuilder(str);
String firstLetter = sb.substring(0, 1);
firstLetter = firstLetter.toLowerCase();
sb.replace(0, 1, firstLetter);
return sb.toString();
}
return str;
}*/


}



<form name="complaintSaveProofTag" method="post" class="nospace">
<input type="text" name="contract.companyName" value=""/>

</form>

public class SomeDTO{


private Contract contract;

public Contract getContract() {
return contract;
}

public void setContract(Contract contract) {
this.contract = contract;
}

/***
*
*
* @author wanggang
*
*/
public static class Contract{

private String companyName;

private String url;

private String phone;

private String brand;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}

}

}

//web中调用的代码

SomeDTO dto= new SomeDTO();
ParameterSetHelper.setParameter(dto,request,true);//调用自动赋值方法

  评论这张
 
阅读(1242)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016