数组作为Struts 2中的get参数

Tho*_*mas 6 struts2 http-get java-ee

我有一个像下面这样的动作

public class CompareAction {

    private Long[] pids;

    public Long[] getPids() {
        return pids;
    }

    public void setPids(Long[] pids) {
        this.pids = pids;
    }

    public String displayComparison() {
        for (Long pid : pids) {
            System.out.println("pid = " + pid);
            System.out.println();
        }
        return "success";
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试通过在地址栏中键入以下URL来发送数组http://localhost:8080/sm-shop/compare?pids=12,23,34.我想要的输出是

pid = 12

pid = 23

pid = 34
Run Code Online (Sandbox Code Playgroud)

但我得到的是

pid = 122334
Run Code Online (Sandbox Code Playgroud)

我试过谷歌搜索但无法找到如何做到这一点.请帮我弄清楚什么是错的.

Ale*_*r M 5

您需要pids多次传递参数:

http://localhost:8080/sm-shop/compare?pids=12&pids=23&pids=34
Run Code Online (Sandbox Code Playgroud)

如果您将pids属性声明为数组,Struts2将自动将多个参数映射到数组.


小智 5

如果你想保留this(http://localhost:8080/sm-shop/compare?pids=12,23,34)url格式,你必须添加一个自定义转换器,或者你可以在你的动作中使pids成为一个String,并通过用逗号分割它来解析数组.