1、ActionForm中的屬性必須在<html:form></html:form>塊中輸出
struts-config.xml文件配置:
<form-beans>
<form-bean name="TestForm" type="yhp.test.struts.TestForm" />
</form-beans>
<action-mappings>
<action input="/test/teststruts.jsp" name="TestForm" path="/test/teststruts" scope="request" type="yhp.test.struts.TestAction" validate="false">
<forward name="success" path="/test/teststruts.jsp" />
</action>
</action-mappings>
TestForm.java文件(兩個屬性):
package yhp.test.struts;
import org.apache.struts.action.*;
public class TestForm extends ActionForm{
private String message;
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
TestAction.java文件:
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
if(actionForm instanceof TestForm){
TestForm form=(TestForm)actionForm;
form.setMessage("Test Struts!");
form.setData("Return data is YHP");
}
return actionMapping.findForward("success");
}
teststruts.jsp文件:
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%
String contextPath = request.getContextPath();
response.setLocale(java.util.Locale.CHINA);
%>
<html>
<head>
</head>
<body>
<html:form action="/test/teststruts.do" styleId="formItem" method="post">
<html:text property="message"/><br>
<html:text property="data"/><br>
</html:form>
</body>
</html>
說明:沒有紅色部分代碼,后臺會報出Cannot find bean org.apache.struts.taglib.html.BEAN in any scope的錯誤信息。這樣說明struts中ActionForm的數據是基于html中對應form的數據。
2、不利用struts標簽輸出ActionForm的屬性值
<%@ page import="yhp.test.struts.TestForm"%>
<%
TestForm form=(TestForm)request.getAttribute("TestForm");//ActionForm類名
%>
<html>
<head>
</head>
<body>
<html:form action="/test/teststruts.do" styleId="formItem" method="post">
<html:text property="message"/><br>
<html:text property="data"/><br>
<%=form.getMessage()%><br>
</html:form>
</body>
</html>
3、通過JSTL輸出ActionForm中的屬性值
利用JSTL輸出AcitonForm中的屬性值:<c:out value="${TestForm.data}" /><br>
利用JSTL輸出AcitonForm中的屬性值:<c:out value="${requestScope.TestForm.data}" /><br>
紅色的字是ActionForm類名,兩句的結果是一樣的
說明:struts把ActionForm寫入了requestScope中,類名作為requestScope的名字。
即:httpServletRequest.setAttribute("TestForm",actionForm);
<c:out value="${requestScope.TestForm.data}" /> 也就是輸出一個bean的屬性值。