code: public static ApplicationContext getWebApplicationContext(
              PortletRequest request, PortletContext portletContext) throws IllegalStateException {
  
          PortletApplicationContext portletApplicationContext = (PortletApplicationContext) request.getAttribute(
                  ContribDispatcherPortlet.PORTLET_APPLICATION_CONTEXT_ATTRIBUTE);
          if (portletApplicationContext != null) {
              return portletApplicationContext;
          }
          
          if (portletContext == null) {
              throw new IllegalStateException("No PortletApplicationContext found: not in a DispatcherPortlet request?");
          }
          portletApplicationContext = PortletApplicationContextUtils2.getPortletApplicationContext(portletContext);
          if (portletApplicationContext != null) {
              return portletApplicationContext;
          }
  
          return PortletApplicationContextUtils.getRequiredWebApplicationContext(portletContext);
      }
docs: Look for the PortletApplicationContext associated with the DispatcherPortlet
  that has initiated request processing, for the global portlet context if none
  was found associated with the current request, and for the global context if no
  global portlet context was found. This method is useful to
  allow components outside the framework, such as JSP tag handlers,
  to access the most specific application context available.
  
  @param request current portlet request
  @param portletContext current portlet context
  @return the request-specific PortletApplicationContext, or the global one
  if no request-specific context has been found
  @throws java.lang.IllegalStateException if neither a portlet-specific nor a
  global context has been found