Struts2 通過ActionContext物件獲取WEB資源之解耦方式的XxxAware介面方法
阿新 • • 發佈:2018-12-11
這個方法相比較ActionContext而言,如果一個Action類中的多個方法都涉及到了取值設定值得情況,最好用XxxAware介面方法
下面是一個例子
package cn.com.action; import java.util.Map; import org.apache.struts2.interceptor.ApplicationAware; import org.apache.struts2.interceptor.ParameterAware; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; public class AwareAction implements ApplicationAware, SessionAware, RequestAware, ParameterAware { /* * author:命運的信徒 date:2018/12/10 * arm:掌握Action獲取web資源的解耦方式之Aware介面的方式ApplicationAware * ,SessionAware,RequestAware,ParameterAware */ /* * 1.第一步,繼承相應的介面如 2.新增介面的方法(自動新增) 3.賦值 4.執行方法獲取值 */ private Map<String, String[]> parameters; private Map<String, Object> requests; private Map<String, Object> applications; private Map<String, Object> sessions; public void setParameters(Map<String, String[]> parameters) { // TODO Auto-generated method stub this.parameters = parameters; } @Override public void setRequest(Map<String, Object> requests) { // TODO Auto-generated method stub this.requests = requests; } @Override public void setSession(Map<String, Object> sessions) { // TODO Auto-generated method stub this.sessions = sessions; } @Override public void setApplication(Map<String, Object> applications) { // TODO Auto-generated method stub this.applications = applications; } public String execute(){ applications.put("applicationkey", "applicationvalue"); sessions.put("sessionkey", "sessionvalue"); requests.put("requestkey", "requestvalue"); //parameters不可以放值只可以取值 String[] str=parameters.get("tt"); System.out.println(str[0]); return "success"; } }
index.jsp頁面就是一個連結請求
<a href="aware.action?tt=yecunwanzhai">aware介面</a>
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> <package name="tjn" extends="struts-default"> <action name="url" class="cn.com.action.Info" method="save"> <result name="success">/WEB-INF/pages/success.jsp</result> </action> <action name="context" class="cn.com.action.TestActionContext"> <result>/context.jsp</result> </action> <action name="aware" class="cn.com.action.AwareAction" > <result>/context.jsp</result> </action> </package> </struts>
顯示引數的頁面
<h4>Aware Test</h4>
application:${applicationScope.applicationkey }<br><br>
session:${sessionScope.sessionkey }<br><br>
request:${requestScope.requestkey }<br><br>
parameter:${parameters.tt[0] }<br><br>