类 WebUtils


  • public abstract class WebUtils
    extends Object
    Miscellaneous utilities for web applications. Used by various framework classes.
    作者:
    Rod Johnson, Juergen Hoeller, Sebastien Deleuze
    • 构造器详细资料

    • 方法详细资料

      • isDefaultHtmlEscape

        @Deprecated
        public static boolean isDefaultHtmlEscape​(ServletContext servletContext)
        已过时。
        Return whether default HTML escaping is enabled for the web application, i.e. the value of the "defaultHtmlEscape" context-param in web.xml (if any). Falls back to false in case of no explicit default given.
        参数:
        servletContext - the servlet context of the web application
        返回:
        whether default HTML escaping is enabled (default is false)
      • getDefaultHtmlEscape

        public static Boolean getDefaultHtmlEscape​(ServletContext servletContext)
        Return whether default HTML escaping is enabled for the web application, i.e. the value of the "defaultHtmlEscape" context-param in web.xml (if any).

        This method differentiates between no param specified at all and an actual boolean value specified, allowing to have a context-specific default in case of no setting at the global level.

        参数:
        servletContext - the servlet context of the web application
        返回:
        whether default HTML escaping is enabled for the given application (null = no explicit default)
      • getResponseEncodedHtmlEscape

        public static Boolean getResponseEncodedHtmlEscape​(ServletContext servletContext)
        Return whether response encoding should be used when HTML escaping characters, thus only escaping XML markup significant characters with UTF-* encodings. This option is enabled for the web application with a ServletContext param, i.e. the value of the "responseEncodedHtmlEscape" context-param in web.xml (if any).

        This method differentiates between no param specified at all and an actual boolean value specified, allowing to have a context-specific default in case of no setting at the global level.

        参数:
        servletContext - the servlet context of the web application
        返回:
        whether response encoding is to be used for HTML escaping (null = no explicit default)
        从以下版本开始:
        4.1.2
      • getTempDir

        public static File getTempDir​(ServletContext servletContext)
        Return the temporary directory for the current web application, as provided by the servlet container.
        参数:
        servletContext - the servlet context of the web application
        返回:
        the File representing the temporary directory
      • getRealPath

        public static String getRealPath​(ServletContext servletContext,
                                         String path)
                                  throws FileNotFoundException
        Return the real path of the given path within the web application, as provided by the servlet container.

        Prepends a slash if the path does not already start with a slash, and throws a FileNotFoundException if the path cannot be resolved to a resource (in contrast to ServletContext's getRealPath, which returns null).

        参数:
        servletContext - the servlet context of the web application
        path - the path within the web application
        返回:
        the corresponding real path
        抛出:
        FileNotFoundException - if the path cannot be resolved to a resource
        另请参阅:
        ServletContext.getRealPath(java.lang.String)
      • getSessionId

        public static String getSessionId​(HttpServletRequest request)
        Determine the session id of the given request, if any.
        参数:
        request - current HTTP request
        返回:
        the session id, or null if none
      • getSessionAttribute

        public static Object getSessionAttribute​(HttpServletRequest request,
                                                 String name)
        Check the given request for a session attribute of the given name. Returns null if there is no session or if the session has no such attribute. Does not create a new session if none has existed before!
        参数:
        request - current HTTP request
        name - the name of the session attribute
        返回:
        the value of the session attribute, or null if not found
      • getRequiredSessionAttribute

        public static Object getRequiredSessionAttribute​(HttpServletRequest request,
                                                         String name)
                                                  throws IllegalStateException
        Check the given request for a session attribute of the given name. Throws an exception if there is no session or if the session has no such attribute. Does not create a new session if none has existed before!
        参数:
        request - current HTTP request
        name - the name of the session attribute
        返回:
        the value of the session attribute, or null if not found
        抛出:
        IllegalStateException - if the session attribute could not be found
      • setSessionAttribute

        public static void setSessionAttribute​(HttpServletRequest request,
                                               String name,
                                               Object value)
        Set the session attribute with the given name to the given value. Removes the session attribute if value is null, if a session existed at all. Does not create a new session if not necessary!
        参数:
        request - current HTTP request
        name - the name of the session attribute
        value - the value of the session attribute
      • getOrCreateSessionAttribute

        @Deprecated
        public static Object getOrCreateSessionAttribute​(HttpSession session,
                                                         String name,
                                                         Class<?> clazz)
                                                  throws IllegalArgumentException
        已过时。
        as of Spring 4.3.2, in favor of custom code for such purposes
        Get the specified session attribute, creating and setting a new attribute if no existing found. The given class needs to have a public no-arg constructor. Useful for on-demand state objects in a web tier, like shopping carts.
        参数:
        session - current HTTP session
        name - the name of the session attribute
        clazz - the class to instantiate for a new attribute
        返回:
        the value of the session attribute, newly created if not found
        抛出:
        IllegalArgumentException - if the session attribute could not be instantiated
      • getSessionMutex

        public static Object getSessionMutex​(HttpSession session)
        Return the best available mutex for the given session: that is, an object to synchronize on for the given session.

        Returns the session mutex attribute if available; usually, this means that the HttpSessionMutexListener needs to be defined in web.xml. Falls back to the HttpSession itself if no mutex attribute found.

        The session mutex is guaranteed to be the same object during the entire lifetime of the session, available under the key defined by the SESSION_MUTEX_ATTRIBUTE constant. It serves as a safe reference to synchronize on for locking on the current session.

        In many cases, the HttpSession reference itself is a safe mutex as well, since it will always be the same object reference for the same active logical session. However, this is not guaranteed across different servlet containers; the only 100% safe way is a session mutex.

        参数:
        session - the HttpSession to find a mutex for
        返回:
        the mutex object (never null)
        另请参阅:
        SESSION_MUTEX_ATTRIBUTE, HttpSessionMutexListener
      • getNativeRequest

        public static <T> T getNativeRequest​(ServletRequest request,
                                             Class<T> requiredType)
        Return an appropriate request object of the specified type, if available, unwrapping the given request as far as necessary.
        参数:
        request - the servlet request to introspect
        requiredType - the desired type of request object
        返回:
        the matching request object, or null if none of that type is available
      • getNativeResponse

        public static <T> T getNativeResponse​(ServletResponse response,
                                              Class<T> requiredType)
        Return an appropriate response object of the specified type, if available, unwrapping the given response as far as necessary.
        参数:
        response - the servlet response to introspect
        requiredType - the desired type of response object
        返回:
        the matching response object, or null if none of that type is available
      • isIncludeRequest

        public static boolean isIncludeRequest​(ServletRequest request)
        Determine whether the given request is an include request, that is, not a top-level HTTP request coming in from the outside.

        Checks the presence of the "javax.servlet.include.request_uri" request attribute. Could check any request attribute that is only present in an include request.

        参数:
        request - current servlet request
        返回:
        whether the given request is an include request
      • exposeErrorRequestAttributes

        public static void exposeErrorRequestAttributes​(HttpServletRequest request,
                                                        Throwable ex,
                                                        String servletName)
        Expose the Servlet spec's error attributes as HttpServletRequest attributes under the keys defined in the Servlet 2.3 specification, for error pages that are rendered directly rather than through the Servlet container's error page resolution: javax.servlet.error.status_code, javax.servlet.error.exception_type, javax.servlet.error.message, javax.servlet.error.exception, javax.servlet.error.request_uri, javax.servlet.error.servlet_name.

        Does not override values if already present, to respect attribute values that have been exposed explicitly before.

        Exposes status code 200 by default. Set the "javax.servlet.error.status_code" attribute explicitly (before or after) in order to expose a different status code.

        参数:
        request - current servlet request
        ex - the exception encountered
        servletName - the name of the offending servlet
      • clearErrorRequestAttributes

        public static void clearErrorRequestAttributes​(HttpServletRequest request)
        Clear the Servlet spec's error attributes as HttpServletRequest attributes under the keys defined in the Servlet 2.3 specification: javax.servlet.error.status_code, javax.servlet.error.exception_type, javax.servlet.error.message, javax.servlet.error.exception, javax.servlet.error.request_uri, javax.servlet.error.servlet_name.
        参数:
        request - current servlet request
      • exposeRequestAttributes

        @Deprecated
        public static void exposeRequestAttributes​(ServletRequest request,
                                                   Map<String,​?> attributes)
        已过时。
        as of Spring 4.3.2, in favor of custom code for such purposes
        Expose the given Map as request attributes, using the keys as attribute names and the values as corresponding attribute values. Keys need to be Strings.
        参数:
        request - current HTTP request
        attributes - the attributes Map
      • getCookie

        public static Cookie getCookie​(HttpServletRequest request,
                                       String name)
        Retrieve the first cookie with the given name. Note that multiple cookies can have the same name but different paths or domains.
        参数:
        request - current servlet request
        name - cookie name
        返回:
        the first cookie with the given name, or null if none is found
      • hasSubmitParameter

        public static boolean hasSubmitParameter​(ServletRequest request,
                                                 String name)
        Check if a specific input type="submit" parameter was sent in the request, either via a button (directly with name) or via an image (name + ".x" or name + ".y").
        参数:
        request - current HTTP request
        name - name of the parameter
        返回:
        if the parameter was sent
        另请参阅:
        SUBMIT_IMAGE_SUFFIXES
      • findParameterValue

        public static String findParameterValue​(ServletRequest request,
                                                String name)
        Obtain a named parameter from the given request parameters.

        See findParameterValue(java.util.Map, String) for a description of the lookup algorithm.

        参数:
        request - current HTTP request
        name - the logical name of the request parameter
        返回:
        the value of the parameter, or null if the parameter does not exist in given request
      • findParameterValue

        public static String findParameterValue​(Map<String,​?> parameters,
                                                String name)
        Obtain a named parameter from the given request parameters.

        This method will try to obtain a parameter value using the following algorithm:

        1. Try to get the parameter value using just the given logical name. This handles parameters of the form logicalName = value. For normal parameters, e.g. submitted using a hidden HTML form field, this will return the requested value.
        2. Try to obtain the parameter value from the parameter name, where the parameter name in the request is of the form logicalName_value = xyz with "_" being the configured delimiter. This deals with parameter values submitted using an HTML form submit button.
        3. If the value obtained in the previous step has a ".x" or ".y" suffix, remove that. This handles cases where the value was submitted using an HTML form image button. In this case the parameter in the request would actually be of the form logicalName_value.x = 123.
        参数:
        parameters - the available parameter map
        name - the logical name of the request parameter
        返回:
        the value of the parameter, or null if the parameter does not exist in given request
      • getTargetPage

        @Deprecated
        public static int getTargetPage​(ServletRequest request,
                                        String paramPrefix,
                                        int currentPage)
        已过时。
        as of Spring 4.3.2, in favor of custom code for such purposes
        Return the target page specified in the request.
        参数:
        request - current servlet request
        paramPrefix - the parameter prefix to check for (e.g. "_target" for parameters like "_target1" or "_target2")
        currentPage - the current page, to be returned as fallback if no target page specified
        返回:
        the page specified in the request, or current page if not found
      • extractFilenameFromUrlPath

        @Deprecated
        public static String extractFilenameFromUrlPath​(String urlPath)
        已过时。
        as of Spring 4.3.2, in favor of custom code for such purposes
        Extract the URL filename from the given request URL path. Correctly resolves nested paths such as "/products/view.html" as well.
        参数:
        urlPath - the request URL path (e.g. "/index.html")
        返回:
        the extracted URI filename (e.g. "index")
      • extractFullFilenameFromUrlPath

        @Deprecated
        public static String extractFullFilenameFromUrlPath​(String urlPath)
        已过时。
        as of Spring 4.3.2, in favor of custom code for such purposes (or UriUtils.extractFileExtension(java.lang.String) for the file extension use case)
        Extract the full URL filename (including file extension) from the given request URL path. Correctly resolve nested paths such as "/products/view.html" and remove any path and or query parameters.
        参数:
        urlPath - the request URL path (e.g. "/products/index.html")
        返回:
        the extracted URI filename (e.g. "index.html")
      • parseMatrixVariables

        public static MultiValueMap<String,​StringparseMatrixVariables​(String matrixVariables)
        Parse the given string with matrix variables. An example string would look like this "q1=a;q1=b;q2=a,b,c". The resulting map would contain keys "q1" and "q2" with values ["a","b"] and ["a","b","c"] respectively.
        参数:
        matrixVariables - the unparsed matrix variables string
        返回:
        a map with matrix variable names and values (never null)
        从以下版本开始:
        3.2
      • isValidOrigin

        public static boolean isValidOrigin​(HttpRequest request,
                                            Collection<String> allowedOrigins)
        Check the given request origin against a list of allowed origins. A list containing "*" means that all origins are allowed. An empty list means only same origin is allowed.

        Note: this method may use values from "Forwarded" (RFC 7239), "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" headers, if present, in order to reflect the client-originated address. Consider using the ForwardedHeaderFilter in order to choose from a central place whether to extract and use, or to discard such headers. See the Spring Framework reference for more on this filter.

        返回:
        true if the request origin is valid, false otherwise
        从以下版本开始:
        4.1.5
        另请参阅:
        RFC 6454: The Web Origin Concept
      • isSameOrigin

        public static boolean isSameOrigin​(HttpRequest request)
        Check if the request is a same-origin one, based on Origin, Host, Forwarded, X-Forwarded-Proto, X-Forwarded-Host and