《刨根問底--struts--得到request過程詳解》詳細分析了經過ServletActionContext.getRequest()獲取request的詳細過程,還能夠經過action類繼承ServletRequestAware獲取rquest。ServletRequestAware接口前面的註釋:All Actions that want to have access to the servlet request object must implement this interface.<p> java
public interface ServletRequestAware { /** * Sets the HTTP request object in implementing classes. * * @param request the HTTP request. */ public void setServletRequest(HttpServletRequest request); }具體action中的操做
public class Action extends ActionSupport implements SessionAware,ServletRequestAware{ protected Map session = null; protected HttpServletRequest request = null; @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } @Override public void setSession(Map map) { this.session = map; } }這樣,就得到了request對象。
具體怎麼何時執行setServletRequest(),如今看看ServletConfigInterceptor攔截器。 session
public class ServletConfigInterceptor extends AbstractInterceptor implements StrutsStatics { public String intercept(ActionInvocation invocation) throws Exception { final Object action = invocation.getAction(); final ActionContext context = invocation.getInvocationContext(); if (action instanceof ServletRequestAware) { HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); ((ServletRequestAware) action).setServletRequest(request); } if (action instanceof ServletResponseAware) { HttpServletResponse response = (HttpServletResponse) context.get(HTTP_RESPONSE); ((ServletResponseAware) action).setServletResponse(response); } if (action instanceof ParameterAware) { ((ParameterAware) action).setParameters((Map)context.getParameters()); } if (action instanceof ApplicationAware) { ((ApplicationAware) action).setApplication(context.getApplication()); } if (action instanceof SessionAware) { ((SessionAware) action).setSession(context.getSession()); } if (action instanceof RequestAware) { ((RequestAware) action).setRequest((Map) context.get("request")); } if (action instanceof PrincipalAware) { HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); if(request != null) { // We are in servtlet environment, so principal information resides in HttpServletRequest ((PrincipalAware) action).setPrincipalProxy(new ServletPrincipalProxy(request)); } } if (action instanceof ServletContextAware) { ServletContext servletContext = (ServletContext) context.get(SERVLET_CONTEXT); ((ServletContextAware) action).setServletContext(servletContext); } return invocation.invoke(); } }註釋:invocation.getAction()獲取action對象, instanceof 判斷action對象是不是默認特定的對象。若是是的話就是執行相應的代碼。
具體何時執行攔截器的intercept()方法,請看《刨根問底-struts-serviceAction()建立並執行action
》 ide