如何在struts2中访问bean内部动作

时间:2014-09-02 20:09:34

标签: struts2

我有以下test.jsp,我点击提交按钮,我试图在transactionBean中设置值并将其显示在HelloWorld.jsp上,但getTransactionBean()返回null 。能不能让我知道我做错了什么。

test.jsp的

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="displayActionlogmetoo.action" method="post">
    <s:submit method="logmetoo" key="login" align="center" />
</s:form>
</body>
</html> 

的helloWorld.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>

   username <s:property value="transactionBean.username"/>
   password <s:property value="transactionBean.password"/>

</body>
</html>

我的Struts.xml是:

<?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>


<package name="default" namespace="/" extends="struts-default"> 
<action name="displayActionlogmetoo" 
    class="com.tutorialspoint.struts2.DisplayLoginAction" 
    method="logmetoo">

<result name="success">HelloWorld.jsp</result>
</action>
</package>
</struts>

我的行动是:

public class DisplayLoginAction extends ActionSupport {

   private TransactionBean transactionBean;
   public TransactionBean getTransactionBean() {
        return transactionBean;
   }

   public void setTransactionBean(TransactionBean transactionBean) {
        this.transactionBean = transactionBean;
   }

   public String logmetoo(){
        System.out.println("Inside logmetoo");
        getTransactionBean().setUsername("usename");
        getTransactionBean().setPassword("password");
        return SUCCESS;
   }
}

1 个答案:

答案 0 :(得分:1)

实现transactionBean实例化的两种方式:

1)自己动手。这很简单:

public String logmetoo(){
    System.out.println("Inside logmetoo");

    setTransactionBean(new TransactionBean());
    getTransactionBean().setUsername("gaurav");
    getTransactionBean().setPassword("bhardwaj");
    return Action.SUCCESS;
}

2)在表单中添加输入字段,并使用name属性告诉您必须实例化字段的操作类。

<s:form action="displayActionlogmetoo.action" method="post">
    <input type="text" name="transactionBean.userName"/>
    <input type="text" name="transactionBean.password"/>
    <s:submit method="logmetoo" key="login" align="center" />
</s:form>

通过向服务器提交表单,struts将自动查看

name="transactionBean.userName"

并执行以下代码:

displayLoginAction.setTransactionBean(new TransactionBean());
displayLoginAction.getTransactionBean().setUserName(*whatever is filled in in the input*);

这不是魔术,它是由param拦截器自动完成的。 param拦截器是拦截器默认堆栈的一部分。