1、ServletXxxAware接口
ActionContext和XxxAware接口对应,属于解耦的设计,但功能单一,我们能够获取到的只是struts2给我们返回的map。ServletActionContext和ServletXxxAware接口对应,属于耦合的设计,但功能强大,能够直接获取servlet相关的对象。
ServletXxxAware同样是struts2依赖注入给Action类的设计,使用起来比ServletActionContext方便,比如多个action的方法,就不需要每次都从context获取了。
ServletContextAware,ServletRequestAware, ServletResponseAware
2、测试代码
package com.test.action; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.util.ServletContextAware; public class TestServletAwareAction implements ServletContextAware, ServletRequestAware, ServletResponseAware { public String execute() { context.setAttribute("applicationKey", "applicationValue"); HttpSession session = request.getSession(); session.setAttribute("sessionKey", "sessionValue"); request.setAttribute("requestKey", "requestValue"); return "success"; } // 注入的HttpServletResponse private HttpServletResponse response; @Override public void setServletResponse(HttpServletResponse response) { this.response = response; } // 注入的HttpServletRequest private HttpServletRequest request; @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } // 注入的ServletContext private ServletContext context; @Override public void setServletContext(ServletContext context) { this.context = context; } }
时间: 2024-10-24 02:15:48