Struts2 - 从JSP访问Action变量

时间:2015-04-03 09:49:22

标签: java jsp variables struts2 action

我对Struts2有一点问题,我不知道它为什么不起作用......

我想通过Action类在两个JSP之间传递2个变量:

view1.jsp:

<s:form action="myAction">
   <input id="var1" name="var1" type="text" />
   <input id="var2" name="var2" type="text" />
   <button type="submit"> Ok </button>
</s:form>

- &GT; var1和var2是我想传递给Action类的变量

struts.xml中:

<action name="myAction" class="MyAction" method="execute">
    <result name="success">view2.jsp</result>
</action>

Action.java:

public class MyAction extends DefaultActionSupport
{
    private String var1;
    private String var2;

public String execute() throws Exception
{
    // ... Some actions ...
    return SUCCESS;
}

// Getters & Setters for var1 and var2 (generated by Eclipse)
public String getVar1()
{
    return var1;
}

public void setVar1(String var1)
{
    this.var1 = var1;
}

public String getVar2()
{
    return var2;
}

public void setVar2(String var2)
{
    this.var2 = var2;
}

- &GT;这工作正常;如果我将“System.out.print”与getter放在一起,它会向我显示var1(content1)和var2(content2)的好值

view2.jsp:

Values of var1 = <s:property value="var1" />
Values of var2 = <s:property value="var2" />

Textfield with var1 in default-value : <s:textfield value="%{var1}" />
Textfield with var2 in default-value : <s:textfield value="%{var2}" />

- &GT;这里有一个问题: 我无法获得var1和var2的内容!
- &GT; <s:property value="var1" /><s:textfield value="%{var1}返回“null”

我的错误在哪里?我不明白......我跟着别人在网上说的话......

谢谢!

1 个答案:

答案 0 :(得分:0)

我终于找到了问题的答案! 要获得var1var2的值,我必须使用以下行:

view1.jsp:

<s:form action="myAction">
   <input id="var1" name="var1" type="text" />
   <input id="var2" name="var2" type="text" />
   <button type="submit"> Ok </button>
</s:form>

<强> struts.xml中:

<action name="myAction" class="MyAction" method="execute">
    <result name="success">view2.jsp</result>
</action>

Action.java:

public class MyAction extends DefaultActionSupport{
    private String var1;
    private String var2;

    public String execute() throws Exception{
        // ... Some actions ...

        ActionContext.getContext().getSession().put("var1", getVar1());
        ActionContext.getContext().getSession().put("var2", getVar2());

        return SUCCESS;
    }

    // Getters & Setters for var1 and var2 (generated by Eclipse)
    public String getVar1(){
        return var1;
    }

    public void setVar1(String var1){
        this.var1 = var1;
    }

    public String getVar2(){
        return var2;
    }

    public void setVar2(String var2){
        this.var2 = var2;
    }
}

view2.jsp:

Values of var1 = <s:property value="#session.var1" />
Values of var2 = <s:property value="#session.var2" />

//To transform var1 and var2 into JSP variables :

<s:set var="var1 " value="#session.var1 " />
<s:set var="var2 " value="#session.var2" />
<jsp:useBean id="var1 " type="java.lang.String" />
<jsp:useBean id="var2 " type="java.lang.String" />

<%
    String myString1 = var1;
    String myString2 = var2
%>