繁体   English   中英

有什么方法可以配置 Struts 来绑定 null 而不是空字符串?

[英]Is there any way to configure Struts to bind null instead of empty String?

当用户决定将表单中的字段留空时,Apache Struts 会将空String绑定为ActionForm中属性的值。 有什么方法可以全局修改行为并选择null而不是空String

我知道 Spring MVC 的功能完全相同,但也有StringTrimmerEditor可以注册为属性编辑器,以将字符串修剪为null

一种可能的解决方案 - 允许所有字符串字段的单个转换入口点 - 将注册一个自定义转换器,但不是使用 Struts 而是使用BeanUtils

为了将请求参数映射到表单属性,Struts 使用了 RequestUtils class 的填充方法 这个 class 反过来使用BeanUtils实现来完成它的工作。

一个简单的流程类似于 Struts 的RequestUtils > BeanUtils > BeanUtilsBean > ConvertUtils > ConvertUtilsBean > Converter

有趣的是,还有一个StringConverter可以将 String 转换为... aaaaaa ... String!

ConvertUtils class 有一个注册方法,您可以使用它来注册转换器,覆盖现有的。 这意味着您可以自己编写自定义字符串转换器,它为空字符串返回 null,然后您可以等待您的 Struts 应用程序完全加载,这样您就不会感到意外(即确保您的转换器是最后一次注册为String类型的转换器)。

应用程序加载后,您介入并用您自己的实现覆盖默认的字符串转换器。 例如,您可以使用ServletContextListener并在contextInitialized方法中调用ConvertUtils.register(...)

然后你在web.xml中配置监听器,你应该对 go 很好

在 web.xml 使用下面的代码

<init-param>
      <param-name>convertNull</param-name>
      <param-value>true</param-value>
</init-param>

I think you might as well use your own implementation of the BeanUtils, overriding the class org.apache.commons.beanutils.converters.AbstractConverter and org.apache.commons.beanutils.converters.StringConverter

Cf http://struts.apache.org/development/1.x/userGuide/configuration.html for convertNull;-)

convertNull - 填充 forms 时强制模拟版本 1.0 行为。 If set to "true", the numeric Java wrapper class types (like java.lang.Integer ) will default to null (rather than 0). (从 1.1 版开始)[假]

这是一个有点老的问题,但我通过实施另一个解决方案解决了这个问题(我认为以更简单的方式)。

我实现了一个TypeConverter将空字符串转换为 null。 需要两个文件:

转换器。

public class StringEmptyToNullConverter implements TypeConverter {

    private static final Logger log = LoggerFactory.getLogger(StringEmptyToNullConverter.class);

    @Override
    public Object convertValue(Map arg0, Object arg1, Member member, String arg3, Object obj, Class arg5) {
        String[] value = (String[]) obj;
        if (value == null || value[0] == null || value[0].isEmpty()) {
            logDebug("is null or empty: return null");
            return null;
        }
        logDebug("not null and not empty: return '{}'", value[0]);
        return value[0];
    }

    private void logDebug(String msg, Object... obj) {
        if (log.isDebugEnabled()) {
            log.debug(msg, obj);
        }
    }
}

以及名为xwork-conversion.properties的寄存器。 你必须把这个文件放在你的 java 路径中。

# syntax: <type> = <converterClassName>
java.lang.String = StringEmptyToNullConverter

请参阅 struts 转换器文档

Struts 2 通过拦截器为此提供了一个很好的机制,我认为这比使用BeanUtils更安全、更容易。 这是我使用的代码,基于Cimbali 的博客,但经过编辑以在 Java 7 中编译(原件来自 2009 年):

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

public class RemoveEmptyParametersInterceptor implements Interceptor {

public RemoveEmptyParametersInterceptor() {
    super();
}

/**
 * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
 */
public void destroy() {
    // Nothing to do.
}

/**
 * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
 */
public void init() {
    // Nothing to do.
}


public String intercept(final ActionInvocation invocation) throws Exception   {
   final String result;

    final ActionContext actionContext = invocation.getInvocationContext();
    final Map<String, Object> parameters = actionContext.getParameters();

    if (parameters == null) {
        // Nothing to do.
    } else {
        final Collection<String> parametersToRemove = new ArrayList<String>();

        for (final Map.Entry entry : parameters.entrySet()) {
            final Object object = entry.getValue();
            if (object instanceof String) {
                final String value = (String) object;

                if (StringUtils.isEmpty(value)) {
                    parametersToRemove.add((String) entry.getKey());
                }
            } else if (object instanceof String[]) {
                final String[] values = (String[]) object;

                final Object[] objects =
                    ArrayUtils.removeElement(values, "");

                if (objects.length == 0) {
                    parametersToRemove.add((String) entry.getKey());
                }
            } else {
                throw new IllegalArgumentException();
            }
        }

        for (final String parameterToRemove : parametersToRemove) {
            parameters.remove(parameterToRemove);
        }
    }

    result = invocation.invoke();

    return result;
  }
}

这是我在 struts.xml 文件中使用它的方法:

<package name="webdefault" namespace="/" extends="struts-default">
      <interceptors>
        <interceptor name="removeEmptyParameters" class="com.sentrylink.web.struts.RemoveEmptyParametersInterceptor"/>
        <interceptor-stack name="webStack">
            <interceptor-ref name="removeEmptyParameters"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
      </interceptors>

     <default-interceptor-ref name="webStack"/>
     ...
</package>

有人向我指出,原始问题中的 ActionForm 是 Struts 1 约定(该问题已被正确标记),但由于 Google 仍然将一个带有 Struts 2 查询的问题带到这里,我希望这个答案对其他人有用。

在 ActionForm 中默认将 String 值声明为NULL
Eg: private String str = null;

编辑:解决方案是。 我认为对于该属性,您有 setter 和 getter 方法,在 getter 方法中检查值是否为空,然后明确设置 null 值。

请参阅 Apache 的StringUtils.stripToNull()方法。

至于配置,Struts 没有为我们提供该功能(我不记得了)。 我会建议从ActionForm覆盖reset()方法,但在 controller 重新填充表单 bean 之前调用该方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM