问题
class SampleAction extends ActionSupport {
private Map<String,String> circleIdNameMap;
public String preprocess(){
--logic for populating value of MAP
}
--getters and setters
}
Now my problem is on page load I call preprocess
function and populate the value of Map
. After page submit another method is called and during that after some DB interaction it redirects to JSP, but this time the value of Map
is empty. I am using this Map
for drop-down tag in Struts2.
My preprocess
is associated in the link like:
href="/gma/preprocessConfigureTspThreshold?operatorId=5102&sessionId=12332"`
So only first time when the link is clicked preprocess
is called, after that when I redirect to my JSP so its not called then, so second time the value of Map
is empty.
Shall I put the map in a session so that it is retained? Or can do something else?
I read that don't use
preprocess
function, usePreparable
interface. But as per docs:The prepare method will always be called by the Struts 2 framework's prepare interceptor
whenever any method is called for the Action class.
So, it will be called for every method. I want preprocess
to be called only when page loads.
回答1:
The prepare
method of the Preparable action class is called on every action execution, that's right. That might be the reason why you prepare the map for a drop-down in the preprocess
method.
public class SampleAction extends ActionSupport {
private Map<String,String> circleIdNameMap;
private String circleId;
//getters and setters here
protected boolean reload = false;
private void preprocess(){
// Get the Map by calling a stateless Session bean
circleIdNameMap = remoteInterface.getMap();
}
public String action1(){
preprocess();
Map session = ActionContext.getContext().getSession();
session.put("circleIdNameMap ", circleIdNameMap );
return SUCCESS;
}
public String action2(){
Map session = ActionContext.getContext().getSession();
circleIdNameMap = (Map<String,String>)session.get("circleIdNameMap");
if (circleIdNameMap == null){
if (reload) {
preprocess();
Map session = ActionContext.getContext().getSession();
session.put("circleIdNameMap ", circleIdNameMap );
} else {
addActionError("circleIdNameMap is null");
return ERROR;
}
}
return SUCCESS;
}
...//other actions
}
the JSP for drop-down
<s:select name="circleId" list="circleIdNameMap" listKey="key" listValue="value"/>
The meaning of this code is: you should not return result SUCCESS
or INPUT
if fields in JSP aren't initialized.
来源:https://stackoverflow.com/questions/20944860/maintaining-values-of-action-variables