public interface RoutingContext
A new instance is created for each HTTP request that is received in the
Handler.handle(Object)
of the router.
The same instance is passed to any matching request or failure handlers during the routing of the request or failure.
The context provides access to the HttpServerRequest
and HttpServerResponse
and allows you to maintain arbitrary data that lives for the lifetime of the context. Contexts are discarded once they
have been routed to the handler for the request.
The context also provides access to the Session
, cookies and body for the request, given the correct handlers
in the application.
If you use the internal error handler
Modifier and Type | Method and Description |
---|---|
default List<LanguageHeader> |
acceptableLanguages()
Returns the languages for the current request.
|
int |
addBodyEndHandler(Handler<Void> handler)
Provides a handler that will be called after the last part of the body is written to the wire.
|
RoutingContext |
addCookie(Cookie cookie)
Deprecated.
Use
HttpServerResponse.addCookie(Cookie)
Add a cookie. This will be sent back to the client in the response. |
default Future<Void> |
addEndHandler()
Add an end handler for the request/response context.
|
int |
addEndHandler(Handler<AsyncResult<Void>> handler)
Add an end handler for the request/response context.
|
int |
addHeadersEndHandler(Handler<Void> handler)
Add a handler that will be called just before headers are written to the response.
|
default RoutingContext |
attachment(String filename)
Set Content-Disposition get to "attachment" with optional
filename mime type. |
RequestBody |
body() |
void |
cancelAndCleanupFileUploads()
Cancel all unfinished file upload in progress and delete all uploaded files.
|
void |
clearUser()
Clear the current user object in the context.
|
int |
cookieCount()
Deprecated.
|
Map<String,Cookie> |
cookieMap()
Deprecated.
|
Route |
currentRoute() |
Map<String,Object> |
data() |
default Future<Void> |
end()
Shortcut to the response end.
|
default Future<Void> |
end(Buffer buffer)
Shortcut to the response end.
|
default RoutingContext |
end(Buffer buffer,
Handler<AsyncResult<Void>> handler)
See
end(Buffer) |
default RoutingContext |
end(Handler<AsyncResult<Void>> handler)
See
end() |
default Future<Void> |
end(String chunk)
Shortcut to the response end.
|
default RoutingContext |
end(String chunk,
Handler<AsyncResult<Void>> handler)
See
end(String) |
default RoutingContext |
etag(String etag)
Set the ETag of a response.
|
void |
fail(int statusCode)
Fail the context with the specified status code.
|
void |
fail(int statusCode,
Throwable throwable)
Fail the context with the specified throwable and the specified the status code.
|
void |
fail(Throwable throwable)
Fail the context with the specified throwable and 500 status code.
|
boolean |
failed() |
Throwable |
failure()
If the context is being routed to failure handlers after a failure has been triggered by calling
fail(Throwable) then this will return that throwable. |
List<FileUpload> |
fileUploads() |
<T> T |
get(String key)
Get some data from the context.
|
<T> T |
get(String key,
T defaultValue)
Get some data from the context.
|
String |
getAcceptableContentType()
If the route specifies produces matches, e.g.
|
default Buffer |
getBody()
Deprecated.
Use
body() instead. |
default JsonObject |
getBodyAsJson()
Deprecated.
Use
body() instead. |
default JsonObject |
getBodyAsJson(int maxAllowedLength)
Deprecated.
Use
body() instead.
Gets the current body buffer as a JsonObject . If a positive limit is provided the parsing will only happen
if the buffer length is smaller or equal to the limit. Otherwise an IllegalStateException is thrown.
When the application is only handling uploads in JSON format, it is recommended to set a limit on
BodyHandler.setBodyLimit(long) as this will avoid the upload to be parsed and
loaded into the application memory. |
default JsonArray |
getBodyAsJsonArray()
Deprecated.
Use
body() instead. |
default JsonArray |
getBodyAsJsonArray(int maxAllowedLength)
Deprecated.
Use
body() instead.
Gets the current body buffer as a JsonArray . If a positive limit is provided the parsing will only happen
if the buffer length is smaller or equal to the limit. Otherwise an IllegalStateException is thrown.
When the application is only handling uploads in JSON format, it is recommended to set a limit on
BodyHandler.setBodyLimit(long) as this will avoid the upload to be parsed and
loaded into the application memory. |
default String |
getBodyAsString()
Deprecated.
Use
body() instead. |
default String |
getBodyAsString(String encoding)
Deprecated.
Use
body() instead.
Get the entire HTTP request body as a string, assuming the specified encoding. The context must have first been routed to a
BodyHandler for this to be populated. |
Cookie |
getCookie(String name)
Deprecated.
Use
HttpServerRequest.getCookie(String)
Get the cookie with the specified name. |
default boolean |
is(String type)
Check if the incoming request contains the "Content-Type"
get field, and it contains the give mime `type`.
|
default boolean |
isFresh()
Check if the request is fresh, aka
Last-Modified and/or the ETag
still match.
|
boolean |
isSessionAccessed()
Whether the
session() has been already called or not. |
default Future<Void> |
json(Object json)
Encode an Object to JSON and end the request.
|
default RoutingContext |
json(Object json,
Handler<AsyncResult<Void>> handler)
See
json(Object) . |
default RoutingContext |
lastModified(java.time.Instant instant)
Set the Last-Modified date using a Instant.
|
default RoutingContext |
lastModified(String instant)
Set the Last-Modified date using a String.
|
String |
mountPoint() |
void |
next()
Tell the router to route this context to the next matching route (if any).
|
default String |
normalisedPath()
Deprecated.
|
String |
normalizedPath()
Return the normalized path for the request.
|
ParsedHeaderValues |
parsedHeaders()
The headers:
Accept
Accept-Charset
Accept-Encoding
Accept-Language
Content-Type
Parsed into
ParsedHeaderValue |
String |
pathParam(String name)
Gets the value of a single path parameter
|
Map<String,String> |
pathParams()
Returns a map of named parameters as defined in path declaration with their actual values
|
default LanguageHeader |
preferredLanguage()
Helper to return the user preferred language.
|
RoutingContext |
put(String key,
Object obj)
Put some arbitrary data in the context.
|
List<String> |
queryParam(String name)
Gets the value of a single query parameter.
|
MultiMap |
queryParams()
Returns a map of all query parameters inside the query string
The query parameters are lazily decoded: the decoding happens on the first time this method is called. |
MultiMap |
queryParams(Charset encoding)
Always decode the current query string with the given
encoding . |
default Future<Void> |
redirect(String url)
Perform a 302 redirect to
url . |
default RoutingContext |
redirect(String url,
Handler<AsyncResult<Void>> handler)
See
redirect(String) . |
<T> T |
remove(String key)
Remove some data from the context.
|
boolean |
removeBodyEndHandler(int handlerID)
Remove a body end handler
|
default Cookie |
removeCookie(String name)
Deprecated.
Use
HttpServerResponse.removeCookie(String)
Expire a cookie, notifying a User Agent to remove it from its cookie jar. |
Cookie |
removeCookie(String name,
boolean invalidate)
Deprecated.
Use
HttpServerResponse.removeCookie(String, boolean)
Remove a cookie from the cookie set. If invalidate is true then it will expire a cookie, notifying a User Agent to
remove it from its cookie jar. |
boolean |
removeEndHandler(int handlerID)
Remove an end handler
|
boolean |
removeHeadersEndHandler(int handlerID)
Remove a headers end handler
|
HttpServerRequest |
request() |
void |
reroute(HttpMethod method,
String path)
Restarts the current router with a new method and path.
|
default void |
reroute(String path)
Restarts the current router with a new path and reusing the original method.
|
HttpServerResponse |
response() |
Session |
session()
Get the session.
|
void |
setAcceptableContentType(String contentType)
Set the acceptable content type.
|
void |
setBody(Buffer body)
Deprecated.
This method is internal. Users that really need to use it should refer to
RoutingContextInternal.setBody(Buffer)
Set the body. Used by the BodyHandler . You will not normally call this method. |
void |
setSession(Session session)
Deprecated.
This method is internal. Users that really need to use it should refer to
RoutingContextInternal.setSession(Session)
Set the session. Used by the SessionHandler . You will not normally call this method. |
void |
setUser(User user)
Set the user.
|
int |
statusCode()
If the context is being routed to failure handlers after a failure has been triggered by calling
fail(int) then this will return that status code. |
User |
user()
Get the authenticated user (if any).
|
Vertx |
vertx() |
HttpServerRequest request()
HttpServerResponse response()
void next()
If next is not called for a handler then the handler should make sure it ends the response or no response will be sent.
void fail(int statusCode)
This will cause the router to route the context to any matching failure handlers for the request. If no failure handlers
match It will trigger the error handler matching the status code. You can define such error handler with
Router.errorHandler(int, Handler)
. If no error handler is not defined, It will send a default failure response with provided status code.
statusCode
- the HTTP status codevoid fail(Throwable throwable)
This will cause the router to route the context to any matching failure handlers for the request. If no failure handlers
match It will trigger the error handler matching the status code. You can define such error handler with
Router.errorHandler(int, Handler)
. If no error handler is not defined, It will send a default failure response with 500 status code.
throwable
- a throwable representing the failurevoid fail(int statusCode, Throwable throwable)
This will cause the router to route the context to any matching failure handlers for the request. If no failure handlers
match It will trigger the error handler matching the status code. You can define such error handler with
Router.errorHandler(int, Handler)
. If no error handler is not defined, It will send a default failure response with provided status code.
statusCode
- the HTTP status codethrowable
- a throwable representing the failureRoutingContext put(String key, Object obj)
key
- the key for the dataobj
- the data<T> T get(String key)
T
- the type of the datakey
- the key for the dataClassCastException
- if the data is not of the expected type<T> T get(String key, T defaultValue)
T
- the type of the datakey
- the key for the datadefaultValue
- when the underlying data doesn't contain the key this will be the return value.ClassCastException
- if the data is not of the expected type<T> T remove(String key)
T
- the type of the datakey
- the key for the dataClassCastException
- if the data is not of the expected typeVertx vertx()
Router
for this contextString mountPoint()
Route currentRoute()
@Deprecated default String normalisedPath()
normalizedPath()
insteadString normalizedPath()
The normalized path is where the URI path has been decoded, i.e. any unicode or other illegal URL characters that were encoded in the original URL with `%` will be returned to their original form. E.g. `%20` will revert to a space. Also `+` reverts to a space in a query.
The normalized path will also not contain any `..` character sequences to prevent resources being accessed outside of the permitted area.
It's recommended to always use the normalized path as opposed to HttpServerRequest.path()
if accessing server resources requested by a client.
@Deprecated Cookie getCookie(String name)
HttpServerRequest.getCookie(String)
Get the cookie with the specified name.name
- the cookie name@Deprecated RoutingContext addCookie(Cookie cookie)
HttpServerResponse.addCookie(Cookie)
Add a cookie. This will be sent back to the client in the response.cookie
- the cookie@Deprecated default Cookie removeCookie(String name)
HttpServerResponse.removeCookie(String)
Expire a cookie, notifying a User Agent to remove it from its cookie jar.name
- the name of the cookie@Deprecated Cookie removeCookie(String name, boolean invalidate)
HttpServerResponse.removeCookie(String, boolean)
Remove a cookie from the cookie set. If invalidate is true then it will expire a cookie, notifying a User Agent to
remove it from its cookie jar.name
- the name of the cookie@Deprecated int cookieCount()
HttpServerRequest.cookieCount()
@Deprecated Map<String,Cookie> cookieMap()
HttpServerRequest.cookieMap()
@Deprecated default String getBodyAsString()
body()
instead.BodyHandler
for this to be populated.@Deprecated default String getBodyAsString(String encoding)
body()
instead.
Get the entire HTTP request body as a string, assuming the specified encoding. The context must have first been routed to a
BodyHandler
for this to be populated.encoding
- the encoding, e.g. "UTF-16"@Deprecated default JsonObject getBodyAsJson(int maxAllowedLength)
body()
instead.
Gets the current body buffer as a JsonObject
. If a positive limit is provided the parsing will only happen
if the buffer length is smaller or equal to the limit. Otherwise an IllegalStateException
is thrown.
When the application is only handling uploads in JSON format, it is recommended to set a limit on
BodyHandler.setBodyLimit(long)
as this will avoid the upload to be parsed and
loaded into the application memory.maxAllowedLength
- if the current buffer length is greater than the limit an IllegalStateException
is
thrown. This can be used to avoid DDoS attacks on very long JSON payloads that could take
over the CPU while attempting to parse the data.JsonObject
. The context must have first been routed to a
BodyHandler
for this to be populated.
null
or the "null"
JSON literal then null
is returned.@Deprecated default JsonArray getBodyAsJsonArray(int maxAllowedLength)
body()
instead.
Gets the current body buffer as a JsonArray
. If a positive limit is provided the parsing will only happen
if the buffer length is smaller or equal to the limit. Otherwise an IllegalStateException
is thrown.
When the application is only handling uploads in JSON format, it is recommended to set a limit on
BodyHandler.setBodyLimit(long)
as this will avoid the upload to be parsed and
loaded into the application memory.maxAllowedLength
- if the current buffer length is greater than the limit an IllegalStateException
is
thrown. This can be used to avoid DDoS attacks on very long JSON payloads that could take
over the CPU while attempting to parse the data.JsonArray
. The context must have first been routed to a
BodyHandler
for this to be populated.
null
or the "null"
JSON literal then null
is returned.@Deprecated default JsonObject getBodyAsJson()
body()
instead.JsonObject
. The context must have first been routed to a
BodyHandler
for this to be populated.
null
or the "null"
JSON literal then null
is returned.@Deprecated default JsonArray getBodyAsJsonArray()
body()
instead.JsonArray
. The context must have first been routed to a
BodyHandler
for this to be populated.
null
or the "null"
JSON literal then null
is returned.@Deprecated default Buffer getBody()
body()
instead.Buffer
. The context must have first been routed to a
BodyHandler
for this to be populated.RequestBody body()
List<FileUpload> fileUploads()
FileUpload
(if any) for the request. The context must have first been routed to a
BodyHandler
for this to work.void cancelAndCleanupFileUploads()
Session session()
SessionHandler
for this to be populated.
Sessions live for a browser session, and are maintained by session cookies.boolean isSessionAccessed()
session()
has been already called or not. This is usually used by the
SessionHandler
.User user()
Throwable failure()
fail(Throwable)
then this will return that throwable. It can be used by failure handlers to render a response,
e.g. create a failure response page.int statusCode()
fail(int)
then this will return that status code. It can be used by failure handlers to render a response,
e.g. create a failure response page.
When the status code has not been set yet (it is undefined) its value will be -1.String getAcceptableContentType()
ParsedHeaderValues parsedHeaders()
ParsedHeaderValue
int addHeadersEndHandler(Handler<Void> handler)
handler
- the handlerboolean removeHeadersEndHandler(int handlerID)
handlerID
- the id as returned from addHeadersEndHandler(Handler)
.int addBodyEndHandler(Handler<Void> handler)
handler
- the handlerboolean removeBodyEndHandler(int handlerID)
handlerID
- the id as returned from addBodyEndHandler(Handler)
.int addEndHandler(Handler<AsyncResult<Void>> handler)
handler
- the handler that will be called with either a success or failure result.default Future<Void> addEndHandler()
addEndHandler(Handler)
boolean removeEndHandler(int handlerID)
handlerID
- the id as returned from addEndHandler(Handler)
.boolean failed()
@Deprecated void setBody(Buffer body)
RoutingContextInternal.setBody(Buffer)
Set the body. Used by the BodyHandler
. You will not normally call this method.body
- the body@Deprecated void setSession(Session session)
RoutingContextInternal.setSession(Session)
Set the session. Used by the SessionHandler
. You will not normally call this method.session
- the sessionvoid setUser(User user)
user
- the uservoid clearUser()
void setAcceptableContentType(String contentType)
contentType
- the content typedefault void reroute(String path)
path
- the new http path.void reroute(HttpMethod method, String path)
method
- the new http requestpath
- the new http path.default List<LanguageHeader> acceptableLanguages()
Accept-Language
header and sorted on quality.
When 2 or more entries have the same quality then the order used to return the best match is based on the lowest
index on the original list. For example if a user has en-US and en-GB with same quality and this order the best
match will be en-US because it was declared as first entry by the client.default LanguageHeader preferredLanguage()
Map<String,String> pathParams()
String pathParam(String name)
name
- the name of parameter as defined in path declarationMultiMap queryParams()
MultiMap queryParams(Charset encoding)
encoding
. The decode result is never cached. Callers
to this method are expected to cache the result if needed. Usually users should use queryParams()
.
This method is only useful when the requests without content type (GET
requests as an example) expect that
query params are in the ASCII format ISO-5559-1
.encoding
- a non null character set.List<String> queryParam(String name)
queryParams()
name
- The name of query parametername
was founddefault RoutingContext attachment(String filename)
filename
mime type.filename
- the filename for the attachmentdefault Future<Void> redirect(String url)
url
. If a custom 3xx code is already defined, then that
one will be preferred.
The string "back" is special-cased
to provide Referrer support, when Referrer
is not present "/" is used.
Examples:
redirect('back');
redirect('/login');
redirect('http://google.com');url
- the target urldefault RoutingContext redirect(String url, Handler<AsyncResult<Void>> handler)
redirect(String)
.default Future<Void> json(Object json)
Content-Type
is not set then correct Content-Type
will be applied to the responsejson
- the jsondefault RoutingContext json(Object json, Handler<AsyncResult<Void>> handler)
json(Object)
.default boolean is(String type)
type
- content typedefault boolean isFresh()
default RoutingContext etag(String etag)
etag
- the etag valuedefault RoutingContext lastModified(java.time.Instant instant)
instant
- the last modified instantdefault RoutingContext lastModified(String instant)
instant
- the last modified instantdefault Future<Void> end(String chunk)
chunk
- a chunkdefault RoutingContext end(String chunk, Handler<AsyncResult<Void>> handler)
end(String)
default Future<Void> end(Buffer buffer)
buffer
- a chunkdefault RoutingContext end(Buffer buffer, Handler<AsyncResult<Void>> handler)
end(Buffer)
default RoutingContext end(Handler<AsyncResult<Void>> handler)
end()
Copyright © 2024 Eclipse. All rights reserved.