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

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

先来说一下模型驱动,在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 关注

相关帖子

欢迎来到这里!

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

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

推荐标签 标签

  • 智能合约

    智能合约(Smart contract)是一种旨在以信息化方式传播、验证或执行合同的计算机协议。智能合约允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。智能合约概念于 1994 年由 Nick Szabo 首次提出。

    1 引用 • 11 回帖 • 8 关注
  • 招聘

    哪里都缺人,哪里都不缺人。

    189 引用 • 1056 回帖
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    69 引用 • 190 回帖 • 475 关注
  • IBM

    IBM(国际商业机器公司)或万国商业机器公司,简称 IBM(International Business Machines Corporation),总公司在纽约州阿蒙克市。1911 年托马斯·沃森创立于美国,是全球最大的信息技术和业务解决方案公司,拥有全球雇员 30 多万人,业务遍及 160 多个国家和地区。

    16 引用 • 53 回帖 • 131 关注
  • 阿里云

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

    89 引用 • 345 回帖 • 2 关注
  • IDEA

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

    180 引用 • 400 回帖 • 1 关注
  • JWT

    JWT(JSON Web Token)是一种用于双方之间传递信息的简洁的、安全的表述性声明规范。JWT 作为一个开放的标准(RFC 7519),定义了一种简洁的,自包含的方法用于通信双方之间以 JSON 的形式安全的传递信息。

    20 引用 • 15 回帖 • 20 关注
  • 域名

    域名(Domain Name),简称域名、网域,是由一串用点分隔的名字组成的 Internet 上某一台计算机或计算机组的名称,用于在数据传输时标识计算机的电子方位(有时也指地理位置)。

    43 引用 • 208 回帖 • 1 关注
  • Solo

    Solo 是一款小而美的开源博客系统,专为程序员设计。Solo 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    1427 引用 • 10046 回帖 • 472 关注
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    186 引用 • 471 回帖 • 3 关注
  • Chrome

    Chrome 又称 Google 浏览器,是一个由谷歌公司开发的网页浏览器。该浏览器是基于其他开源软件所编写,包括 WebKit,目标是提升稳定性、速度和安全性,并创造出简单且有效率的使用者界面。

    62 引用 • 289 回帖
  • AngularJS

    AngularJS 诞生于 2009 年,由 Misko Hevery 等人创建,后为 Google 所收购。是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入等。2.0 版本后已经改名为 Angular。

    12 引用 • 50 回帖 • 442 关注
  • 支付宝

    支付宝是全球领先的独立第三方支付平台,致力于为广大用户提供安全快速的电子支付/网上支付/安全支付/手机支付体验,及转账收款/水电煤缴费/信用卡还款/AA 收款等生活服务应用。

    29 引用 • 347 回帖 • 2 关注
  • SQLite

    SQLite 是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是全世界使用最为广泛的数据库引擎。

    4 引用 • 7 回帖
  • Redis

    Redis 是一个开源的使用 ANSI C 语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库,并提供多种语言的 API。从 2010 年 3 月 15 日起,Redis 的开发工作由 VMware 主持。从 2013 年 5 月开始,Redis 的开发由 Pivotal 赞助。

    284 引用 • 248 回帖 • 124 关注
  • Log4j

    Log4j 是 Apache 开源的一款使用广泛的 Java 日志组件。

    20 引用 • 18 回帖 • 23 关注
  • 钉钉

    钉钉,专为中国企业打造的免费沟通协同多端平台, 阿里巴巴出品。

    15 引用 • 67 回帖 • 348 关注
  • DNSPod

    DNSPod 建立于 2006 年 3 月份,是一款免费智能 DNS 产品。 DNSPod 可以为同时有电信、网通、教育网服务器的网站提供智能的解析,让电信用户访问电信的服务器,网通的用户访问网通的服务器,教育网的用户访问教育网的服务器,达到互联互通的效果。

    6 引用 • 26 回帖 • 529 关注
  • Kotlin

    Kotlin 是一种在 Java 虚拟机上运行的静态类型编程语言,由 JetBrains 设计开发并开源。Kotlin 可以编译成 Java 字节码,也可以编译成 JavaScript,方便在没有 JVM 的设备上运行。在 Google I/O 2017 中,Google 宣布 Kotlin 成为 Android 官方开发语言。

    19 引用 • 33 回帖 • 51 关注
  • OpenResty

    OpenResty 是一个基于 NGINX 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

    17 引用 • 40 关注
  • ngrok

    ngrok 是一个反向代理,通过在公共的端点和本地运行的 Web 服务器之间建立一个安全的通道。

    7 引用 • 63 回帖 • 613 关注
  • 程序员

    程序员是从事程序开发、程序维护的专业人员。

    544 引用 • 3531 回帖
  • Hibernate

    Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,使得 Java 程序员可以随心所欲的使用对象编程思维来操纵数据库。

    39 引用 • 103 回帖 • 702 关注
  • Latke

    Latke 是一款以 JSON 为主的 Java Web 框架。

    70 引用 • 533 回帖 • 735 关注
  • 国际化

    i18n(其来源是英文单词 internationalization 的首末字符 i 和 n,18 为中间的字符数)是“国际化”的简称。对程序来说,国际化是指在不修改代码的情况下,能根据不同语言及地区显示相应的界面。

    7 引用 • 26 回帖
  • 安全

    安全永远都不是一个小问题。

    191 引用 • 813 回帖 • 1 关注
  • Lute

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

    25 引用 • 191 回帖 • 20 关注