Class MockHttpServletRequest
- java.lang.Object
- org.springframework.mock.web.MockHttpServletRequest
- All Implemented Interfaces:
HttpServletRequest,ServletRequest
- Direct Known Subclasses:
MockMultipartHttpServletRequest
public class MockHttpServletRequest extends Object implements HttpServletRequest
Mock implementation of theHttpServletRequestinterface.The default, preferred
Localefor the server mocked by this request isLocale.ENGLISH. This value can be changed viaaddPreferredLocale(java.util.Locale)orsetPreferredLocales(java.util.List<java.util.Locale>).As of Spring Framework 4.0, this set of mocks is designed on a Servlet 3.0 baseline.
- Since:
- 1.0.2
- Author:
- Juergen Hoeller, Rod Johnson, Rick Evans, Mark Fisher, Chris Beams, Sam Brannen, Brian Clozel
Field Summary
Fields Modifier and Type Field Description static StringDEFAULT_PROTOCOLThe default protocol: 'HTTP/1.1'.static StringDEFAULT_REMOTE_ADDRThe default remote address: '127.0.0.1'.static StringDEFAULT_REMOTE_HOSTThe default remote host: 'localhost'.static StringDEFAULT_SCHEMEThe default scheme: 'http'.static StringDEFAULT_SERVER_ADDRThe default server address: '127.0.0.1'.static StringDEFAULT_SERVER_NAMEThe default server name: 'localhost'.static intDEFAULT_SERVER_PORTThe default server port: '80'.Fields inherited from interface javax.servlet.http.HttpServletRequest
BASIC_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH, FORM_AUTH
Constructor Summary
Constructors Constructor Description MockHttpServletRequest()Create a newMockHttpServletRequestwith a defaultMockServletContext.MockHttpServletRequest(String method, String requestURI)Create a newMockHttpServletRequestwith a defaultMockServletContext.MockHttpServletRequest(ServletContext servletContext)Create a newMockHttpServletRequestwith the suppliedServletContext.MockHttpServletRequest(ServletContext servletContext, String method, String requestURI)
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddHeader(String name, Object value)Add 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.voidaddPart(Part part)voidaddPreferredLocale(Locale locale)Add a new preferred locale, before any existing locales.voidaddUserRole(String role)booleanauthenticate(HttpServletResponse response)StringchangeSessionId()The implementation of this (Servlet 3.1+) method callsMockHttpSession.changeSessionId()if the session is a mock session.protected voidcheckActive()Check whether this request is still active (that is, not completed yet), throwing an IllegalStateException if not active anymore.voidclearAttributes()Clear all of this request's attributes.voidclose()Mark this request as completed, keeping its state.AsyncContextgetAsyncContext()ObjectgetAttribute(String name)Enumeration<String>getAttributeNames()StringgetAuthType()StringgetCharacterEncoding()intgetContentLength()longgetContentLengthLong()StringgetContentType()StringgetContextPath()Cookie[]getCookies()longgetDateHeader(String name)Return the long timestamp for the date header with the givenname.DispatcherTypegetDispatcherType()StringgetHeader(String name)Enumeration<String>getHeaderNames()Enumeration<String>getHeaders(String name)ServletInputStreamgetInputStream()intgetIntHeader(String name)StringgetLocalAddr()LocalegetLocale()Return the first preferred locale configured in this mock request.Enumeration<Locale>getLocales()Return an enumeration of the preferred locales configured in this mock request.StringgetLocalName()intgetLocalPort()StringgetMethod()StringgetParameter(String name)Map<String,String[]>getParameterMap()Enumeration<String>getParameterNames()String[]getParameterValues(String name)PartgetPart(String name)Collection<Part>getParts()StringgetPathInfo()StringgetPathTranslated()StringgetProtocol()StringgetQueryString()BufferedReadergetReader()StringgetRealPath(String path)Deprecated.StringgetRemoteAddr()StringgetRemoteHost()intgetRemotePort()StringgetRemoteUser()RequestDispatchergetRequestDispatcher(String path)StringgetRequestedSessionId()StringgetRequestURI()StringBuffergetRequestURL()StringgetScheme()StringgetServerName()intgetServerPort()ServletContextgetServletContext()Return the ServletContext that this request is associated with.StringgetServletPath()HttpSessiongetSession()HttpSessiongetSession(boolean create)PrincipalgetUserPrincipal()voidinvalidate()Invalidate this request, clearing its state.booleanisActive()Return whether this request is still active (that is, not completed yet).booleanisAsyncStarted()booleanisAsyncSupported()booleanisRequestedSessionIdFromCookie()booleanisRequestedSessionIdFromUrl()Deprecated.booleanisRequestedSessionIdFromURL()booleanisRequestedSessionIdValid()booleanisSecure()booleanisUserInRole(String role)voidlogin(String username, String password)voidlogout()voidremoveAllParameters()Remove 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)voidsetContentType(String contentType)voidsetContextPath(String contextPath)voidsetCookies(Cookie... cookies)voidsetDispatcherType(DispatcherType dispatcherType)voidsetLocalAddr(String localAddr)voidsetLocalName(String localName)voidsetLocalPort(int localPort)voidsetMethod(String method)voidsetParameter(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)voidsetScheme(String scheme)voidsetSecure(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)voidsetUserPrincipal(Principal userPrincipal)AsyncContextstartAsync()AsyncContextstartAsync(ServletRequest request, ServletResponse response)Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.servlet.http.HttpServletRequest
upgrade
Field Detail
DEFAULT_PROTOCOL
public static final String DEFAULT_PROTOCOL
The default protocol: 'HTTP/1.1'.- Since:
- 4.3.7
- See Also:
- Constant Field Values
DEFAULT_SCHEME
public static final String DEFAULT_SCHEME
The default scheme: 'http'.- Since:
- 4.3.7
- See Also:
- Constant Field Values
DEFAULT_SERVER_ADDR
public static final String DEFAULT_SERVER_ADDR
The default server address: '127.0.0.1'.- See Also:
- Constant Field Values
DEFAULT_SERVER_NAME
public static final String DEFAULT_SERVER_NAME
The default server name: 'localhost'.- See Also:
- Constant Field Values
DEFAULT_SERVER_PORT
public static final int DEFAULT_SERVER_PORT
The default server port: '80'.- See Also:
- Constant Field Values
DEFAULT_REMOTE_ADDR
public static final String DEFAULT_REMOTE_ADDR
The default remote address: '127.0.0.1'.- See Also:
- Constant Field Values
DEFAULT_REMOTE_HOST
public static final String DEFAULT_REMOTE_HOST
The default remote host: 'localhost'.- See Also:
- Constant Field Values
Constructor Detail
MockHttpServletRequest
public MockHttpServletRequest()
Create a newMockHttpServletRequestwith a defaultMockServletContext.
MockHttpServletRequest
public MockHttpServletRequest(String method, String requestURI)
Create a newMockHttpServletRequestwith a defaultMockServletContext.- Parameters:
method- the request method (may benull)requestURI- the request URI (may benull)- See Also:
setMethod(java.lang.String),setRequestURI(java.lang.String),MockHttpServletRequest(ServletContext, String, String)
MockHttpServletRequest
public MockHttpServletRequest(ServletContext servletContext)
Create a newMockHttpServletRequestwith the suppliedServletContext.- Parameters:
servletContext- the ServletContext that the request runs in (may benullto use a defaultMockServletContext)- See Also:
MockHttpServletRequest(ServletContext, String, String)
MockHttpServletRequest
public MockHttpServletRequest(ServletContext servletContext, String method, 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:
setMethod(java.lang.String),setRequestURI(java.lang.String),setPreferredLocales(java.util.List<java.util.Locale>),MockServletContext
Method Detail
getServletContext
public ServletContext 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
protected void checkActive() throws IllegalStateException
Check whether this request is still active (that is, not completed yet), throwing an IllegalStateException if not active anymore.- Throws:
IllegalStateException
getAttribute
public Object getAttribute(String name)
- Specified by:
getAttributein interfaceServletRequest
getAttributeNames
public Enumeration<String> getAttributeNames()
- Specified by:
getAttributeNamesin interfaceServletRequest
getCharacterEncoding
public String getCharacterEncoding()
- Specified by:
getCharacterEncodingin interfaceServletRequest
setCharacterEncoding
public void setCharacterEncoding(String characterEncoding)
- Specified by:
setCharacterEncodingin interfaceServletRequest
setContent
public void setContent(byte[] content)
getContentLength
public int getContentLength()
- Specified by:
getContentLengthin interfaceServletRequest
getContentLengthLong
public long getContentLengthLong()
- Specified by:
getContentLengthLongin interfaceServletRequest
setContentType
public void setContentType(String contentType)
getContentType
public String getContentType()
- Specified by:
getContentTypein interfaceServletRequest
getInputStream
public ServletInputStream getInputStream()
- Specified by:
getInputStreamin interfaceServletRequest
setParameter
public void setParameter(String name, String value)
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
public void setParameter(String name, String... values)
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
public void setParameters(Map<String,?> params)
Set all provided parameters replacing any existing values for the provided parameter names. To add without replacing existing values, useaddParameters(java.util.Map).
addParameter
public void addParameter(String name, String value)
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
public void addParameter(String name, String... values)
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
public void addParameters(Map<String,?> params)
Add all provided parameters without replacing any existing values. To replace existing values, usesetParameters(java.util.Map).
removeParameter
public void removeParameter(String name)
Remove already registered values for the specified HTTP parameter, if any.
removeAllParameters
public void removeAllParameters()
Remove all existing parameters.
getParameter
public String getParameter(String name)
- Specified by:
getParameterin interfaceServletRequest
getParameterNames
public Enumeration<String> getParameterNames()
- Specified by:
getParameterNamesin interfaceServletRequest
getParameterValues
public String[] getParameterValues(String name)
- Specified by:
getParameterValuesin interfaceServletRequest
getParameterMap
public Map<String,String[]> getParameterMap()
- Specified by:
getParameterMapin interfaceServletRequest
setProtocol
public void setProtocol(String protocol)
getProtocol
public String getProtocol()
- Specified by:
getProtocolin interfaceServletRequest
getScheme
public String getScheme()
- Specified by:
getSchemein interfaceServletRequest
setServerName
public void setServerName(String serverName)
getServerName
public String getServerName()
- Specified by:
getServerNamein interfaceServletRequest
setServerPort
public void setServerPort(int serverPort)
getServerPort
public int getServerPort()
- Specified by:
getServerPortin interfaceServletRequest
getReader
public BufferedReader getReader() throws UnsupportedEncodingException
- Specified by:
getReaderin interfaceServletRequest- Throws:
UnsupportedEncodingException
setRemoteAddr
public void setRemoteAddr(String remoteAddr)
getRemoteAddr
public String getRemoteAddr()
- Specified by:
getRemoteAddrin interfaceServletRequest
setRemoteHost
public void setRemoteHost(String remoteHost)
getRemoteHost
public String getRemoteHost()
- Specified by:
getRemoteHostin interfaceServletRequest
setAttribute
public void setAttribute(String name, Object value)
- Specified by:
setAttributein interfaceServletRequest
removeAttribute
public void removeAttribute(String name)
- Specified by:
removeAttributein interfaceServletRequest
clearAttributes
public void clearAttributes()
Clear all of this request's attributes.
addPreferredLocale
public void addPreferredLocale(Locale locale)
Add a new preferred locale, before any existing locales.
setPreferredLocales
public void setPreferredLocales(List<Locale> locales)
Set the list of preferred locales, in descending order, effectively replacing any existing locales.- Since:
- 3.2
- See Also:
addPreferredLocale(java.util.Locale)
getLocale
public Locale 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:
ServletRequest.getLocale(),addPreferredLocale(Locale),setPreferredLocales(List)
getLocales
public Enumeration<Locale> 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:
ServletRequest.getLocales(),addPreferredLocale(Locale),setPreferredLocales(List)
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(),getScheme(),setScheme(String)
isSecure
public boolean isSecure()
- Specified by:
isSecurein interfaceServletRequest- See Also:
ServletRequest.isSecure()
getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path)
- Specified by:
getRequestDispatcherin interfaceServletRequest
getRealPath
@Deprecated public String getRealPath(String path)
Deprecated.- Specified by:
getRealPathin interfaceServletRequest
setRemotePort
public void setRemotePort(int remotePort)
getRemotePort
public int getRemotePort()
- Specified by:
getRemotePortin interfaceServletRequest
setLocalName
public void setLocalName(String localName)
getLocalName
public String getLocalName()
- Specified by:
getLocalNamein interfaceServletRequest
setLocalAddr
public void setLocalAddr(String localAddr)
getLocalAddr
public String getLocalAddr()
- Specified by:
getLocalAddrin interfaceServletRequest
setLocalPort
public void setLocalPort(int localPort)
getLocalPort
public int getLocalPort()
- Specified by:
getLocalPortin interfaceServletRequest
startAsync
public AsyncContext startAsync()
- Specified by:
startAsyncin interfaceServletRequest
startAsync
public AsyncContext startAsync(ServletRequest request, ServletResponse response)
- 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
public void setAsyncContext(MockAsyncContext asyncContext)
getAsyncContext
public AsyncContext getAsyncContext()
- Specified by:
getAsyncContextin interfaceServletRequest
setDispatcherType
public void setDispatcherType(DispatcherType dispatcherType)
getDispatcherType
public DispatcherType getDispatcherType()
- Specified by:
getDispatcherTypein interfaceServletRequest
setAuthType
public void setAuthType(String authType)
getAuthType
public String getAuthType()
- Specified by:
getAuthTypein interfaceHttpServletRequest
setCookies
public void setCookies(Cookie... cookies)
getCookies
public Cookie[] getCookies()
- Specified by:
getCookiesin interfaceHttpServletRequest
addHeader
public void addHeader(String name, Object value)
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
public void removeHeader(String name)
Remove already registered entries for the specified HTTP header, if any.- Since:
- 4.3.20
getDateHeader
public long getDateHeader(String name)
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:
- Section 7.1.1.1 of RFC 7231
getHeader
public String getHeader(String name)
- Specified by:
getHeaderin interfaceHttpServletRequest
getHeaders
public Enumeration<String> getHeaders(String name)
- Specified by:
getHeadersin interfaceHttpServletRequest
getHeaderNames
public Enumeration<String> getHeaderNames()
- Specified by:
getHeaderNamesin interfaceHttpServletRequest
getIntHeader
public int getIntHeader(String name)
- Specified by:
getIntHeaderin interfaceHttpServletRequest
getMethod
public String getMethod()
- Specified by:
getMethodin interfaceHttpServletRequest
setPathInfo
public void setPathInfo(String pathInfo)
getPathInfo
public String getPathInfo()
- Specified by:
getPathInfoin interfaceHttpServletRequest
getPathTranslated
public String getPathTranslated()
- Specified by:
getPathTranslatedin interfaceHttpServletRequest
setContextPath
public void setContextPath(String contextPath)
getContextPath
public String getContextPath()
- Specified by:
getContextPathin interfaceHttpServletRequest
setQueryString
public void setQueryString(String queryString)
getQueryString
public String getQueryString()
- Specified by:
getQueryStringin interfaceHttpServletRequest
setRemoteUser
public void setRemoteUser(String remoteUser)
getRemoteUser
public String getRemoteUser()
- Specified by:
getRemoteUserin interfaceHttpServletRequest
addUserRole
public void addUserRole(String role)
isUserInRole
public boolean isUserInRole(String role)
- Specified by:
isUserInRolein interfaceHttpServletRequest
setUserPrincipal
public void setUserPrincipal(Principal userPrincipal)
getUserPrincipal
public Principal getUserPrincipal()
- Specified by:
getUserPrincipalin interfaceHttpServletRequest
setRequestedSessionId
public void setRequestedSessionId(String requestedSessionId)
getRequestedSessionId
public String getRequestedSessionId()
- Specified by:
getRequestedSessionIdin interfaceHttpServletRequest
setRequestURI
public void setRequestURI(String requestURI)
getRequestURI
public String getRequestURI()
- Specified by:
getRequestURIin interfaceHttpServletRequest
getRequestURL
public StringBuffer getRequestURL()
- Specified by:
getRequestURLin interfaceHttpServletRequest
setServletPath
public void setServletPath(String servletPath)
getServletPath
public String getServletPath()
- Specified by:
getServletPathin interfaceHttpServletRequest
setSession
public void setSession(HttpSession session)
getSession
public HttpSession getSession(boolean create)
- Specified by:
getSessionin interfaceHttpServletRequest
getSession
public HttpSession getSession()
- Specified by:
getSessionin interfaceHttpServletRequest
changeSessionId
public String 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
isRequestedSessionIdFromUrl
@Deprecated public boolean isRequestedSessionIdFromUrl()
Deprecated.- Specified by:
isRequestedSessionIdFromUrlin interfaceHttpServletRequest
authenticate
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException
- Specified by:
authenticatein interfaceHttpServletRequest- Throws:
IOExceptionServletException
login
public void login(String username, String password) throws ServletException
- Specified by:
loginin interfaceHttpServletRequest- Throws:
ServletException
logout
public void logout() throws ServletException
- Specified by:
logoutin interfaceHttpServletRequest- Throws:
ServletException
getPart
public Part getPart(String name) throws IOException, ServletException
- Specified by:
getPartin interfaceHttpServletRequest- Throws:
IOExceptionServletException
getParts
public Collection<Part> getParts() throws IOException, ServletException
- Specified by:
getPartsin interfaceHttpServletRequest- Throws:
IOExceptionServletException