I have a struts2 action class which looks something like this:
//import relevant packages
public class Product implements SessionAware, ServletRequestAware,
ServletResponseAware, ServletContextAware {
private String productName;
private String description;
private String price;
private ServletContext servletContext;
private HttpServletRequest servletRequest;
private HttpServletResponse servletResponse;
private Map sessionMap;
//getters and setters here
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public void setSession(Map map) {
this.sessionMap = map;
}
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public String execute() {
// do something here
return "success";
}
public List<String> getCountries() {
List<String> countries = new ArrayList<String>();
countries.add("Australia");
countries.add("Fiji");
countries.add("New Zealand");
countries.add("Vanuatu");
return countries;
}
}
sruts.xml has the following contents:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="package.name" namespace="/" extends="struts-default">
<action name="Product_input">
<result>/jsp/Product.jsp</result>
</action>
<action name="Product_save" class="package.name.Product" method="execute">
<result>/jsp/Details.jsp</result>
</action>
</package>
</struts>
Product.jsp consists of a simple form:
<s:form action="Product_save">
<s:textfield label="Product Name" key="productName"/>
<s:textfield label="Description" key="description"/>
<s:textfield label="Price" key="price"/>
<s:submit/>
</s:form>
Details.jsp displays the contents entered in the form:
<h5>Details:</h5>
Product Name:
<s:property value="productName" />
<br /> Description:
<s:property value="description" />
<br /> Price: $
<s:property value="price" /> </br>
<s:property value="countries[0]" /> </br>
The last line in Details.jsp tries to access the countries list declared in the getCountries() in action class and ideally it should not print anything since the method is never accessed nor the countries list is part of the action class attributes (and hence while creating the object of type Product in the Value stack, it shouldn’t have countries).
But it does print Australia (the indexed value of list) along with the other form properties. How/Why is this happening?
When you write
countriesinit calls for
getCountries()method. Now as you’ve put[0]next to it andcountriesbeing a list…it translates to
You can verify the same by putting a
sysoutin thegetCountries()method.