---
title: "action向jsp页面传递数据的方法"
author: "wode66"
date: "2009-06-12T22:13:11Z"
tags: []
categories: ["编程语言"]
slug: "action-jsp"
draft: false
lastmod: "2009-06-12T23:36:07Z"
id: 407565
url: "https://suo.iteye.com/blog/407565"
---

action向jsp页面传递数据的几种方法：

 

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

```
<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**方法来传递数据

```
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();
			errorInfo = "用户不能找到，用户名称=[" + username + "]";
		}catch(PasswordErrorException pee) {
			pee.printStackTrace();
			errorInfo = "密码错误";
		}
		request.setAttribute("errorinfo", errorInfo);
		return mapping.findForward("error");
	}
}
```

 

 设置好后，就可以在login\_success.jsp页面中，利用一下代码得到数据：

```
<%= request.getAttribute("username") %>
```

 

**方法二**：直接在**request**对象中获取**ActionForm**对象：

```
<%@ page import="com.bjsxt.struts.*" %>

<%
	LoginActionForm laf = (LoginActionForm)request.getAttribute("loginForm");
%>
               <%=laf.getUsername() %>,登录成功
```

 **方法三**：使用**EL**表达式：