您的位置:首页 > 编程语言 > Java开发

struts2用ActionContext获取Web资源。

2015-12-30 13:40 555 查看
什么是Web资源?比如http post的值,session,等等。

ActionContext是在com.opensymphony.xwork2.ActionContext;的一个对象,通过静态成员getContext()获取ActionContext对象的实例。

通过 成员变量 getSession获取一个Map<String,Object> 关于http session的map.键为session的键,值为session存的值。

在Jsp中可以使用EL表达式${sessionScope.键}获取这个Session值,El表达式和标签库不一样的是,el表达式 不需要加任何包的支持,用于显示数据。

testAction.java

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;

public class testAction {

public String execute()

{

//|getContext()是静态函数

ActionContext ac=ActionContext.getContext();

//|sessionMap

Map<String,Object> sessionMap=ac.getSession();

sessionMap.put("SessionKey", "SessionValue");

return "success";

}

}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

<package name="test" extends="struts-default" namespace="/test">

<!-- ActionContext获取Web资源 -->

<action name="test1" class="testAction">

<result name="success">/test1.jsp</result>

</action>

</package>

</struts>

test1.jsp

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

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'test1.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

下面是ActionContext的测试结果 <br>

${sessionScope.SessionKey}

</body>

</html>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: