struts2 模型驱动要注意的一个问题

本贴最后更新于 3344 天前,其中的信息可能已经时移世异

先来说一下模型驱动,在struts2的默认拦截器栈struts-default包中有一个 ModelDriverInterceptor拦截器,如果有我们的action实现ModerDriver接口,即可实现模型驱动。action如下代码

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>,SessionAware,ServletRequestAware{

/** model 的支持 */
protected T model;

public void setModel(T model) {
	this.model = model;
}

public BaseAction() {
	ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
	Class&lt;T&gt; clazz=(Class&lt;T&gt;) (genericSuperclass.getActualTypeArguments()[0]);
	try {
		model=clazz.newInstance();
		log.info(&quot;BaseAction model:&quot;+model);
	} catch (Exception e) {
		//throw new RuntimeException(e);
	}
	
	
}

@Override
public T getModel() {
	return model;
}<br />//部分代码省略<br />}</pre>

从代码上看,每次都new了一个对象, 如果我们用 XXXService.update(model)的话,会将空值、默认值也会更新进去,显示这不是我们想要的。
,可以采用这一种方式:先通过id查找到这个对象,然后将model的非空属性赋值给这个对象,最后更新对象。

public String edit() throws Exception {        
        log.info("修改用户:"+model);
        User u=userService.getById(model.getId());        
        if (StrUtils.notNull(model.getPassword())) {
            model.setPassword(DigestUtils.md5Hex(model.getPassword()));
        }
        BeanUtils.copyNotNullProperties(model, u);
        userService.update(u);

//省略部分代码...

}

最后上一个BeanUtils工具类:

package core.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

/**

  • 扩展 spring 的 BeanUtils,增加拷贝属性排除 null 值的功能(注:String 为 null 不考虑)
  • 扩展 Apache Commons BeanUtils, 提供一些反射方面缺失功能的封装.
  • @author shollin

/
public class BeanUtils extends org.springframework.beans.BeanUtils {
/
* logger. */
private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);

 /** getter prefix length. */

public static final int LENGTH_GETTER_PREFIX = "get".length();

/** 保护的构造方法. */
protected BeanUtils() {
}

public static void copyNotNullProperties(Object source, Object target, String[] ignoreProperties) throws BeansException {
	copyNotNullProperties(source, target, null, ignoreProperties);
}

public static void copyNotNullProperties(Object source, Object target, Class&lt;?&gt; editable) throws BeansException {
	copyNotNullProperties(source, target, editable, null);
}

public static void copyNotNullProperties(Object source, Object target) throws BeansException {
	copyNotNullProperties(source, target, null, null);
}

private static void copyNotNullProperties(Object source, Object target, Class&lt;?&gt; editable, String[] ignoreProperties) throws BeansException {

	Assert.notNull(source, &quot;Source must not be null&quot;);
	Assert.notNull(target, &quot;Target must not be null&quot;);

	Class&lt;?&gt; actualEditable = target.getClass();
	if (editable != null) {
		if (!editable.isInstance(target)) {
			throw new IllegalArgumentException(&quot;Target class [&quot; + target.getClass().getName() + &quot;] not assignable to Editable class [&quot; + editable.getName() + &quot;]&quot;);
		}
		actualEditable = editable;
	}
	PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
	List&lt;String&gt; ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

	for (PropertyDescriptor targetPd : targetPds) {
		if (targetPd.getWriteMethod() != null &amp;&amp; (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
			PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
			if (sourcePd != null &amp;&amp; sourcePd.getReadMethod() != null) {
				try {
					Method readMethod = sourcePd.getReadMethod();
					if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
						readMethod.setAccessible(true);
					}
					Object value = readMethod.invoke(source);
					if (value != null || readMethod.getReturnType().getName().equals(&quot;java.lang.String&quot;)) {// 这里判断以下value是否为空,当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等,如果是String类型,则不需要验证是否为空
						boolean isEmpty = false;
						if (value instanceof Set) {
							Set s = (Set) value;
							if (s == null || s.isEmpty()) {
								isEmpty = true;
							}
						} else if (value instanceof Map) {
							Map m = (Map) value;
							if (m == null || m.isEmpty()) {
								isEmpty = true;
							}
						} else if (value instanceof List) {
							List l = (List) value;
							if (l == null || l.size() &lt; 1) {
								isEmpty = true;
							}
						} else if (value instanceof Collection) {
							Collection c = (Collection) value;
							if (c == null || c.size() &lt; 1) {
								isEmpty = true;
							}
						}
						if (!isEmpty) {
							Method writeMethod = targetPd.getWriteMethod();
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						}
					}
				} catch (Throwable ex) {
					throw new FatalBeanException(&quot;Could not copy properties from source to target&quot;, ex);
				}
			}
		}
	}
}
/**
 * 循环向上转型,获取对象的DeclaredField.
 * 
 * @param object
 *            对象实例
 * @param propertyName
 *            属性名
 * @return 返回对应的Field
 * @throws NoSuchFieldException
 *             如果没有该Field时抛出
 */
public static Field getDeclaredField(Object object, String propertyName)
        throws NoSuchFieldException {
    Assert.notNull(object);
    Assert.hasText(propertyName);

    return getDeclaredField(object.getClass(), propertyName);
}

/**
 * 循环向上转型,获取对象的DeclaredField.
 * 
 * @param clazz
 *            类型
 * @param propertyName
 *            属性名
 * @return 返回对应的Field
 * @throws NoSuchFieldException
 *             如果没有该Field时抛出.
 */
public static Field getDeclaredField(Class clazz, String propertyName)
        throws NoSuchFieldException {
    Assert.notNull(clazz);
    Assert.hasText(propertyName);

    for (Class superClass = clazz; superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            return superClass.getDeclaredField(propertyName);
        } catch (NoSuchFieldException ex) {
            // Field不在当前类定义,继续向上转型
            logger.debug(ex.getMessage(), ex);
        }
    }

    throw new NoSuchFieldException(&quot;No such field: &quot; + clazz.getName()
            + '.' + propertyName);
}

/**
 * 暴力获取对象变量值,忽略private,protected修饰符的限制.
 * 
 * @param object
 *            对象实例
 * @param propertyName
 *            属性名
 * @return 强制获得属性值
 * @throws NoSuchFieldException
 *             如果没有该Field时抛出.
 */
public static Object forceGetProperty(Object object, String propertyName)
        throws NoSuchFieldException, IllegalAccessException {
    return getFieldValue(object, propertyName, true);
}

public static Object safeGetFieldValue(Object object, String fieldName) {
    return safeGetFieldValue(object, fieldName, true);
}

public static Object safeGetFieldValue(Object object, String fieldName,
        boolean targetAccessible) {
    try {
        return getFieldValue(object, fieldName, targetAccessible);
    } catch (NoSuchFieldException ex) {
        logger.warn(&quot;&quot;, ex);
    } catch (IllegalAccessException ex) {
        logger.warn(&quot;&quot;, ex);
    }

    return null;
}

public static Object getFieldValue(Object object, String fieldName)
        throws NoSuchFieldException, IllegalAccessException {
    return getFieldValue(object, fieldName, false);
}

public static Object getFieldValue(Object object, String fieldName,
        boolean targetAccessible) throws NoSuchFieldException,
        IllegalAccessException {
    Assert.notNull(object);
    Assert.hasText(fieldName);

    Field field = getDeclaredField(object, fieldName);

    boolean accessible = field.isAccessible();
    field.setAccessible(targetAccessible);

    Object result = field.get(object);

    field.setAccessible(accessible);

    return result;
}

/**
 * 暴力设置对象变量值,忽略private,protected修饰符的限制.
 * 
 * @param object
 *            对象实例
 * @param propertyName
 *            属性名
 * @param newValue
 *            赋予的属性值
 * @throws NoSuchFieldException
 *             如果没有该Field时抛出.
 */
public static void forceSetProperty(Object object, String propertyName,
        Object newValue) throws NoSuchFieldException,
        IllegalAccessException {
    setFieldValue(object, propertyName, newValue, true);
}

public static void safeSetFieldValue(Object object, String fieldName,
        Object newValue) {
    safeSetFieldValue(object, fieldName, newValue, true);
}

public static void safeSetFieldValue(Object object, String fieldName,
        Object newValue, boolean targetAccessible) {
    try {
        setFieldValue(object, fieldName, newValue, targetAccessible);
    } catch (NoSuchFieldException ex) {
        logger.warn(&quot;&quot;, ex);
    } catch (IllegalAccessException ex) {
        logger.warn(&quot;&quot;, ex);
    }
}

public static void setFieldValue(Object object, String propertyName,
        Object newValue, boolean targetAccessible)
        throws NoSuchFieldException, IllegalAccessException {
    Assert.notNull(object);
    Assert.hasText(propertyName);

    Field field = getDeclaredField(object, propertyName);

    boolean accessible = field.isAccessible();
    field.setAccessible(targetAccessible);

    field.set(object, newValue);

    field.setAccessible(accessible);
}

/**
 * 暴力调用对象函数,忽略private,protected修饰符的限制.
 * 
 * @param object
 *            对象实例
 * @param methodName
 *            方法名
 * @param params
 *            方法参数
 * @return Object 方法调用返回的结果对象
 * @throws NoSuchMethodException
 *             如果没有该Method时抛出.
 */
public static Object invokePrivateMethod(Object object, String methodName,
        Object... params) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {
    return invokeMethod(object, methodName, true, params);
}

public static Object safeInvokeMethod(Object object, Method method,
        Object... params) {
    try {
        return method.invoke(object, params);
    } catch (IllegalAccessException ex) {
        logger.warn(&quot;&quot;, ex);
    } catch (InvocationTargetException ex) {
        logger.warn(&quot;&quot;, ex);
    }

    return null;
}

public static Object safeInvokeMethod(Object object, String methodName,
        Object... params) {
    try {
        return invokeMethod(object, methodName, params);
    } catch (NoSuchMethodException ex) {
        logger.warn(&quot;&quot;, ex);
    } catch (IllegalAccessException ex) {
        logger.warn(&quot;&quot;, ex);
    } catch (InvocationTargetException ex) {
        logger.warn(&quot;&quot;, ex);
    }

    return null;
}

public static Object invokeMethod(Object object, String methodName,
        Object... params) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {
    return invokeMethod(object, methodName, false, params);
}

public static Object invokeMethod(Object object, String methodName,
        boolean targetAccessible, Object... params)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    Assert.notNull(object);
    Assert.hasText(methodName);

    Class[] types = new Class[params.length];

    for (int i = 0; i &lt; params.length; i++) {
        types[i] = params[i].getClass();
    }

    Class clazz = object.getClass();
    Method method = null;

    for (Class superClass = clazz; superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            method = superClass.getDeclaredMethod(methodName, types);

            break;
        } catch (NoSuchMethodException ex) {
            // 方法不在当前类定义,继续向上转型
            logger.debug(ex.getMessage(), ex);
        }
    }

    if (method == null) {
        throw new NoSuchMethodException(&quot;No Such Method : &quot;
                + clazz.getSimpleName() + &quot;.&quot; + methodName
                + Arrays.asList(types));
    }

    boolean accessible = method.isAccessible();
    method.setAccessible(targetAccessible);

    Object result = method.invoke(object, params);

    method.setAccessible(accessible);

    return result;
}

/**
 * 按Field的类型取得Field列表.
 * 
 * @param object
 *            对象实例
 * @param type
 *            类型
 * @return 属性对象列表
 */
public static List&lt;Field&gt; getFieldsByType(Object object, Class type) {
    List&lt;Field&gt; list = new ArrayList&lt;Field&gt;();
    Field[] fields = object.getClass().getDeclaredFields();

    for (Field field : fields) {
        if (field.getType().isAssignableFrom(type)) {
            list.add(field);
        }
    }

    return list;
}

/**
 * 按FieldName获得Field的类型.
 * 
 * @param type
 *            类型
 * @param name
 *            属性名
 * @return 属性的类型
 * @throws NoSuchFieldException
 *             指定属性不存在时,抛出异常
 */
public static Class getPropertyType(Class type, String name)
        throws NoSuchFieldException {
    return getDeclaredField(type, name).getType();
}

/**
 * 获得field的getter函数名称.
 * 
 * @param type
 *            类型
 * @param fieldName
 *            属性名
 * @return getter方法名
 * @throws NoSuchFieldException
 *             field不存在时抛出异常
 * 
 * @todo: 使用reflectUtils里的方法更合适,这里的实现方式,必须先有field才能有method,逻辑上有问题 实际上,即使没有field也可以单独有method。
 */
public static String getGetterName(Class type, String fieldName)
        throws NoSuchFieldException {
    Assert.notNull(type, &quot;Type required&quot;);
    Assert.hasText(fieldName, &quot;FieldName required&quot;);

    Class fieldType = getDeclaredField(type, fieldName).getType();

    if ((fieldType == boolean.class) || (fieldType == Boolean.class)) {
        return &quot;is&quot; + StrUtils.capitalize(fieldName);
    } else {
        return &quot;get&quot; + StrUtils.capitalize(fieldName);
    }
}

/**
 * 获得field的getter函数,如果找不到该方法,返回null.
 * 
 * @param type
 *            类型
 * @param fieldName
 *            属性名
 * @return getter方法对象
 */
public static Method getGetterMethod(Class type, String fieldName) {
    try {
        return type.getMethod(getGetterName(type, fieldName));
    } catch (NoSuchMethodException ex) {
        logger.error(ex.getMessage(), ex);
    } catch (NoSuchFieldException ex) {
        logger.error(ex.getMessage(), ex);
    }

    return null;
}

public static String getFieldName(String methodName) {
    String fieldName = methodName.substring(LENGTH_GETTER_PREFIX);

    return fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
}

}

 

 

  • Struts2
    13 引用 • 14 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • IDEA

    IDEA 全称 IntelliJ IDEA,是一款 Java 语言开发的集成环境,在业界被公认为最好的 Java 开发工具之一。IDEA 是 JetBrains 公司的产品,这家公司总部位于捷克共和国的首都布拉格,开发人员以严谨著称的东欧程序员为主。

    180 引用 • 400 回帖
  • Typecho

    Typecho 是一款博客程序,它在 GPLv2 许可证下发行,基于 PHP 构建,可以运行在各种平台上,支持多种数据库(MySQL、PostgreSQL、SQLite)。

    12 引用 • 60 回帖 • 462 关注
  • 禅道

    禅道是一款国产的开源项目管理软件,她的核心管理思想基于敏捷方法 scrum,内置了产品管理和项目管理,同时又根据国内研发现状补充了测试管理、计划管理、发布管理、文档管理、事务管理等功能,在一个软件中就可以将软件研发中的需求、任务、bug、用例、计划、发布等要素有序的跟踪管理起来,完整地覆盖了项目管理的核心流程。

    5 引用 • 15 回帖 • 220 关注
  • FFmpeg

    FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

    22 引用 • 31 回帖 • 3 关注
  • 阿里云

    阿里云是阿里巴巴集团旗下公司,是全球领先的云计算及人工智能科技公司。提供云服务器、云数据库、云安全等云计算服务,以及大数据、人工智能服务、精准定制基于场景的行业解决方案。

    89 引用 • 345 回帖
  • OkHttp

    OkHttp 是一款 HTTP & HTTP/2 客户端库,专为 Android 和 Java 应用打造。

    16 引用 • 6 回帖 • 53 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    941 引用 • 1458 回帖 • 154 关注
  • GAE

    Google App Engine(GAE)是 Google 管理的数据中心中用于 WEB 应用程序的开发和托管的平台。2008 年 4 月 发布第一个测试版本。目前支持 Python、Java 和 Go 开发部署。全球已有数十万的开发者在其上开发了众多的应用。

    14 引用 • 42 回帖 • 687 关注
  • Google

    Google(Google Inc.,NASDAQ:GOOG)是一家美国上市公司(公有股份公司),于 1998 年 9 月 7 日以私有股份公司的形式创立,设计并管理一个互联网搜索引擎。Google 公司的总部称作“Googleplex”,它位于加利福尼亚山景城。Google 目前被公认为是全球规模最大的搜索引擎,它提供了简单易用的免费服务。不作恶(Don't be evil)是谷歌公司的一项非正式的公司口号。

    49 引用 • 192 回帖
  • wolai

    我来 wolai:不仅仅是未来的云端笔记!

    1 引用 • 11 回帖 • 1 关注
  • 以太坊

    以太坊(Ethereum)并不是一个机构,而是一款能够在区块链上实现智能合约、开源的底层系统。以太坊是一个平台和一种编程语言 Solidity,使开发人员能够建立和发布下一代去中心化应用。 以太坊可以用来编程、分散、担保和交易任何事物:投票、域名、金融交易所、众筹、公司管理、合同和知识产权等等。

    34 引用 • 367 回帖 • 3 关注
  • 外包

    有空闲时间是接外包好呢还是学习好呢?

    26 引用 • 232 回帖 • 6 关注
  • 反馈

    Communication channel for makers and users.

    123 引用 • 906 回帖 • 193 关注
  • PostgreSQL

    PostgreSQL 是一款功能强大的企业级数据库系统,在 BSD 开源许可证下发布。

    22 引用 • 22 回帖
  • etcd

    etcd 是一个分布式、高可用的 key-value 数据存储,专门用于在分布式系统中保存关键数据。

    5 引用 • 26 回帖 • 495 关注
  • 音乐

    你听到信仰的声音了么?

    59 引用 • 509 回帖
  • 强迫症

    强迫症(OCD)属于焦虑障碍的一种类型,是一组以强迫思维和强迫行为为主要临床表现的神经精神疾病,其特点为有意识的强迫和反强迫并存,一些毫无意义、甚至违背自己意愿的想法或冲动反反复复侵入患者的日常生活。

    15 引用 • 161 回帖 • 2 关注
  • 区块链

    区块链是分布式数据存储、点对点传输、共识机制、加密算法等计算机技术的新型应用模式。所谓共识机制是区块链系统中实现不同节点之间建立信任、获取权益的数学算法 。

    91 引用 • 751 回帖 • 1 关注
  • QQ

    1999 年 2 月腾讯正式推出“腾讯 QQ”,在线用户由 1999 年的 2 人(马化腾和张志东)到现在已经发展到上亿用户了,在线人数超过一亿,是目前使用最广泛的聊天软件之一。

    45 引用 • 557 回帖 • 218 关注
  • Lute

    Lute 是一款结构化的 Markdown 引擎,支持 Go 和 JavaScript。

    25 引用 • 191 回帖 • 23 关注
  • 工具

    子曰:“工欲善其事,必先利其器。”

    276 引用 • 685 回帖
  • golang

    Go 语言是 Google 推出的一种全新的编程语言,可以在不损失应用程序性能的情况下降低代码的复杂性。谷歌首席软件工程师罗布派克(Rob Pike)说:我们之所以开发 Go,是因为过去 10 多年间软件开发的难度令人沮丧。Go 是谷歌 2009 发布的第二款编程语言。

    492 引用 • 1383 回帖 • 370 关注
  • H2

    H2 是一个开源的嵌入式数据库引擎,采用 Java 语言编写,不受平台的限制,同时 H2 提供了一个十分方便的 web 控制台用于操作和管理数据库内容。H2 还提供兼容模式,可以兼容一些主流的数据库,因此采用 H2 作为开发期的数据库非常方便。

    11 引用 • 54 回帖 • 641 关注
  • Markdown

    Markdown 是一种轻量级标记语言,用户可使用纯文本编辑器来排版文档,最终通过 Markdown 引擎将文档转换为所需格式(比如 HTML、PDF 等)。

    164 引用 • 1456 回帖
  • Solidity

    Solidity 是一种智能合约高级语言,运行在 [以太坊] 虚拟机(EVM)之上。它的语法接近于 JavaScript,是一种面向对象的语言。

    3 引用 • 18 回帖 • 349 关注
  • Sublime

    Sublime Text 是一款可以用来写代码、写文章的文本编辑器。支持代码高亮、自动完成,还支持通过插件进行扩展。

    10 引用 • 5 回帖
  • OpenShift

    红帽提供的 PaaS 云,支持多种编程语言,为开发人员提供了更为灵活的框架、存储选择。

    14 引用 • 20 回帖 • 602 关注