【发布时间】:2017-01-21 06:43:02
【问题描述】:
我的 Action 类 preprocess() 和 getThresholdData() 中有两个方法:
我在
preprocess()方法中设置了一个List<String>变量(页面加载时调用);然后从 JSP 页面提交一个表单并调用
getThresholdData()。
JSP:
<body>
<s:form action="getThresholdDataConfigureTspThreshold">
<s:select list="tspNames" label="Select TSP:" name="tspName"></s:select>
<s:radio list="{'Default', 'Latest'}" label="Select Threshold type:"
name="thresholdType"></s:radio>
<s:submit value="Submit"></s:submit>
</s:form>
</body>
tspNames(要迭代的列表)在页面加载后立即在操作类的preprocess() 方法中设置,如下所示:
<a href="/gma/preprocessConfigureTspThreshold" />
动作类:
public class ConfigureTspThresholdAction extends ActionSupport{
private static final String DISPLAY = "display";
private Map session;
private List<String> tspNames;
private List<String> thresholdParametres;
private String tspName;
private String thresholdType;
public String preprocess() {
// Get tspNames from server after Table creation
tspNames = new ArrayList<String>();
tspNames.add("RELIANCE");
tspNames.add("AIRTEL");
tspNames.add("TATA");
tspNames.add("BSNL");
tspNames.add("MTNL");
session.put("tspNames", tspNames);
return DISPLAY;
}
public String getThresholdData(){
// Get parametres from server after creating table
thresholdParametres = new ArrayList<String>();
thresholdParametres.add("1");
thresholdParametres.add("2");
thresholdParametres.add("3");
thresholdParametres.add("4");
thresholdParametres.add("5");
System.out.println("************" + tspNames);
return DISPLAY;
}
/** GETTER AND SETTERS*/
}
struts.xml:
<action name="*ConfigureTspThreshold"
class="gma.struts.ConfigureTspThresholdAction" method="{1}">
<result name="display">pages/ConfigureTspThresholdInput.jsp</result>
</action>
流程是:
- JSP 加载
preprocess在设置列表的地方调用。 - 用户填写并提交表单,一些工作在服务器端完成,用户重定向到同一个 JSP。
但是错误是因为 JSP 无法显示为 preprocess() 方法中设置的列表 tspNames 即将出现 null。
在这里,当我尝试打印列表时
System.out.println("************" + tspNames);
我在第一个函数中设置的值是null。
为什么会这样?表单提交后变量值是否丢失? 与会话概念有什么关系吗?
【问题讨论】:
-
@SiddharthTrikha 每个变量都有其作用域。因此,当您调用预处理函数并设置列表值时,它仅适用于该函数。在这个范围之外,它的值为空。例如,假设您非常了解“java”语言,但对“.net”一无所知。因此,当有人问您有关 java 的任何问题时,您知道答案.. 但 .NET 不一样.. 您不知道答案,因为它超出了您的范围。所以首先你必须学习它,然后你才能回答它。
-
@SiddharthTrikha 对于每个动作调用,都会创建一个动作类的新实例,如果您不使用数据填充该实例,则在没有它的情况下渲染 JSP 会丢失。