在Struts2的Action中使用Servlet的API(鬆耦版)

前面介紹瞭如何在Action中獲取Servlet的API對象,實際上這種方法是Action與Servlet的緊耦,不利於軟件的擴展,也不是Struts2推薦的方法,那麼如何實現鬆耦合地獲取Servlet的API呢?答案是ActionContext類。

下面介紹使用ActionContext類來對request、session和application對象進行操作。

首先新建Web項目struts2.11,然後添加Struts2框架支持文件。

1.創建控制層,ShowScopeValue.java文件,代碼如下

package controller;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;


public class ShowScopeValue {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String execute(){
			
		Map request = (Map) ActionContext.getContext().get("request");
		request.put("requestValue", "this is a request value");
		ActionContext.getContext().put("otherRequestValue", "this is an other request value");
		
		Map session = (Map) ActionContext.getContext().getSession();
		session.put("sessionValue", "this is a session value");
		
		Map application = (Map) ActionContext.getContext().getApplication();
		application.put("applicationValue", "this is a application value");
		
		return "success";
	}

	
}

使用如下代碼分別獲取request、session和application

		Map request = (Map) ActionContext.getContext().get("request");
		Map session = (Map) ActionContext.getContext().getSession();	
		Map application = (Map) ActionContext.getContext().getApplication();

由於Struts2沒有類似getRequest()這樣的方法,所以必須使用(Map) ActionContext.getContext().get("request");這樣的代碼獲取request對象,也可以使用如下代碼直接向request對象中存放數據

ActionContext.getContext().put("otherRequestValue", "this is an other request value");

 

2.創建JSP視圖

新建showScopeValue.jsp,代碼如下

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page isELIgnored="false"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<body>
		request值是:
		<s:property value="#request.requestValue" />
		<br />
		other request值是:
		<s:property value="#request.otherRequestValue" />
		<br />
		session值是:
		<s:property value="#session.sessionValue" />
		<br />
		application值是:
		<s:property value="#application.applicationValue" />
		<br />
	</body>
</html>

3.配置struts.xml,代碼如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

	<package name="struts2.11" extends="struts-default">
		<action name="showScopeValue" class="controller.ShowScopeValue">
			<result name="success">/showScopeValue.jsp</result>
		</action>

	</package>

</struts>

4.運行結果,如下圖所示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章