为什么 Struts2 将我的字符串转换为字符串数组? [英] Why is Struts2 converting my string to a string array?

查看:32
本文介绍了为什么 Struts2 将我的字符串转换为字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Struts 2(JDK 1.7、Struts 2.2.1)应用程序,其中包含一个过滤条件列表,以字符串形式存储在映射中.

I have a Struts 2 (JDK 1.7, Struts 2.2.1) application that contains a list of filtering criteria, stored as strings in a map.

Map< String, String > m_filters = new HashMap< String, String >();

public Map< String, String > getFilters() {
    return m_filters;
}

我传递了一个格式如下的 URL:

I pass a URL formatted like this:

http://myserver.com/myapp/GenerateReport.action?reportID=Whatever&filters.fromDate=0&filters.toDate=2000000000&filters.FcsType=piv_cardholder_3kp&detailed=true

即使 Map 有 key &指定为 String 的值类型,尝试从中获取值

Even though the Map has both key & value types specified as String, attempting to get a value from this

    Map< String, String > filters = getFilters();
    String value = filters.get( "fromDate" );

导致抛出这个异常:

java.lang.ClassCastException: [Ljava.lang.String;不能强制转换为 java.lang.String

我在单元测试中重现了这一点,并在调试器中确认 Struts 2 似乎正在为每个参数创建一个 String[1] 而不是 String.即它是一个长度为 1 的字符串数组,唯一的字符串是预期值(在本例中为0").

I reproduced this in a unit test, and confirmed in a debugger that Struts 2 seems to be creating a String[1] instead of a String for each of the parameters. i.e. it is a length-1 string array with the only string being the expected value ("0" in this case).

我的问题是:这是 Struts2 中的错误,还是我做错了什么?

My question is: Is this a bug in Struts2, or am I doing something incorrectly?

如果是错误,是否有已知的解决方法?

If it is a bug, is there a known workaround?

推荐答案

如果您遵循 Java bean 约定,则没有问题.

There are no issues if you follow Java bean conventions.

以下是解决问题的一些指南:

Here are some guidelines to resolve the issue:

  • 如果您将私有成员命名为过滤器"并仅提供过滤器的 getter,则不会发生此问题.
  • 如果您在 getter 之外还提供公共 setter(即使您为私有成员使用不同的名称,例如 m_filter),则不会发生此问题
  • 此问题仅在您不提供 setter 并且该属性与 getter 名称不同时才会发生.

长话短说遵循惯例.以上行为已用 Struts 2.3.4 测试

Long story short follow conventions. Above behaviour tested with Struts 2.3.4

我猜正在发生什么:getter 也允许设置(如果只有一个 setter,你只能在地图中设置一个项目,对于当前的参数拦截器,这是案件).检查 bean 的属性以查看它应该如何进行类型转换,可能首先它会查找失败的 setter,然后查看该名称的属性的操作以确定失败的类型,因为它需要使用默认值.默认参数类型是 String 到 String[] 的映射,这就是您所看到的.

What I'm guessing is happening: The getter allows for setting too (If there was only a setter you could only set one item in the map, well with the current parameter interceptor this is the case). The bean is inspected for the property to see how it should do type conversion probably first it looks for a setter failing that it looks at the action for a propterty of that name to determine the type failing that it will need to use the default. The default parameter type is a mapping of String to String[] and this is what you are seeing.

这篇关于为什么 Struts2 将我的字符串转换为字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆