Struts2中使用ActionContext传递参数

Struts2中使用ActionContext传递参数

(1)使用背景

        在Struts中,一般都是通过View页面通过Post或Get方式像Action提交请求,Action返回逻辑视图,struts再根据struts.xml中的逻辑视图名跳转到物理视图。

        当我们需要从Action向物理视图传参数时,可以使用ActionContext来传递参数。

(2)使用示例

        Action中的代码如下所示:

package blog.wlb.net.oschina.my;

import com.opensymphony.xwork2.ActionContext;

public class UserAction {
	
	public String test(){
		ActionContext.getContext().put("username", "zhangsan");
		ActionContext.getContext().put("password", "123456");
		ActionContext.getContext().put("age", 26);
		return "success";
	}
}

        本示例中,通过Actioncontext向View中传递了3个参数分别是username、password、age。

        Struts.xml代码如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <package name="default" extends="struts-default">
        <action name="user" class="blog.wlb.net.oschina.my.UserAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

        success.jsp代码如下所示:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>参数接收页面</title>
  </head>
  
  <body>
	UserName:${#username}<br/>
	Password:${#password}<br/>
	Age:${#age}<br/>
  </body>
</html>

        最终结果如下图所示:

        135918_wK7U_119360.jpg

二、知识扩展

(1)访问ActionContext当中的属性方法

访问ActionContext当中属性的方法为:{#属性名}

(2)Struts2中对ActionContext访问的容错性

如果使用{属性名}这种不加“#”的方式也是可以访问的,但是这种是利用了Struts2中的容错性,强烈建议不要这样写。

转载于:https://my.oschina.net/wlb/blog/278690

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值