Struts2 将列表数据从 JSP 发送到 Action 类:替代方式

2022-01-16 00:00:00 type-conversion java jsp struts2 ognl

我正在向一位同事解释如何使用索引从 JSP 页面获取列表数据以返回到操作类,如 这里和这里.他不太明白,自己摸索了一下,直到他突然完全不使用索引就让它工作了!

I was explaining to a colleague the way of getting list data from a JSP page to back to the action class by using indices as explained here and here. He didn't quite understand and fumbled a bit on his own until he suddenly he made it work by not using indices at all!

在他的 JSP 页面中,他有:

In his JSP page he had:

<input type="checkbox" name="contactNameList" value="someValue1">
<input type="checkbox" name="contactNameList" value="someValue2">
<input type="checkbox" name="contactNameList" value="someValue3">
<input type="checkbox" name="contactNameList" value="someValue4">

在他的动作课上,他有合适的"二传手:

In his action class he had the 'appropiate' setters:

public List<String> getContactNameList()

public void setContactNameList(List<String> list)

我很困惑为什么会这样.我认为这是可行的,因为他正在发送非 bean 数据(在本例中为字符串),并且 Struts2/OGNL 中内置了一个智能功能,可以将值附加到列表而不是覆盖他们.

I'm baffled as to why this work. I think this works because he is sending non-bean data (in this case strings) and there is an intelligence build into Struts2/OGNL to append values to lists rather than overwrite them.

任何人都可以详细解释这个无索引"案例的幕后情况吗?字符串列表是如何用上面的代码片段实例化和填充的?

Can anybody explain with great detail what is going behind the hood in this "no indices" case? How is the list of strings instantiated and populated with the snippets above?

推荐答案

你应该明白 bean 数据而不是 bean 数据是作为参数传递给动作的.参数有一个结构,如果你实现 ParameterAware,你可以找到它.

You should understand that bean data and not bean data are passed as parameters to the action. The parameters has a structure that you can find if you implement ParameterAware.

请注意,将返回给定名称的所有参数值,因此地图中对象的类型是java.lang.String[].

Note that all parameter values for a given name will be returned, so the type of the objects in the map is java.lang.String[].

然后 XWork Type Conversion 会尽力将此映射转换为 beans 属性.请参阅内置类型转换支持.

Then XWork Type Conversion make its best to convert this map to beans properties. See Built in Type Conversion Support.

框架中的常规类型转换是透明的.一般来说,您需要做的就是确保 HTML 输入的名称可以在 OGNL 表达式中使用.(HTML 输入是表单元素和其他GET/POST 参数.)

Routine type conversion in the framework is transparent. Generally, all you need to do is ensure that HTML inputs have names that can be used in OGNL expressions. (HTML inputs are form elements and other GET/POST parameters.)

在没有索引的情况下,参数被映射在一个键下,而不是索引名称在它们自己的名称下使用.

In the no indexes case parameters are mapped under the one key, rather than indexed names are used under their own names.

相关文章