struts及jstl使用问题集(一)

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的属性值。

转载于:https://www.cnblogs.com/swingboat/archive/2005/06/06/168839.html

猜你喜欢

转载自blog.csdn.net/weixin_33676492/article/details/93957306