Class RedirectView
- All Implemented Interfaces:
Aware
,BeanNameAware
,InitializingBean
,ApplicationContextAware
,ServletContextAware
,SmartView
,View
isEligibleProperty(String, Object)
method.
A URL for this view is supposed to be an 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:
-
Field Summary
Fields inherited from class org.springframework.web.servlet.view.AbstractView
DEFAULT_CONTENT_TYPE
Fields inherited from class org.springframework.context.support.ApplicationObjectSupport
logger
Fields inherited from interface org.springframework.web.servlet.View
PATH_VARIABLES, RESPONSE_STATUS_ATTRIBUTE, SELECTED_CONTENT_TYPE
-
Constructor Summary
ConstructorDescriptionConstructor for use as a bean.RedirectView
(String url) Create a new RedirectView with the given URL.RedirectView
(String url, boolean contextRelative) Create a new RedirectView with the given URL.RedirectView
(String url, boolean contextRelative, boolean http10Compatible) Create a new RedirectView with the given URL.RedirectView
(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes) Create a new RedirectView with the given URL. -
Method Summary
Modifier and TypeMethodDescriptionprotected void
appendCurrentQueryParams
(StringBuilder targetUrl, HttpServletRequest request) Append the query string of the current request to the target redirect URL.protected void
appendQueryProperties
(StringBuilder targetUrl, Map<String, Object> model, String encodingScheme) Append query properties to the redirect URL.protected final String
createTargetUrl
(Map<String, Object> model, HttpServletRequest request) 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.String[]
getHosts()
Return the configured application hosts.protected HttpStatusCode
getHttp11StatusCode
(HttpServletRequest request, HttpServletResponse response, String targetUrl) Determines the status code to use for HTTP 1.1 compatible requests.protected boolean
An ApplicationContext is not strictly required for RedirectView.protected boolean
isEligibleProperty
(String key, Object value) Determine whether the given model element should be exposed as a query property.protected boolean
isEligibleValue
(Object value) Determine whether the given model element value is eligible for exposure.boolean
Whether to propagate the query params of the current URL.boolean
Returns "true" indicating this view performs a redirect.protected boolean
isRemoteHost
(String targetUrl) Whether the given targetUrl has a host that is a "foreign" system in which caseHttpServletResponse.encodeRedirectURL(java.lang.String)
will not be applied.queryProperties
(Map<String, Object> model) Determine name-value pairs for query strings, which will be stringified, URL-encoded and formatted byappendQueryProperties(java.lang.StringBuilder, java.util.Map<java.lang.String, java.lang.Object>, java.lang.String)
.protected void
renderMergedOutputModel
(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) Convert model to request parameters and redirect to the given URL.protected StringBuilder
replaceUriTemplateVariables
(String targetUrl, Map<String, Object> model, Map<String, String> currentUriVariables, String encodingScheme) Replace URI template variables in the target URL with encoded model attributes or URI variables from the current request.protected void
sendRedirect
(HttpServletRequest request, HttpServletResponse response, String targetUrl, boolean http10Compatible) Send a redirect back to the HTTP client.void
setContextRelative
(boolean contextRelative) Set whether to interpret a given URL that starts with a slash ("/") as relative to the current ServletContext, i.e.void
setEncodingScheme
(String encodingScheme) Set the encoding scheme for this view.void
setExpandUriTemplateVariables
(boolean expandUriTemplateVariables) Whether to treat the redirect URL as a URI template.void
setExposeModelAttributes
(boolean exposeModelAttributes) Set theexposeModelAttributes
flag which denotes whether model attributes should be exposed as HTTP query parameters.void
Configure one or more hosts associated with the application.void
setHttp10Compatible
(boolean http10Compatible) Set whether to stay compatible with HTTP 1.0 clients.void
setPropagateQueryParams
(boolean propagateQueryParams) When set totrue
the query string of the current URL is appended and thus propagated through to the redirected URL.void
setStatusCode
(HttpStatusCode statusCode) Set the status code for this view.protected String
updateTargetUrl
(String targetUrl, Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) Find the registeredRequestDataValueProcessor
, if any, and allow it to update the redirect target URL.protected String
URL-encode the given input String with the given encoding scheme.Methods inherited from class org.springframework.web.servlet.view.AbstractUrlBasedView
afterPropertiesSet, checkResource, getUrl, isUrlRequired, setUrl, toString
Methods inherited from class org.springframework.web.servlet.view.AbstractView
addStaticAttribute, createMergedOutputModel, createRequestContext, createTemporaryOutputStream, exposeModelAsRequestAttributes, formatViewName, generatesDownloadContent, getAttributesMap, getBeanName, getContentType, getRequestContextAttribute, getRequestToExpose, getStaticAttributes, isExposePathVariables, prepareResponse, render, setAttributes, setAttributesCSV, setAttributesMap, setBeanName, setContentType, setExposeContextBeansAsAttributes, setExposedContextBeanNames, setExposePathVariables, setRequestContextAttribute, setResponseContentType, writeToResponse
Methods inherited from class org.springframework.web.context.support.WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, initServletContext, setServletContext
Methods inherited from class org.springframework.context.support.ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, initApplicationContext, obtainApplicationContext, requiredContextClass, setApplicationContext
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.springframework.web.servlet.View
getContentType, render
-
Constructor Details
-
RedirectView
public RedirectView()Constructor for use as a bean. -
RedirectView
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
Create a new RedirectView with the given URL.- Parameters:
url
- the URL to redirect tocontextRelative
- whether to interpret the given URL as relative to the current ServletContext
-
RedirectView
Create a new RedirectView with the given URL.- Parameters:
url
- the URL to redirect tocontextRelative
- whether to interpret the given URL as relative to the current ServletContexthttp10Compatible
- whether to stay compatible with HTTP 1.0 clients
-
RedirectView
public RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes) Create a new RedirectView with the given URL.- Parameters:
url
- the URL to redirect tocontextRelative
- whether to interpret the given URL as relative to the current ServletContexthttp10Compatible
- whether to stay compatible with HTTP 1.0 clientsexposeModelAttributes
- whether model attributes should be exposed as query parameters
-
-
Method Details
-
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:
-
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.
-
setExposeModelAttributes
public void setExposeModelAttributes(boolean exposeModelAttributes) Set theexposeModelAttributes
flag which denotes whether model attributes should be exposed as HTTP query parameters.Defaults to
true
. -
setEncodingScheme
Set the encoding scheme for this view.Default is the request's encoding scheme (which is ISO-8859-1 if not specified otherwise).
-
setStatusCode
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 tofalse
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 totrue
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
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
Return the configured application hosts.- Since:
- 4.3
-
isRedirectView
public boolean isRedirectView()Returns "true" indicating this view performs a redirect.- Specified by:
isRedirectView
in interfaceSmartView
-
isContextRequired
protected boolean isContextRequired()An ApplicationContext is not strictly required for RedirectView.- Overrides:
isContextRequired
in classWebApplicationObjectSupport
- See Also:
-
renderMergedOutputModel
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOExceptionConvert model to request parameters and redirect to the given URL.- Specified by:
renderMergedOutputModel
in classAbstractView
- Parameters:
model
- combined output Map (nevernull
), with dynamic values taking precedence over static attributesrequest
- current HTTP requestresponse
- current HTTP response- Throws:
IOException
- See Also:
-
createTargetUrl
protected final String createTargetUrl(Map<String, Object> model, HttpServletRequest request) throws UnsupportedEncodingExceptionCreate 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:
UnsupportedEncodingException
-
replaceUriTemplateVariables
protected StringBuilder replaceUriTemplateVariables(String targetUrl, Map<String, Object> model, Map<String, throws UnsupportedEncodingExceptionString> currentUriVariables, String encodingScheme) 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 URLmodel
- a Map that contains model attributescurrentUriVariables
- current request URI variables to useencodingScheme
- the encoding scheme to use- Throws:
UnsupportedEncodingException
- if string encoding failed
-
appendCurrentQueryParams
Append the query string of the current request to the target redirect URL.- Parameters:
targetUrl
- the StringBuilder to append the properties torequest
- the current request- Since:
- 4.1
-
appendQueryProperties
protected void appendQueryProperties(StringBuilder targetUrl, Map<String, Object> model, String encodingScheme) throws UnsupportedEncodingExceptionAppend query properties to the redirect URL. Stringifies, URL-encodes and formats model attributes as query properties.- Parameters:
targetUrl
- the StringBuilder to append the properties tomodel
- a Map that contains model attributesencodingScheme
- the encoding scheme to use- Throws:
UnsupportedEncodingException
- if string encoding failed- See Also:
-
queryProperties
Determine name-value pairs for query strings, which will be stringified, URL-encoded and formatted byappendQueryProperties(java.lang.StringBuilder, java.util.Map<java.lang.String, java.lang.Object>, java.lang.String)
.This implementation filters the model through checking
isEligibleProperty(String, Object)
for each element, by default accepting Strings, primitives and primitive wrappers only.- Parameters:
model
- the original model Map- Returns:
- the filtered Map of eligible query properties
- See Also:
-
isEligibleProperty
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 elementvalue
- the value of the model element- Returns:
- whether the element is eligible as query property
-
isEligibleValue
Determine whether the given model element value is eligible for exposure.The default implementation considers primitives, strings, numbers, dates, URIs, URLs etc as eligible, according to
BeanUtils.isSimpleValueType(java.lang.Class<?>)
. This can be overridden in subclasses.- Parameters:
value
- the model element value- Returns:
- whether the element value is eligible
- See Also:
-
urlEncode
URL-encode the given input String with the given encoding scheme.The default implementation uses
URLEncoder.encode(input, enc)
.- Parameters:
input
- the unencoded input StringencodingScheme
- the encoding scheme- Returns:
- the encoded output String
- Throws:
UnsupportedEncodingException
- if thrown by the JDK URLEncoder- See Also:
-
updateTargetUrl
protected String updateTargetUrl(String targetUrl, Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) Find the registeredRequestDataValueProcessor
, 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, String targetUrl, boolean http10Compatible) throws 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 tohttp10Compatible
- whether to stay compatible with HTTP 1.0 clients- Throws:
IOException
- if thrown by response methods
-
isRemoteHost
Whether the given targetUrl has a host that is a "foreign" system in which caseHttpServletResponse.encodeRedirectURL(java.lang.String)
will not be applied.This method returns
true
if thesetHosts(String[])
property is configured and the target URL has a host that does not match.- Parameters:
targetUrl
- the target redirect URL- Returns:
true
if the target URL has a remote host,false
if the URL does not have a host or the "host" property is not configured- Since:
- 4.3
-
getHttp11StatusCode
protected HttpStatusCode getHttp11StatusCode(HttpServletRequest request, HttpServletResponse response, 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 theView.RESPONSE_STATUS_ATTRIBUTE
attribute. If neither are set, it defaults toHttpStatus.SEE_OTHER
(303).- Parameters:
request
- the request to inspectresponse
- the servlet responsetargetUrl
- the target URL- Returns:
- the response status
-