/** Cleans up a request of thread locals */
 public void cleanupRequest(HttpServletRequest request) {
   Integer counterVal = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);
   if (counterVal != null) {
     counterVal -= 1;
     request.setAttribute(CLEANUP_RECURSION_COUNTER, counterVal);
     if (counterVal > 0) {
       if (log.isDebugEnabled()) {
         log.debug("skipping cleanup counter=" + counterVal);
       }
       return;
     }
   }
   // always clean up the thread request, even if an action hasn't been executed
   try {
     dispatcher.cleanUpRequest(request);
   } catch (IOException e) {
     if (LOG.isWarnEnabled()) {
       LOG.warn(
           "Cannot clean up the request, some files can still remain in #0 after upload!",
           e,
           StrutsConstants.STRUTS_MULTIPART_SAVEDIR);
     }
   } finally {
     ActionContext.setContext(null);
     Dispatcher.setInstance(null);
   }
 }
  /** Creates the action context and initializes the thread local */
  public ActionContext createActionContext(
      HttpServletRequest request, HttpServletResponse response) {
    ActionContext ctx;
    Integer counter = 1;
    Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);
    if (oldCounter != null) {
      counter = oldCounter + 1;
    }

    ActionContext oldContext = ActionContext.getContext();
    if (oldContext != null) {
      // detected existing context, so we are probably in a forward
      ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));
    } else {
      ValueStack stack =
          dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
      stack
          .getContext()
          .putAll(dispatcher.createContextMap(request, response, null, servletContext));

      // 利用ValueStack的context属性实例化ActionContext
      ctx = new ActionContext(stack.getContext());
    }
    request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);
    ActionContext.setContext(ctx);
    return ctx;
  }
  public void testCharacterEncodingSetBeforeRequestWrappingAndActionService() throws Exception {
    MockServletContext servletContext = new MockServletContext();
    MockFilterConfig filterConfig = new MockFilterConfig(servletContext);
    MockHttpServletRequest req = new MockHttpServletRequest(servletContext);
    MockHttpServletResponse res = new MockHttpServletResponse();
    MockFilterChain chain = new MockFilterChain();
    final InnerDispatcher _dispatcher = new InnerDispatcher(servletContext);
    Dispatcher.setInstance(null);

    _dispatcher.setDefaultEncoding("UTF-16_DUMMY");

    FilterDispatcher filter =
        new FilterDispatcher() {
          protected Dispatcher createDispatcher(FilterConfig filterConfig) {
            return _dispatcher;
          }
        };
    filter.init(filterConfig);
    // set ActionMapper after init() as all dependencies will be injected in init()
    filter.setActionMapper(new InnerActionMapper());
    _dispatcher.setDefaultEncoding("UTF-16_DUMMY");
    filter.doFilter(req, res, chain);

    assertTrue(_dispatcher.wrappedRequest);
    assertTrue(_dispatcher.serviceRequest);
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    InitOperations init = new InitOperations();
    Dispatcher dispatcher = null;
    try {
      FilterHostConfig config = new FilterHostConfig(filterConfig);
      init.initLogging(config);
      dispatcher = init.initDispatcher(config);

      prepare = new PrepareOperations(dispatcher);
      this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

      postInit(dispatcher, filterConfig);
    } finally {
      if (dispatcher != null) {
        dispatcher.cleanUpAfterInit();
      }
      init.cleanup();
    }
  }
 /** Cleans up the dispatcher instance */
 public void cleanupDispatcher() {
   if (dispatcher == null) {
     throw new StrutsException(
         "Something is seriously wrong, Dispatcher is not initialized (null) ");
   } else {
     try {
       dispatcher.cleanup();
     } finally {
       ActionContext.setContext(null);
     }
   }
 }
 /**
  * Wraps the request with the Struts wrapper that handles multipart requests better
  *
  * @return The new request, if there is one
  * @throws ServletException
  */
 public HttpServletRequest wrapRequest(HttpServletRequest oldRequest) throws ServletException {
   HttpServletRequest request = oldRequest;
   try {
     // Wrap request first, just in case it is multipart/form-data
     // parameters might not be accessible through before encoding (ww-1278)
     request = dispatcher.wrapRequest(request, servletContext);
   } catch (IOException e) {
     String message = "Could not wrap servlet request with MultipartRequestWrapper!";
     throw new ServletException(message, e);
   }
   return request;
 }
  /**
   *
   * <li>forceLookup 为false时,优先返回(ActionMapping) request.getAttribute(STRUTS_ACTION_MAPPING_KEY)
   * <li>forceLookup 为true时,每次都去获取ActionMapper实例 <br>
   *     <br>
   *     Finds and optionally creates an {@link ActionMapping}. if forceLookup is false, it first
   *     looks in the current request to see if one has already been found, otherwise, it creates it
   *     and stores it in the request. No mapping will be created in the case of static resource
   *     requests or unidentifiable requests for other servlets, for example.
   *
   * @param forceLookup if true, the action mapping will be looked up from the ActionMapper
   *     instance, ignoring if there is one in the request or not
   */
  public ActionMapping findActionMapping(
      HttpServletRequest request, HttpServletResponse response, boolean forceLookup) {
    ActionMapping mapping = (ActionMapping) request.getAttribute(STRUTS_ACTION_MAPPING_KEY);
    if (mapping == null || forceLookup) {
      try {
        // ActionMapper默认实例是{ @link org.apache.struts2.dispatcher.mapper.DefaultActionMapper}
        mapping =
            dispatcher
                .getContainer()
                .getInstance(ActionMapper.class)
                .getMapping(request, dispatcher.getConfigurationManager());
        if (mapping != null) {
          // 设置mapping到request属性,
          request.setAttribute(STRUTS_ACTION_MAPPING_KEY, mapping);
        }
      } catch (Exception ex) {
        dispatcher.sendError(
            request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
      }
    }

    return mapping;
  }
Exemple #8
0
  public static String buildNamespace(
      ActionMapper mapper, ValueStack stack, HttpServletRequest request) {
    ActionContext context = new ActionContext(stack.getContext());
    ActionInvocation invocation = context.getActionInvocation();

    if (invocation == null) {
      ActionMapping mapping =
          mapper.getMapping(request, Dispatcher.getInstance().getConfigurationManager());

      if (mapping != null) {
        return mapping.getNamespace();
      } else {
        // well, if the ActionMapper can't tell us, and there is no existing action invocation,
        // let's just go with a default guess that the namespace is the last the path minus the
        // last part (/foo/bar/baz.xyz -> /foo/bar)

        String path = RequestUtils.getServletPath(request);
        return path.substring(0, path.lastIndexOf("/"));
      }
    } else {
      return invocation.getProxy().getNamespace();
    }
  }
  public void testIfActionMapperIsNullDontServiceAction() throws Exception {
    MockServletContext servletContext = new MockServletContext();
    MockFilterConfig filterConfig = new MockFilterConfig(servletContext);
    MockHttpServletRequest req = new MockHttpServletRequest(servletContext);
    MockHttpServletResponse res = new MockHttpServletResponse();
    MockFilterChain chain = new MockFilterChain();
    final NoOpDispatcher _dispatcher = new NoOpDispatcher(servletContext);
    ConfigurationManager confManager = new ConfigurationManager();
    confManager.setConfiguration(new DefaultConfiguration());
    _dispatcher.setConfigurationManager(confManager);
    Dispatcher.setInstance(_dispatcher);

    FilterDispatcher filter =
        new FilterDispatcher() {
          protected Dispatcher createDispatcher() {
            return _dispatcher;
          }
        };
    filter.init(filterConfig);
    filter.setActionMapper(null);
    filter.doFilter(req, res, chain);

    assertFalse(_dispatcher.serviceRequest);
  }
 /** Sets the request encoding and locale on the response */
 public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) {
   dispatcher.prepare(request, response);
 }
 /** Assigns the dispatcher to the dispatcher thread local */
 public void assignDispatcherToThread() {
   Dispatcher.setInstance(dispatcher);
 }