org.springframework.web.servlet.view

Class RedirectView

  • All Implemented Interfaces:
    Aware, BeanNameAware, InitializingBean, ApplicationContextAware, ServletContextAware, SmartView, View


    public class RedirectView
    extends AbstractUrlBasedView
    implements SmartView
    View that redirects to an absolute, context relative, or current request relative URL. The URL may be a URI template in which case the URI template variables will be replaced with values available in the model. By default all primitive model attributes (or collections thereof) are exposed as HTTP query parameters (assuming they've not been used as URI template variables), but this behavior can be changed by overriding the isEligibleProperty(String, Object) method.

    A URL for this view is supposed to be a HTTP redirect URL, i.e. suitable for HttpServletResponse's sendRedirect method, which is what actually does the redirect if the HTTP 1.0 flag is on, or via sending back an HTTP 303 code - if the HTTP 1.0 compatibility flag is off.

    Note that while the default value for the "contextRelative" flag is off, you will probably want to almost always set it to true. With the flag off, URLs starting with "/" are considered relative to the web server root, while with the flag on, they are considered relative to the web application root. Since most web applications will never know or care what their context path actually is, they are much better off setting this flag to true, and submitting paths which are to be considered relative to the web application root.

    NOTE when using this redirect view in a Portlet environment: Make sure that your controller respects the Portlet sendRedirect constraints.

    Author:
    Rod Johnson, Juergen Hoeller, Colin Sampaleanu, Sam Brannen, Arjen Poutsma, Rossen Stoyanchev
    See Also:
    setContextRelative(boolean), setHttp10Compatible(boolean), setExposeModelAttributes(boolean), HttpServletResponse.sendRedirect(java.lang.String)
    • Constructor Detail

      • RedirectView

        public RedirectView()
        Constructor for use as a bean.
      • RedirectView

        public RedirectView(java.lang.String url)
        Create a new RedirectView with the given URL.

        The given URL will be considered as relative to the web server, not as relative to the current ServletContext.

        Parameters:
        url - the URL to redirect to
        See Also:
        RedirectView(String, boolean)
      • RedirectView

        public RedirectView(java.lang.String url,
                            boolean contextRelative)
        Create a new RedirectView with the given URL.
        Parameters:
        url - the URL to redirect to
        contextRelative - whether to interpret the given URL as relative to the current ServletContext
      • RedirectView

        public RedirectView(java.lang.String url,
                            boolean contextRelative,
                            boolean http10Compatible)
        Create a new RedirectView with the given URL.
        Parameters:
        url - the URL to redirect to
        contextRelative - whether to interpret the given URL as relative to the current ServletContext
        http10Compatible - whether to stay compatible with HTTP 1.0 clients
      • RedirectView

        public RedirectView(java.lang.String url,
                            boolean contextRelative,
                            boolean http10Compatible,
                            boolean exposeModelAttributes)
        Create a new RedirectView with the given URL.
        Parameters:
        url - the URL to redirect to
        contextRelative - whether to interpret the given URL as relative to the current ServletContext
        http10Compatible - whether to stay compatible with HTTP 1.0 clients
        exposeModelAttributes - whether or not model attributes should be exposed as query parameters
    • Method Detail

      • setContextRelative

        public void setContextRelative(boolean contextRelative)
        Set whether to interpret a given URL that starts with a slash ("/") as relative to the current ServletContext, i.e. as relative to the web application root.

        Default is "false": A URL that starts with a slash will be interpreted as absolute, i.e. taken as-is. If "true", the context path will be prepended to the URL in such a case.

        See Also:
        HttpServletRequest.getContextPath()
      • setHttp10Compatible

        public void setHttp10Compatible(boolean http10Compatible)
        Set whether to stay compatible with HTTP 1.0 clients.

        In the default implementation, this will enforce HTTP status code 302 in any case, i.e. delegate to HttpServletResponse.sendRedirect. Turning this off will send HTTP status code 303, which is the correct code for HTTP 1.1 clients, but not understood by HTTP 1.0 clients.

        Many HTTP 1.1 clients treat 302 just like 303, not making any difference. However, some clients depend on 303 when redirecting after a POST request; turn this flag off in such a scenario.

        See Also:
        HttpServletResponse.sendRedirect(java.lang.String)
      • setExposeModelAttributes

        public void setExposeModelAttributes(boolean exposeModelAttributes)
        Set the exposeModelAttributes flag which denotes whether or not model attributes should be exposed as HTTP query parameters.

        Defaults to true.

      • setEncodingScheme

        public void setEncodingScheme(java.lang.String encodingScheme)
        Set the encoding scheme for this view.

        Default is the request's encoding scheme (which is ISO-8859-1 if not specified otherwise).

      • setStatusCode

        public void setStatusCode(HttpStatus statusCode)
        Set the status code for this view.

        Default is to send 302/303, depending on the value of the http10Compatible flag.

      • setExpandUriTemplateVariables

        public void setExpandUriTemplateVariables(boolean expandUriTemplateVariables)
        Whether to treat the redirect URL as a URI template. Set this flag to false if the redirect URL contains open and close curly braces "{", "}" and you don't want them interpreted as URI variables.

        Defaults to true.

      • setPropagateQueryParams

        public void setPropagateQueryParams(boolean propagateQueryParams)
        When set to true the query string of the current URL is appended and thus propagated through to the redirected URL.

        Defaults to false.

        Since:
        4.1
      • isPropagateQueryProperties

        public boolean isPropagateQueryProperties()
        Whether to propagate the query params of the current URL.
        Since:
        4.1
      • setHosts

        public void setHosts(@Nullable
                             java.lang.String... hosts)
        Configure one or more hosts associated with the application. All other hosts will be considered external hosts.

        In effect, this property provides a way turn off encoding via HttpServletResponse.encodeRedirectURL(java.lang.String) for URLs that have a host and that host is not listed as a known host.

        If not set (the default) all URLs are encoded through the response.

        Parameters:
        hosts - one or more application hosts
        Since:
        4.3
      • getHosts

        @Nullable
        public java.lang.String[] getHosts()
        Return the configured application hosts.
        Since:
        4.3
      • isRedirectView

        public boolean isRedirectView()
        Returns "true" indicating this view performs a redirect.
        Specified by:
        isRedirectView in interface SmartView
      • createTargetUrl

        protected final java.lang.String createTargetUrl(java.util.Map<java.lang.String,java.lang.Object> model,
                                                         HttpServletRequest request)
                                                  throws java.io.UnsupportedEncodingException
        Create the target URL by checking if the redirect string is a URI template first, expanding it with the given model, and then optionally appending simple type model attributes as query String parameters.
        Throws:
        java.io.UnsupportedEncodingException
      • replaceUriTemplateVariables

        protected java.lang.StringBuilder replaceUriTemplateVariables(java.lang.String targetUrl,
                                                                      java.util.Map<java.lang.String,java.lang.Object> model,
                                                                      java.util.Map<java.lang.String,java.lang.String> currentUriVariables,
                                                                      java.lang.String encodingScheme)
                                                               throws java.io.UnsupportedEncodingException
        Replace URI template variables in the target URL with encoded model attributes or URI variables from the current request. Model attributes referenced in the URL are removed from the model.
        Parameters:
        targetUrl - the redirect URL
        model - a Map that contains model attributes
        currentUriVariables - current request URI variables to use
        encodingScheme - the encoding scheme to use
        Throws:
        java.io.UnsupportedEncodingException - if string encoding failed
      • appendCurrentQueryParams

        protected void appendCurrentQueryParams(java.lang.StringBuilder targetUrl,
                                                HttpServletRequest request)
        Append the query string of the current request to the target redirect URL.
        Parameters:
        targetUrl - the StringBuilder to append the properties to
        request - the current request
        Since:
        4.1
      • appendQueryProperties

        protected void appendQueryProperties(java.lang.StringBuilder targetUrl,
                                             java.util.Map<java.lang.String,java.lang.Object> model,
                                             java.lang.String encodingScheme)
                                      throws java.io.UnsupportedEncodingException
        Append query properties to the redirect URL. Stringifies, URL-encodes and formats model attributes as query properties.
        Parameters:
        targetUrl - the StringBuilder to append the properties to
        model - a Map that contains model attributes
        encodingScheme - the encoding scheme to use
        Throws:
        java.io.UnsupportedEncodingException - if string encoding failed
        See Also:
        queryProperties(java.util.Map<java.lang.String, java.lang.Object>)
      • isEligibleProperty

        protected boolean isEligibleProperty(java.lang.String key,
                                             @Nullable
                                             java.lang.Object value)
        Determine whether the given model element should be exposed as a query property.

        The default implementation considers Strings and primitives as eligible, and also arrays and Collections/Iterables with corresponding elements. This can be overridden in subclasses.

        Parameters:
        key - the key of the model element
        value - the value of the model element
        Returns:
        whether the element is eligible as query property
      • isEligibleValue

        protected boolean isEligibleValue(@Nullable
                                          java.lang.Object value)
        Determine whether the given model element value is eligible for exposure.

        The default implementation considers primitives, Strings, Numbers, Dates, URIs, URLs and Locale objects as eligible. This can be overridden in subclasses.

        Parameters:
        value - the model element value
        Returns:
        whether the element value is eligible
        See Also:
        BeanUtils.isSimpleValueType(java.lang.Class<?>)
      • urlEncode

        protected java.lang.String urlEncode(java.lang.String input,
                                             java.lang.String encodingScheme)
                                      throws java.io.UnsupportedEncodingException
        URL-encode the given input String with the given encoding scheme.

        The default implementation uses URLEncoder.encode(input, enc).

        Parameters:
        input - the unencoded input String
        encodingScheme - the encoding scheme
        Returns:
        the encoded output String
        Throws:
        java.io.UnsupportedEncodingException - if thrown by the JDK URLEncoder
        See Also:
        URLEncoder.encode(String, String), URLEncoder.encode(String)
      • updateTargetUrl

        protected java.lang.String updateTargetUrl(java.lang.String targetUrl,
                                                   java.util.Map<java.lang.String,java.lang.Object> model,
                                                   HttpServletRequest request,
                                                   HttpServletResponse response)
        Find the registered RequestDataValueProcessor, if any, and allow it to update the redirect target URL.
        Parameters:
        targetUrl - the given redirect URL
        Returns:
        the updated URL or the same as URL as the one passed in
      • sendRedirect

        protected void sendRedirect(HttpServletRequest request,
                                    HttpServletResponse response,
                                    java.lang.String targetUrl,
                                    boolean http10Compatible)
                             throws java.io.IOException
        Send a redirect back to the HTTP client.
        Parameters:
        request - current HTTP request (allows for reacting to request method)
        response - current HTTP response (for sending response headers)
        targetUrl - the target URL to redirect to
        http10Compatible - whether to stay compatible with HTTP 1.0 clients
        Throws:
        java.io.IOException - if thrown by response methods
      • isRemoteHost

        protected boolean isRemoteHost(java.lang.String targetUrl)
        Whether the given targetUrl has a host that is a "foreign" system in which case HttpServletResponse.encodeRedirectURL(java.lang.String) will not be applied. This method returns true if the setHosts(String[]) property is configured and the target URL has a host that does not match.
        Parameters:
        targetUrl - the target redirect URL
        Returns:
        true the target URL has a remote host, false if it the URL does not have a host or the "host" property is not configured.
        Since:
        4.3
      • getHttp11StatusCode

        protected HttpStatus getHttp11StatusCode(HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 java.lang.String targetUrl)
        Determines the status code to use for HTTP 1.1 compatible requests.

        The default implementation returns the statusCode property if set, or the value of the View.RESPONSE_STATUS_ATTRIBUTE attribute. If neither are set, it defaults to HttpStatus.SEE_OTHER (303).

        Parameters:
        request - the request to inspect
        response - the servlet response
        targetUrl - the target URL
        Returns:
        the response status