页面中的请求如何流转到后台程序,后台程序又是如何将数据转发给页面?
为了避免于Servlet API耦合在一起,方便Action做单元测试,Struts2对HttpServletRequest HttpSession ServletContext进行了封装,构造了三个Map
架构如下图所示:
图片说明

页面请求

<a href="TestActionContext.action?name=actioncontext">Test ActionContext</a>

struts.xml

<action name="TestActionContext" class="com.atguigu.struts2.actioncontext.TestActionContext">
       <result>/test-actionContext.jsp</result>
</action>

TestActionContext

public String execute() {

        ActionContext actionContext = ActionContext.getContext();

        //1.获取application对应的Map,并向其添加一个属性
        Map<String, Object> application = actionContext.getApplication();
        application.put("applicationKey", "applicationValue");
        //从页面中获取值
        Object date = application.get("date");
        System.out.println(date);

        //2.session
        Map<String, Object> session = actionContext.getSession();
        session.put("sessionKey", "sessionValue");

        //3.request
        Map<String,Object> request = (Map<String,Object>) actionContext.get("request");
        request.put("requestKey", "requestValue");

        //4.获取请求参数对应的Map,并获取指定的参数值
        Map<String, Parameter> parameters = actionContext.getParameters();
        System.out.println(parameters);//{name=actioncontext}
        System.out.println(parameters.get("name"));
        return "success";
    }

页面jsp获取

<body>
    application:${applicationScope.applicationKey}
    <br>
    session:${sessionScope.sessionKey}
    <br>
    request:${requestScope.requestKey}
    <br><br><br>

    application2:${applicationScope.applicationKey2}
    <br>
    session2:${sessionScope.sessionKey2}
    <br>
    request2:${requestScope.requestKey2}

</body>

第二种方式:
类通过实现aware接口的方式
若一个Action类中有多个action方法,且多个方法都需要使用域对象的Map或parameters,则建议使用接口的方式

public class TestAwareAction implements ApplicationAware,SessionAware,RequestAware {

    public String execute() {
        application.put("applicationKey2", "applicationValue2");
        Object date = application.get("date");
        System.out.println(date);

        return "success";
    }

    private Map<String, Object> application;

    @Override
    public void setApplication(Map<String, Object> application) {

        this.application = application;

    }

    @Override
    public void setRequest(Map<String, Object> request) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setSession(Map<String, Object> session) {
        // TODO Auto-generated method stub

    }

}