Class MockHttpServletRequest
- All Implemented Interfaces:
HttpServletRequest,ServletRequest
- Direct Known Subclasses:
MockMultipartHttpServletRequest
HttpServletRequest interface.
The default, preferred Locale for the server mocked by this request
is Locale.ENGLISH. This value can be changed via addPreferredLocale(java.util.Locale)
or setPreferredLocales(java.util.List<java.util.Locale>).
As of Spring 6.0, this set of mocks is designed on a Servlet 6.0 baseline.
- Since:
- 1.0.2
- Author:
- Juergen Hoeller, Rod Johnson, Rick Evans, Mark Fisher, Chris Beams, Sam Brannen, Brian Clozel
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe default protocol: 'HTTP/1.1'.static final StringThe default remote address: '127.0.0.1'.static final StringThe default remote host: 'localhost'.static final StringThe default scheme: 'http'.static final StringThe default server address: '127.0.0.1'.static final StringThe default server name: 'localhost'.static final intThe default server port: '80'.Fields inherited from interface jakarta.servlet.http.HttpServletRequest
BASIC_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH, FORM_AUTH -
Constructor Summary
ConstructorsConstructorDescriptionCreate a newMockHttpServletRequestwith a defaultMockServletContext.MockHttpServletRequest(ServletContext servletContext) Create a newMockHttpServletRequestwith the suppliedServletContext.MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) MockHttpServletRequest(String method, String requestURI) Create a newMockHttpServletRequestwith a defaultMockServletContext. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdd an HTTP header entry for the given name.voidaddParameter(String name, String value) Add a single value for the specified HTTP parameter.voidaddParameter(String name, String... values) Add an array of values for the specified HTTP parameter.voidaddParameters(Map<String, ?> params) Add all provided parameters without replacing any existing values.voidvoidaddPreferredLocale(Locale locale) Add a new preferred locale, before any existing locales.voidaddUserRole(String role) booleanauthenticate(HttpServletResponse response) The implementation of this (Servlet 3.1+) method callsMockHttpSession.changeSessionId()if the session is a mock session.protected voidCheck whether this request is still active (that is, not completed yet), throwing an IllegalStateException if not active anymore.voidClear all of this request's attributes.voidclose()Mark this request as completed, keeping its state.getAttribute(String name) byte[]Get the content of the request body as a byte array.Get the content of the request body as aString, using the configured character encoding.intlongCookie[]longgetDateHeader(String name) Return the long timestamp for the date header with the givenname.getHeaders(String name) intgetIntHeader(String name) Return the first preferred locale configured in this mock request.Return an enumeration of the preferred locales configured in this mock request.intgetParameter(String name) String[]getParameterValues(String name) getParts()intgetRequestDispatcher(String path) intReturn the ServletContext that this request is associated with.getSession(boolean create) Return the original URI template used to prepare the request, if any.voidInvalidate this request, clearing its state.booleanisActive()Return whether this request is still active (that is, not completed yet).booleanbooleanbooleanbooleanbooleanbooleanisSecure()booleanisUserInRole(String role) voidvoidlogout()voidRemove all existing parameters.voidremoveAttribute(String name) voidremoveHeader(String name) Remove already registered entries for the specified HTTP header, if any.voidremoveParameter(String name) Remove already registered values for the specified HTTP parameter, if any.voidsetAsyncContext(MockAsyncContext asyncContext) voidsetAsyncStarted(boolean asyncStarted) voidsetAsyncSupported(boolean asyncSupported) voidsetAttribute(String name, Object value) voidsetAuthType(String authType) voidsetCharacterEncoding(String characterEncoding) voidsetContent(byte[] content) Set the content of the request body as a byte array.voidsetContentType(String contentType) voidsetContextPath(String contextPath) voidsetCookies(Cookie... cookies) voidsetDispatcherType(DispatcherType dispatcherType) voidsetHttpServletMapping(HttpServletMapping httpServletMapping) voidsetLocalAddr(String localAddr) voidsetLocalName(String localName) voidsetLocalPort(int localPort) voidvoidsetParameter(String name, String value) Set a single value for the specified HTTP parameter.voidsetParameter(String name, String... values) Set an array of values for the specified HTTP parameter.voidsetParameters(Map<String, ?> params) Set all provided parameters replacing any existing values for the provided parameter names.voidsetPathInfo(String pathInfo) voidsetPreferredLocales(List<Locale> locales) Set the list of preferred locales, in descending order, effectively replacing any existing locales.voidsetProtocol(String protocol) voidsetQueryString(String queryString) voidsetRemoteAddr(String remoteAddr) voidsetRemoteHost(String remoteHost) voidsetRemotePort(int remotePort) voidsetRemoteUser(String remoteUser) voidsetRequestedSessionId(String requestedSessionId) voidsetRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) voidsetRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) voidsetRequestedSessionIdValid(boolean requestedSessionIdValid) voidsetRequestURI(String requestURI) voidvoidsetSecure(boolean secure) Set the booleansecureflag indicating whether the mock request was made using a secure channel, such as HTTPS.voidsetServerName(String serverName) voidsetServerPort(int serverPort) voidsetServletPath(String servletPath) voidsetSession(HttpSession session) voidsetUriTemplate(String uriTemplate) Set the original URI template used to prepare the request, if any.voidsetUserPrincipal(Principal userPrincipal) startAsync(ServletRequest request, ServletResponse response) <T extends HttpUpgradeHandler>
TMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface jakarta.servlet.http.HttpServletRequest
getTrailerFields, isTrailerFieldsReady, newPushBuilder
-
Field Details
-
DEFAULT_PROTOCOL
The default protocol: 'HTTP/1.1'.- Since:
- 4.3.7
- See Also:
-
DEFAULT_SCHEME
The default scheme: 'http'.- Since:
- 4.3.7
- See Also:
-
DEFAULT_SERVER_ADDR
The default server address: '127.0.0.1'.- See Also:
-
DEFAULT_SERVER_NAME
The default server name: 'localhost'.- See Also:
-
DEFAULT_SERVER_PORT
public static final int DEFAULT_SERVER_PORTThe default server port: '80'.- See Also:
-
DEFAULT_REMOTE_ADDR
The default remote address: '127.0.0.1'.- See Also:
-
DEFAULT_REMOTE_HOST
The default remote host: 'localhost'.- See Also:
-
-
Constructor Details
-
MockHttpServletRequest
public MockHttpServletRequest()Create a newMockHttpServletRequestwith a defaultMockServletContext. -
MockHttpServletRequest
Create a newMockHttpServletRequestwith a defaultMockServletContext.- Parameters:
method- the request method (may benull)requestURI- the request URI (may benull)- See Also:
-
MockHttpServletRequest
Create a newMockHttpServletRequestwith the suppliedServletContext.- Parameters:
servletContext- the ServletContext that the request runs in (may benullto use a defaultMockServletContext)- See Also:
-
MockHttpServletRequest
public MockHttpServletRequest(@Nullable ServletContext servletContext, @Nullable String method, @Nullable String requestURI) Create a newMockHttpServletRequestwith the suppliedServletContext,method, andrequestURI.The preferred locale will be set to
Locale.ENGLISH.- Parameters:
servletContext- the ServletContext that the request runs in (may benullto use a defaultMockServletContext)method- the request method (may benull)requestURI- the request URI (may benull)- See Also:
-
-
Method Details
-
getServletContext
Return the ServletContext that this request is associated with. (Not available in the standard HttpServletRequest interface for some reason.)- Specified by:
getServletContextin interfaceServletRequest
-
isActive
public boolean isActive()Return whether this request is still active (that is, not completed yet). -
close
public void close()Mark this request as completed, keeping its state. -
invalidate
public void invalidate()Invalidate this request, clearing its state. -
checkActive
Check whether this request is still active (that is, not completed yet), throwing an IllegalStateException if not active anymore.- Throws:
IllegalStateException
-
getAttribute
- Specified by:
getAttributein interfaceServletRequest
-
getAttributeNames
- Specified by:
getAttributeNamesin interfaceServletRequest
-
getCharacterEncoding
- Specified by:
getCharacterEncodingin interfaceServletRequest
-
setCharacterEncoding
- Specified by:
setCharacterEncodingin interfaceServletRequest
-
setContent
Set the content of the request body as a byte array.If the supplied byte array represents text such as XML or JSON, the
character encodingshould typically be set as well. -
getContentAsByteArray
Get the content of the request body as a byte array.- Returns:
- the content as a byte array (potentially
null) - Since:
- 5.0
- See Also:
-
getContentAsString
@Nullable public String getContentAsString() throws IllegalStateException, UnsupportedEncodingExceptionGet the content of the request body as aString, using the configured character encoding.- Returns:
- the content as a
String, potentiallynull - Throws:
IllegalStateException- if the character encoding has not been setUnsupportedEncodingException- if the character encoding is not supported- Since:
- 5.0
- See Also:
-
getContentLength
public int getContentLength()- Specified by:
getContentLengthin interfaceServletRequest
-
getContentLengthLong
public long getContentLengthLong()- Specified by:
getContentLengthLongin interfaceServletRequest
-
setContentType
-
getContentType
- Specified by:
getContentTypein interfaceServletRequest
-
getInputStream
- Specified by:
getInputStreamin interfaceServletRequest
-
setParameter
Set a single value for the specified HTTP parameter.If there are already one or more values registered for the given parameter name, they will be replaced.
-
setParameter
Set an array of values for the specified HTTP parameter.If there are already one or more values registered for the given parameter name, they will be replaced.
-
setParameters
Set all provided parameters replacing any existing values for the provided parameter names. To add without replacing existing values, useaddParameters(java.util.Map). -
addParameter
Add a single value for the specified HTTP parameter.If there are already one or more values registered for the given parameter name, the given value will be added to the end of the list.
-
addParameter
Add an array of values for the specified HTTP parameter.If there are already one or more values registered for the given parameter name, the given values will be added to the end of the list.
-
addParameters
Add all provided parameters without replacing any existing values. To replace existing values, usesetParameters(java.util.Map). -
removeParameter
Remove already registered values for the specified HTTP parameter, if any. -
removeAllParameters
public void removeAllParameters()Remove all existing parameters. -
getParameter
- Specified by:
getParameterin interfaceServletRequest
-
getParameterNames
- Specified by:
getParameterNamesin interfaceServletRequest
-
getParameterValues
- Specified by:
getParameterValuesin interfaceServletRequest
-
getParameterMap
- Specified by:
getParameterMapin interfaceServletRequest
-
setProtocol
-
getProtocol
- Specified by:
getProtocolin interfaceServletRequest
-
setScheme
-
getScheme
- Specified by:
getSchemein interfaceServletRequest
-
setServerName
-
getServerName
- Specified by:
getServerNamein interfaceServletRequest
-
setServerPort
public void setServerPort(int serverPort) -
getServerPort
public int getServerPort()- Specified by:
getServerPortin interfaceServletRequest
-
getReader
- Specified by:
getReaderin interfaceServletRequest- Throws:
UnsupportedEncodingException
-
setRemoteAddr
-
getRemoteAddr
- Specified by:
getRemoteAddrin interfaceServletRequest
-
setRemoteHost
-
getRemoteHost
- Specified by:
getRemoteHostin interfaceServletRequest
-
setAttribute
- Specified by:
setAttributein interfaceServletRequest
-
removeAttribute
- Specified by:
removeAttributein interfaceServletRequest
-
clearAttributes
public void clearAttributes()Clear all of this request's attributes. -
addPreferredLocale
Add a new preferred locale, before any existing locales. -
setPreferredLocales
Set the list of preferred locales, in descending order, effectively replacing any existing locales.- Since:
- 3.2
- See Also:
-
getLocale
Return the first preferred locale configured in this mock request.If no locales have been explicitly configured, the default, preferred
Localefor the server mocked by this request isLocale.ENGLISH.In contrast to the Servlet specification, this mock implementation does not take into consideration any locales specified via the
Accept-Languageheader.- Specified by:
getLocalein interfaceServletRequest- See Also:
-
getLocales
Return an enumeration of the preferred locales configured in this mock request.If no locales have been explicitly configured, the default, preferred
Localefor the server mocked by this request isLocale.ENGLISH.In contrast to the Servlet specification, this mock implementation does not take into consideration any locales specified via the
Accept-Languageheader.- Specified by:
getLocalesin interfaceServletRequest- See Also:
-
setSecure
public void setSecure(boolean secure) Set the booleansecureflag indicating whether the mock request was made using a secure channel, such as HTTPS.- See Also:
-
isSecure
public boolean isSecure()- Specified by:
isSecurein interfaceServletRequest- See Also:
-
getRequestDispatcher
- Specified by:
getRequestDispatcherin interfaceServletRequest
-
setRemotePort
public void setRemotePort(int remotePort) -
getRemotePort
public int getRemotePort()- Specified by:
getRemotePortin interfaceServletRequest
-
setLocalName
-
getLocalName
- Specified by:
getLocalNamein interfaceServletRequest
-
setLocalAddr
-
getLocalAddr
- Specified by:
getLocalAddrin interfaceServletRequest
-
setLocalPort
public void setLocalPort(int localPort) -
getLocalPort
public int getLocalPort()- Specified by:
getLocalPortin interfaceServletRequest
-
startAsync
- Specified by:
startAsyncin interfaceServletRequest
-
startAsync
- Specified by:
startAsyncin interfaceServletRequest
-
setAsyncStarted
public void setAsyncStarted(boolean asyncStarted) -
isAsyncStarted
public boolean isAsyncStarted()- Specified by:
isAsyncStartedin interfaceServletRequest
-
setAsyncSupported
public void setAsyncSupported(boolean asyncSupported) -
isAsyncSupported
public boolean isAsyncSupported()- Specified by:
isAsyncSupportedin interfaceServletRequest
-
setAsyncContext
-
getAsyncContext
- Specified by:
getAsyncContextin interfaceServletRequest
-
setDispatcherType
-
getDispatcherType
- Specified by:
getDispatcherTypein interfaceServletRequest
-
getRequestId
- Specified by:
getRequestIdin interfaceServletRequest
-
getProtocolRequestId
- Specified by:
getProtocolRequestIdin interfaceServletRequest
-
getServletConnection
- Specified by:
getServletConnectionin interfaceServletRequest
-
setAuthType
-
getAuthType
- Specified by:
getAuthTypein interfaceHttpServletRequest
-
setCookies
-
getCookies
- Specified by:
getCookiesin interfaceHttpServletRequest
-
addHeader
Add an HTTP header entry for the given name.While this method can take any
Objectas a parameter, it is recommended to use the following types:- String or any Object to be converted using
toString(); seegetHeader(java.lang.String). - String, Number, or Date for date headers; see
getDateHeader(java.lang.String). - String or Number for integer headers; see
getIntHeader(java.lang.String). String[]orCollection<String>for multiple values; seegetHeaders(java.lang.String).
- String or any Object to be converted using
-
removeHeader
Remove already registered entries for the specified HTTP header, if any.- Since:
- 4.3.20
-
getDateHeader
Return the long timestamp for the date header with the givenname.If the internal value representation is a String, this method will try to parse it as a date using the supported date formats:
- "EEE, dd MMM yyyy HH:mm:ss zzz"
- "EEE, dd-MMM-yy HH:mm:ss zzz"
- "EEE MMM dd HH:mm:ss yyyy"
- Specified by:
getDateHeaderin interfaceHttpServletRequest- Parameters:
name- the header name- See Also:
-
getHeader
- Specified by:
getHeaderin interfaceHttpServletRequest
-
getHeaders
- Specified by:
getHeadersin interfaceHttpServletRequest
-
getHeaderNames
- Specified by:
getHeaderNamesin interfaceHttpServletRequest
-
getIntHeader
- Specified by:
getIntHeaderin interfaceHttpServletRequest
-
setMethod
-
getMethod
- Specified by:
getMethodin interfaceHttpServletRequest
-
setPathInfo
-
getPathInfo
- Specified by:
getPathInfoin interfaceHttpServletRequest
-
getPathTranslated
- Specified by:
getPathTranslatedin interfaceHttpServletRequest
-
setContextPath
-
getContextPath
- Specified by:
getContextPathin interfaceHttpServletRequest
-
setQueryString
-
getQueryString
- Specified by:
getQueryStringin interfaceHttpServletRequest
-
setRemoteUser
-
getRemoteUser
- Specified by:
getRemoteUserin interfaceHttpServletRequest
-
addUserRole
-
isUserInRole
- Specified by:
isUserInRolein interfaceHttpServletRequest
-
setUserPrincipal
-
getUserPrincipal
- Specified by:
getUserPrincipalin interfaceHttpServletRequest
-
setRequestedSessionId
-
getRequestedSessionId
- Specified by:
getRequestedSessionIdin interfaceHttpServletRequest
-
setUriTemplate
Set the original URI template used to prepare the request, if any.- Parameters:
uriTemplate- the URI template used to set up the request, if any- Since:
- 6.2
-
getUriTemplate
Return the original URI template used to prepare the request, if any.- Since:
- 6.2
-
setRequestURI
-
getRequestURI
- Specified by:
getRequestURIin interfaceHttpServletRequest
-
getRequestURL
- Specified by:
getRequestURLin interfaceHttpServletRequest
-
setServletPath
-
getServletPath
- Specified by:
getServletPathin interfaceHttpServletRequest
-
setSession
-
getSession
- Specified by:
getSessionin interfaceHttpServletRequest
-
getSession
- Specified by:
getSessionin interfaceHttpServletRequest
-
changeSessionId
The implementation of this (Servlet 3.1+) method callsMockHttpSession.changeSessionId()if the session is a mock session. Otherwise it simply returns the current session id.- Specified by:
changeSessionIdin interfaceHttpServletRequest- Since:
- 4.0.3
-
setRequestedSessionIdValid
public void setRequestedSessionIdValid(boolean requestedSessionIdValid) -
isRequestedSessionIdValid
public boolean isRequestedSessionIdValid()- Specified by:
isRequestedSessionIdValidin interfaceHttpServletRequest
-
setRequestedSessionIdFromCookie
public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) -
isRequestedSessionIdFromCookie
public boolean isRequestedSessionIdFromCookie()- Specified by:
isRequestedSessionIdFromCookiein interfaceHttpServletRequest
-
setRequestedSessionIdFromURL
public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) -
isRequestedSessionIdFromURL
public boolean isRequestedSessionIdFromURL()- Specified by:
isRequestedSessionIdFromURLin interfaceHttpServletRequest
-
authenticate
- Specified by:
authenticatein interfaceHttpServletRequest- Throws:
IOExceptionServletException
-
login
- Specified by:
loginin interfaceHttpServletRequest- Throws:
ServletException
-
logout
- Specified by:
logoutin interfaceHttpServletRequest- Throws:
ServletException
-
addPart
-
getPart
- Specified by:
getPartin interfaceHttpServletRequest- Throws:
IOExceptionServletException
-
getParts
- Specified by:
getPartsin interfaceHttpServletRequest- Throws:
IOExceptionServletException
-
setHttpServletMapping
-
getHttpServletMapping
- Specified by:
getHttpServletMappingin interfaceHttpServletRequest
-
upgrade
public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException - Specified by:
upgradein interfaceHttpServletRequest- Throws:
IOExceptionServletException
-