Pass Arraylist from Java class and fetch it in JSP page In Struts 2

佐手、 提交于 2019-12-04 07:00:46

问题


I am trying to get ArrayList in JSP page passed from java class. But eventually I didn't succeed. Here is what I have done.

Here is my POJO class:

public class Coordinates {    
private double latitude;
private double longitude;
public double getLatitude() {
    return latitude;
}
public void setLatitude(double latitude) {
    this.latitude = latitude;
}
public double getLongitude() {
    return longitude;
}
public void setLongitude(double longitude) {
    this.longitude = longitude;
}
}

And this one is Java class where I write business logic:

public class Leverage extends ActionSupport{
List<Coordinates> mylist = new ArrayList<Coordinates>();
public String getMapDetail()throws Exception{
    LevService lev =LevService .getInstance();
    mylist = lev .getCurrentLocation();
    System.out.println("Size of list is: "+mylist.size());
    return SUCCESS;
}

Here is my JSP page:

<Table>
<s:iterator value="mylist" status="Status">           
<tr>
<td><s:property  value="%{mylist[#Status.index].latitude}" /></td>
<td><s:property  value="%{mylist[#Status.index].longitude}" /></td>
</tr>
</s:iterator> 
</Table>

It prints the size of ArrayList in console. But it doesn't create the row.


回答1:


The iterator tag expects a myList, so you should provide a getter

public List<Coordinates> getMyList() {
    return myList;
}

This value should be initialized like you did

private List<Coordinates> myList = new ArrayList<>();

Then you should not override it in the action, just create a local variable or rename a variable returned by the service.

List<Coordinates> list = lev.getCurrentLocation();
if (list != null && list.size() > 0)
  myList = list;

In the JSP you can get the values from the iterator tag, it finds all values referenced inside the body of the tag in the value stack. You don't need to provide an indexed expression to get the values.

<table>
<s:iterator value="myList">           
<tr>
<td><s:property value="%{latitude}" /></td>
<td><s:property value="%{longitude}" /></td>
</tr>
</s:iterator> 
</table>


来源:https://stackoverflow.com/questions/22869995/pass-arraylist-from-java-class-and-fetch-it-in-jsp-page-in-struts-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!