📄 wicketfilter.java
字号:
e.getMessage()); } if (filterPath == null) { log.info("Unable to parse filter mapping web.xml for " + filterConfig.getFilterName() + ". " + "Configure with init-param " + FILTER_MAPPING_PARAM + " if it is not \"/*\"."); } } } IWebApplicationFactory factory = getApplicationFactory(); // Construct WebApplication subclass webApplication = factory.createApplication(this); // Set this WicketFilter as the filter for the web application webApplication.setWicketFilter(this); // Store instance of this application object in servlet context to // make integration with outside world easier String contextKey = "wicket:" + filterConfig.getFilterName(); filterConfig.getServletContext().setAttribute(contextKey, webApplication); // set the application thread local in case initialization code uses it Application.set(webApplication); // Call internal init method of web application for default // initialization webApplication.internalInit(); // Call init method of web application webApplication.init(); // We initialize components here rather than in the constructor or // in the internal init, because in the init method class aliases // can be added, that would be used in installing resources in the // component. webApplication.initializeComponents(); // Give the application the option to log that it is started webApplication.logStarted(); portletOnlyFilter = Boolean.valueOf(filterConfig.getInitParameter(PORTLET_ONLY_FILTER)) .booleanValue(); if (isPortletContextAvailable(filterConfig)) { filterPortletContext = newWicketFilterPortletContext(); } if (filterPortletContext != null) { filterPortletContext.initFilter(filterConfig, webApplication); } } finally { Application.unset(); if (newClassLoader != previousClassLoader) { Thread.currentThread().setContextClassLoader(previousClassLoader); } } } protected boolean isPortletContextAvailable(FilterConfig config) throws ServletException { boolean detectPortletContext = false; String parameter = config.getInitParameter(DETECT_PORTLET_CONTEXT); if (parameter != null) { detectPortletContext = Boolean.valueOf(parameter).booleanValue(); } else { parameter = config.getServletContext().getInitParameter( DETECT_PORTLET_CONTEXT_FULL_NAME); if (parameter != null) { detectPortletContext = Boolean.valueOf(parameter).booleanValue(); } else { InputStream is = Thread.currentThread() .getContextClassLoader() .getResourceAsStream(WICKET_PORTLET_PROPERTIES); if (is != null) { try { Properties properties = new Properties(); properties.load(is); detectPortletContext = Boolean.valueOf( properties.getProperty(DETECT_PORTLET_CONTEXT_FULL_NAME, "false")) .booleanValue(); } catch (IOException e) { throw new ServletException( "Failed to load WicketPortlet.properties from classpath", e); } } } } if (detectPortletContext) { try { Class portletClass = Class.forName("javax.portlet.PortletContext"); return true; } catch (ClassNotFoundException e) { } } return false; } protected WicketFilterPortletContext newWicketFilterPortletContext() { return new WicketFilterPortletContext(); } protected void createRequestContext(WebRequest request, WebResponse response) { if (filterPortletContext == null || !filterPortletContext.createPortletRequestContext(request, response)) { new RequestContext(); } } private String getFilterPath(String filterName, InputStream is) throws ServletException { String prefix = servletMode ? "servlet" : "filter"; String mapping = prefix + "-mapping"; String name = prefix + "-name"; // Filter mappings look like this: // // <filter-mapping> <filter-name>WicketFilter</filter-name> // <url-pattern>/*</url-pattern> <...> <filter-mapping> try { ArrayList urlPatterns = new ArrayList(); XmlPullParser parser = new XmlPullParser(); parser.parse(is); while (true) { XmlTag elem; do { elem = (XmlTag)parser.nextTag(); } while (elem != null && (!(elem.getName().equals(mapping) && elem.isOpen()))); if (elem == null) { break; } String encounteredFilterName = null, urlPattern = null; do { elem = (XmlTag)parser.nextTag(); if (elem.isOpen()) { parser.setPositionMarker(); } else if (elem.isClose() && elem.getName().equals(name)) { encounteredFilterName = parser.getInputFromPositionMarker(elem.getPos()) .toString() .trim(); } else if (elem.isClose() && elem.getName().equals("url-pattern")) { urlPattern = parser.getInputFromPositionMarker(elem.getPos()) .toString() .trim(); } } while (urlPattern == null || encounteredFilterName == null); if (filterName.equals(encounteredFilterName)) { urlPatterns.add(urlPattern); } } String prefixUppered = Character.toUpperCase(prefix.charAt(0)) + prefix.substring(1); // By the time we get here, we have a list of urlPatterns we match // this filter against. // In all likelihood, we will only have one. If we have none, we // have an error. // If we have more than one, we pick the first one to use for any // 302 redirects that require absolute URLs. if (urlPatterns.size() == 0) { throw new IllegalArgumentException("Error initializing Wicket" + prefixUppered + " - you have no <" + mapping + "> element with a url-pattern that uses " + prefix + ": " + filterName); } String urlPattern = (String)urlPatterns.get(0); // Check for leading '/' and trailing '*'. if (!urlPattern.startsWith("/") || !urlPattern.endsWith("*")) { throw new IllegalArgumentException("<" + mapping + "> for Wicket" + prefixUppered + " \"" + filterName + "\" must start with '/' and end with '*'."); } // Strip trailing '*' and keep leading '/'. return stripWildcard(urlPattern); } catch (IOException e) { throw new ServletException("Error finding <" + prefix + "> " + filterName + " in web.xml", e); } catch (ParseException e) { throw new ServletException("Error finding <" + prefix + "> " + filterName + " in web.xml", e); } catch (ResourceStreamNotFoundException e) { throw new ServletException("Error finding <" + prefix + "> " + filterName + " in web.xml", e); } } /** * Is this a Wicket request? * * @param relativePath * The relativePath * @return True if this is a Wicket request */ private boolean isWicketRequest(String relativePath) { // default location, like // /wicket-examples/forminput/?wicket:interface=:0:::: // the relative path here is empty (wicket-examples is the web // application and the filter is mapped to /forminput/* if (relativePath.equals("")) { return true; } // Resources if (relativePath.startsWith(WebRequestCodingStrategy.RESOURCES_PATH_PREFIX)) { return true; } // Mounted page return webApplication.getRequestCycleProcessor() .getRequestCodingStrategy() .urlCodingStrategyForPath(relativePath) != null; } /** * If the response has not already a 'lastModified' header set and if 'lastModified' >= 0 than * set the response header accordingly. * * @param resp * @param lastModified */ private void maybeSetLastModified(final HttpServletResponse resp, final long lastModified) { if (resp.containsHeader("Last-Modified")) { return; } if (lastModified >= 0) { resp.setDateHeader("Last-Modified", lastModified); } } /** * Creates the web application factory instance. * * If no APP_FACT_PARAM is specified in web.xml ContextParamWebApplicationFactory will be used * by default. * * @see ContextParamWebApplicationFactory * * @return application factory instance */ protected IWebApplicationFactory getApplicationFactory() { final String appFactoryClassName = filterConfig.getInitParameter(APP_FACT_PARAM); if (appFactoryClassName == null) { // If no context param was specified we return the default factory return new ContextParamWebApplicationFactory(); } else { try { // Try to find the specified factory class final Class factoryClass = Thread.currentThread() .getContextClassLoader() .loadClass(appFactoryClassName); // Instantiate the factory return (IWebApplicationFactory)factoryClass.newInstance(); } catch (ClassCastException e) { throw new WicketRuntimeException("Application factory class " + appFactoryClassName + " must implement IWebApplicationFactory"); } catch (ClassNotFoundException e) { throw new WebApplicationFactoryCreationException(appFactoryClassName, e); } catch (InstantiationException e) { throw new WebApplicationFactoryCreationException(appFactoryClassName, e); } catch (IllegalAccessException e) { throw new WebApplicationFactoryCreationException(appFactoryClassName, e); } catch (SecurityException e) { throw new WebApplicationFactoryCreationException(appFactoryClassName, e); } } } /** * @return The class loader */ protected ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } protected String getFilterPath(HttpServletRequest request) { if (filterPath != null) { return filterPath; } if (servletMode) { return filterPath = request.getServletPath(); } String result; // Legacy migration check. // TODO: Remove this after 1.3 is released and everyone's upgraded. if (filterConfig.getInitParameter("filterPath") != null) { throw new WicketRuntimeException( "\nThe filterPath init-param for WicketFilter has been removed.\n" + "Please use a param called " + FILTER_MAPPING_PARAM + " with a value that exactly\n" + "matches that in the <url-pattern> element of your <filter-mapping> (e.g. \"/app/*\")."); } result = filterConfig.getInitParameter(FILTER_MAPPING_PARAM); if (result == null || result.equals("/*")) { return ""; } else if (!result.startsWith("/") || !result.endsWith("/*")) { throw new WicketRuntimeException("Your " + FILTER_MAPPING_PARAM + " must start with \"/\" and end with \"/*\". It is: " + result); } return filterPath = stripWildcard(result); } /** * Strip trailing '*' and keep leading '/' * * @param result * @return The stripped String */ private String stripWildcard(String result) { return result.substring(1, result.length() - 1); } /** * Gets the last modified time stamp for the given request. * * @param servletRequest * @return The last modified time stamp */ long getLastModified(final HttpServletRequest servletRequest) { final String pathInfo = getRelativePath(servletRequest); if (pathInfo.startsWith(WebRequestCodingStrategy.RESOURCES_PATH_PREFIX)) { final String resourceReferenceKey = pathInfo.substring(WebRequestCodingStrategy.RESOURCES_PATH_PREFIX.length()); Resource resource = null; boolean externalCall = !Application.exists(); try { // if called externally (i.e. WicketServlet) we need to set the thread local here // AND clean it up at the end of the request if (externalCall) { Application.set(webApplication); } // Try to find shared resource resource = webApplication.getSharedResources().get(resourceReferenceKey); // If resource found and it is cacheable if ((resource != null) && resource.isCacheable()) { final WebRequest request = webApplication.newWebRequest(servletRequest); // make the session available. Session.findOrCreate(request, new WebResponse()); // Set parameters from servlet request resource.setParameters(request.getParameterMap()); // Get resource stream IResourceStream stream = resource.getResourceStream(); // Get last modified time from stream Time time = stream.lastModifiedTime(); try { stream.close(); } catch (IOException e) { // ignore } return time != null ? time.getMilliseconds() : -1; } } catch (AbortException e) { return -1; } finally { if (resource != null) { resource.setParameters(null); } if (externalCall) { // Clean up thread local application if this was an external call // (if not, doFilter will clean it up) Application.unset(); RequestContext.unset(); } if (Session.exists()) { Session.unset(); } } } return -1; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -