日期:2014-05-16  浏览次数:20426 次

action向jsp页面传递数据的方法
action向jsp页面传递数据的方法
关键字: struts, request
action向jsp页面传递数据的几种方法:



前提:在struts的配置文件struts-config.xml中,设置该action的scope属性为“request”,即:

Xml代码 
<struts-config> 
    <form-beans> 
        <form-bean name="loginForm" type="com.bjsxt.struts.LoginActionForm"/> 
    </form-beans> 
     
    <action-mappings> 
        <action path="/login" 
                type="com.bjsxt.struts.LoginAction" 
                name="loginForm" 
                scope="request" 
        > 
            <forward name="success" path="/login_success.jsp"/> 
            <forward name="error" path="/login_error.jsp"/>         
        </action> 
    </action-mappings> 
</struts-config> 

<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.bjsxt.struts.LoginActionForm"/>
</form-beans>
  
   <action-mappings>
   <action path="/login"
   type="com.bjsxt.struts.LoginAction"
   name="loginForm"
   scope="request"
   >
   <forward name="success" path="/login_success.jsp"/>
<forward name="error" path="/login_error.jsp"/>
   </action>
   </action-mappings>
</struts-config>    注意:所有struts-config.xml中的path属性都是以"/"开头的。

方法一:在action中利用request对象的setAttribute方法来传递数据

Java代码 
package com.bjsxt.struts;  
/** 
* 用户登录的Action 
*/ 
public class LoginAction extends Action {  
 
    public ActionForward execute(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
        LoginActionForm laf = (LoginActionForm)form;  
        String username = laf.getUsername();  
        String password = laf.getPassword();  
        String errorInfo = "";  
        try {  
            UserManager.getInstance().login(username, password);  
            //request.setAttribute("username", username);  
            return mapping.findForward("success");  
        }catch(UserNotFoundException unfe) {  
            unfe.printStackTrace();  
  &nbs