-
- All Implemented Interfaces:
public interface Context
Provides access to functions for handling the request and response
-
-
Method Summary
Modifier and Type Method Description abstract HttpServletRequest
req()
Servlet request abstract HttpServletResponse
res()
Servlet response abstract <T extends Any> T
appAttribute(String key)
Gets an attribute from the Javalin instance serving the request abstract HandlerType
handlerType()
Gets the handler type of the current handler abstract String
matchedPath()
Gets the path that was used to match request (also includes before/after paths)
abstract String
endpointHandlerPath()
Gets the endpoint path that was used to match request (null in before, available in endpoint/after) Integer
contentLength()
Gets the request content length. String
contentType()
Gets the request content type, or null. Context
contentType(String contentType)
Sets response content type to specified String value. Context
contentType(ContentType contentType)
Sets response content type to specified ContentType value. HandlerType
method()
Gets the request method. String
path()
Gets the request path. Integer
port()
Gets the request port. String
protocol()
Gets the request protocol. String
contextPath()
Gets the request context path. String
userAgent()
Gets the request user agent, or null. String
characterEncoding()
Try to obtain request encoding from Header.CONTENT_TYPE header String
url()
Gets the request url. String
fullUrl()
Gets the full request url, including query string (if present) String
scheme()
Gets the request scheme. String
host()
Gets the request host, or null. String
ip()
Gets the request ip. String
body()
Gets the request body as a String. ByteArray
bodyAsBytes()
Gets the request body as a ByteArray. <T extends Any> T
bodyAsClass(Class<T> clazz)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.plugin.json. <T extends Any> T
bodyStreamAsClass(Class<T> clazz)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.plugin.json. InputStream
bodyAsInputStream()
Gets the request body as a InputStream <T extends Any> BodyValidator<T>
bodyValidator(Class<T> clazz)
Creates a typed BodyValidator for the body() value String
formParam(String key)
Gets a form param if it exists, else null <T extends Any> Validator<T>
formParamAsClass(String key, Class<T> clazz)
Creates a typed Validator for the formParam() value List<String>
formParams(String key)
Gets a list of form params for the specified key, or empty list. Map<String, List<String>>
formParamMap()
Gets a map with all the form param keys and values. abstract String
pathParam(String key)
Gets a path param by name (ex: pathParam("param"). <T extends Any> Validator<T>
pathParamAsClass(String key, Class<T> clazz)
Creates a typed Validator for the pathParam() value abstract Map<String, String>
pathParamMap()
Gets a map of all the pathParamAsClass keys and values. String
queryParam(String key)
Gets a query param if it exists, else null <T extends Any> Validator<T>
queryParamAsClass(String key, Class<T> clazz)
Creates a typed Validator for the queryParam() value List<String>
queryParams(String key)
Gets a list of query params for the specified key, or empty list. Map<String, List<String>>
queryParamMap()
Gets a map with all the query param keys and values. String
queryString()
Gets the request query string, or null. Unit
sessionAttribute(String key, Object value)
Sets an attribute for the user session. <T extends Any> T
sessionAttribute(String key)
Gets specified attribute from the user session, or null. <T extends Any> T
consumeSessionAttribute(String key)
Get session attribute, and set value to null Unit
cachedSessionAttribute(String key, Object value)
Sets an attribute for the user session, and caches it on the request <T extends Any> T
cachedSessionAttribute(String key)
Gets specified attribute from the request attribute cache, or the user session, or null. <T extends Any> T
cachedSessionAttributeOrCompute(String key, Function1<Context, T> callback)
Gets specified attribute from the request attribute cache, or the user session, or computes the value from callback. Map<String, Object>
sessionAttributeMap()
Gets a map of all the attributes in the user session. Unit
attribute(String key, Object value)
Sets an attribute on the request(). <T extends Any> T
attribute(String key)
Gets the specified attribute from the request(). Map<String, Object>
attributeMap()
Gets a map with all the attribute keys and values on the request(). CookieStore
cookieStore()
Gets cookie store used by this request String
cookie(String name)
Gets a request cookie by name, or null. Context
cookie(String name, String value)
Sets a cookie with name, value, and max-age = -1. Context
cookie(String name, String value, Integer maxAge)
Sets a cookie with name, value and max-age property Context
cookie(Cookie cookie)
Sets a Cookie. Map<String, String>
cookieMap()
Gets a map with all the cookie keys and values on the request(). String
header(String header)
Gets a request header by name, or null. Context
header(String name, String value)
Sets response header by name and value. <T extends Any> Validator<T>
headerAsClass(String header, Class<T> clazz)
Creates a typed Validator for the header() value Map<String, String>
headerMap()
Gets a map with all the header keys and values on the request(). BasicAuthCredentials
basicAuthCredentials()
Gets basic-auth credentials from the request, or throws. Boolean
isMultipart()
Returns true if request is multipart. Boolean
isMultipartFormData()
Returns true if request is multipart/form-data. UploadedFile
uploadedFile(String fileName)
Gets first UploadedFile for the specified name, or null. List<UploadedFile>
uploadedFiles(String fileName)
Gets a list of UploadedFiles for the specified name, or empty list. List<UploadedFile>
uploadedFiles()
Gets a list of UploadedFiles, or empty list. abstract ServletOutputStream
outputStream()
Gets output-stream you can write to. CompletableFuture<?>
writeSeekableStream(InputStream inputStream, String contentType, Long size)
Writes the specified inputStream as a seekable stream. CompletableFuture<?>
writeSeekableStream(InputStream inputStream, String contentType)
Writes input stream to writeSeekableStream with currently available data (InputStream.available) Context
result(String resultString)
Sets context result to the specified String. Context
result(ByteArray resultBytes)
Sets context result to the specified array of bytes. Context
result(InputStream resultStream)
Sets context result to the specified InputStream. String
resultString()
Gets the current resultStream as a String (if possible), and reset the underlying stream abstract InputStream
resultStream()
Extracts input stream from latest result if possible CompletableFuture<?>
async(ExecutorService executor, Long timeout, Function0<Unit> onTimeout, Runnable task)
Utility function that allows to run async task on top of the Context.future method. CompletableFuture<?>
async(Long timeout, Function0<Unit> onTimeout, Runnable task)
Launch async task with default, globally predefined executor service stored in appAttribute as ASYNC_EXECUTOR_KEY. CompletableFuture<?>
async(Runnable task)
Launch async task with default async executor and without custom timeout abstract <T extends Any> Context
future(CompletableFuture<T> future, Runnable launch, Consumer<T> callback)
The main entrypoint for all async related functionalities exposed by Context. <T extends Any> Context
future(CompletableFuture<T> future)
See the main future(CompletableFuture<T>, Runnable, Consumer<T>)
method for details.<T extends Any> Context
future(CompletableFuture<T> future, Consumer<T> callback)
See the main future(CompletableFuture<T>, Runnable, Consumer<T>)
method for details.abstract CompletableFuture<?>
resultFuture()
Gets the current context result as a CompletableFuture (if set). Unit
redirect(String location, HttpStatus status)
Redirects to location with given status. Unit
redirect(String location)
Redirects to location with status HttpStatus.FOUND. Context
status(HttpStatus status)
Sets the response status. Context
status(Integer status)
Sets the response status. HttpStatus
status()
Gets the response status. Integer
statusCode()
Gets the response status code Context
removeCookie(String name, String path)
Removes cookie specified by name and path (optional). Context
removeCookie(String name)
Removes cookie specified by name Context
json(Object obj)
Serializes object to a JSON-string using the registered io.javalin.plugin.json. Context
jsonStream(Object obj)
Serializes object to a JSON-stream using the registered io.javalin.plugin.json. Context
html(String html)
Sets context result to specified html string and sets content-type to text/html. Context
render(String filePath, Map<String, Object> model)
Renders a file with specified values and sets it as the context result. Context
render(String filePath)
-
-
Method Detail
-
req
abstract HttpServletRequest req()
Servlet request
-
res
abstract HttpServletResponse res()
Servlet response
-
appAttribute
abstract <T extends Any> T appAttribute(String key)
Gets an attribute from the Javalin instance serving the request
-
handlerType
abstract HandlerType handlerType()
Gets the handler type of the current handler
-
matchedPath
abstract String matchedPath()
Gets the path that was used to match request (also includes before/after paths)
-
endpointHandlerPath
abstract String endpointHandlerPath()
Gets the endpoint path that was used to match request (null in before, available in endpoint/after)
-
contentLength
Integer contentLength()
Gets the request content length.
-
contentType
String contentType()
Gets the request content type, or null.
-
contentType
Context contentType(String contentType)
Sets response content type to specified String value.
-
contentType
Context contentType(ContentType contentType)
Sets response content type to specified ContentType value.
-
method
HandlerType method()
Gets the request method.
-
contextPath
String contextPath()
Gets the request context path.
-
characterEncoding
String characterEncoding()
Try to obtain request encoding from Header.CONTENT_TYPE header
-
bodyAsBytes
ByteArray bodyAsBytes()
Gets the request body as a ByteArray. Calling this method returns the body as a ByteArray. If io.javalin.JavalinConfig.maxRequestSize is set and body is bigger than its value, a io.javalin.http.HttpResponseException is throw, with status 413 CONTENT_TOO_LARGE.
-
bodyAsClass
<T extends Any> T bodyAsClass(Class<T> clazz)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.plugin.json.JsonMapper
-
bodyStreamAsClass
<T extends Any> T bodyStreamAsClass(Class<T> clazz)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.plugin.json.JsonMapper
-
bodyAsInputStream
InputStream bodyAsInputStream()
Gets the request body as a InputStream
-
bodyValidator
<T extends Any> BodyValidator<T> bodyValidator(Class<T> clazz)
Creates a typed BodyValidator for the body() value
-
formParamAsClass
<T extends Any> Validator<T> formParamAsClass(String key, Class<T> clazz)
Creates a typed Validator for the formParam() value
-
formParams
List<String> formParams(String key)
Gets a list of form params for the specified key, or empty list.
-
formParamMap
Map<String, List<String>> formParamMap()
Gets a map with all the form param keys and values.
-
pathParam
abstract String pathParam(String key)
Gets a path param by name (ex: pathParam("param").
Ex: If the handler path is /users/{user-id}, and a browser GETs /users/123, pathParam("user-id") will return "123"
-
pathParamAsClass
<T extends Any> Validator<T> pathParamAsClass(String key, Class<T> clazz)
Creates a typed Validator for the pathParam() value
-
pathParamMap
abstract Map<String, String> pathParamMap()
Gets a map of all the pathParamAsClass keys and values.
-
queryParam
String queryParam(String key)
Gets a query param if it exists, else null
-
queryParamAsClass
<T extends Any> Validator<T> queryParamAsClass(String key, Class<T> clazz)
Creates a typed Validator for the queryParam() value
-
queryParams
List<String> queryParams(String key)
Gets a list of query params for the specified key, or empty list.
-
queryParamMap
Map<String, List<String>> queryParamMap()
Gets a map with all the query param keys and values.
-
queryString
String queryString()
Gets the request query string, or null.
-
sessionAttribute
Unit sessionAttribute(String key, Object value)
Sets an attribute for the user session.
-
sessionAttribute
<T extends Any> T sessionAttribute(String key)
Gets specified attribute from the user session, or null.
-
consumeSessionAttribute
<T extends Any> T consumeSessionAttribute(String key)
Get session attribute, and set value to null
-
cachedSessionAttribute
Unit cachedSessionAttribute(String key, Object value)
Sets an attribute for the user session, and caches it on the request
-
cachedSessionAttribute
<T extends Any> T cachedSessionAttribute(String key)
Gets specified attribute from the request attribute cache, or the user session, or null.
-
cachedSessionAttributeOrCompute
<T extends Any> T cachedSessionAttributeOrCompute(String key, Function1<Context, T> callback)
Gets specified attribute from the request attribute cache, or the user session, or computes the value from callback.
-
sessionAttributeMap
Map<String, Object> sessionAttributeMap()
Gets a map of all the attributes in the user session.
-
attribute
Unit attribute(String key, Object value)
Sets an attribute on the request(). Attributes are available to other handlers in the request lifecycle
-
attributeMap
Map<String, Object> attributeMap()
Gets a map with all the attribute keys and values on the request().
-
cookieStore
CookieStore cookieStore()
Gets cookie store used by this request
-
cookie
Context cookie(String name, String value, Integer maxAge)
Sets a cookie with name, value and max-age property
-
cookieMap
Map<String, String> cookieMap()
Gets a map with all the cookie keys and values on the request().
-
headerAsClass
<T extends Any> Validator<T> headerAsClass(String header, Class<T> clazz)
Creates a typed Validator for the header() value
-
headerMap
Map<String, String> headerMap()
Gets a map with all the header keys and values on the request().
-
basicAuthCredentials
BasicAuthCredentials basicAuthCredentials()
Gets basic-auth credentials from the request, or throws.
Returns a wrapper object BasicAuthCredentials which contains the Base64 decoded username and password from the Authorization header, or null if basic-auth is not properly configured
-
isMultipart
Boolean isMultipart()
Returns true if request is multipart.
-
isMultipartFormData
Boolean isMultipartFormData()
Returns true if request is multipart/form-data.
-
uploadedFile
UploadedFile uploadedFile(String fileName)
Gets first UploadedFile for the specified name, or null.
-
uploadedFiles
List<UploadedFile> uploadedFiles(String fileName)
Gets a list of UploadedFiles for the specified name, or empty list.
-
uploadedFiles
List<UploadedFile> uploadedFiles()
Gets a list of UploadedFiles, or empty list.
-
outputStream
abstract ServletOutputStream outputStream()
Gets output-stream you can write to. This stream by default uses compression specified in Javalin configuration, if you're looking for raw, uncompressed servlet's output-stream, use
ctx.res().outputStream
.
-
writeSeekableStream
CompletableFuture<?> writeSeekableStream(InputStream inputStream, String contentType, Long size)
Writes the specified inputStream as a seekable stream. This method is asynchronous and uses the global predefined executor service stored in appAttribute as ASYNC_EXECUTOR_KEY. You can change this default in io.javalin.config.JavalinConfig.
-
writeSeekableStream
CompletableFuture<?> writeSeekableStream(InputStream inputStream, String contentType)
Writes input stream to writeSeekableStream with currently available data (InputStream.available)
-
result
Context result(String resultString)
Sets context result to the specified String. Will overwrite the current result if there is one.
-
result
Context result(ByteArray resultBytes)
Sets context result to the specified array of bytes. Will overwrite the current result if there is one.
-
result
Context result(InputStream resultStream)
Sets context result to the specified InputStream. Will overwrite the current result if there is one.
-
resultString
String resultString()
Gets the current resultStream as a String (if possible), and reset the underlying stream
-
resultStream
abstract InputStream resultStream()
Extracts input stream from latest result if possible
-
async
CompletableFuture<?> async(ExecutorService executor, Long timeout, Function0<Unit> onTimeout, Runnable task)
Utility function that allows to run async task on top of the Context.future method. It means you should treat provided task as a result of this handler, and you can't use any other result function simultaneously.
- Parameters:
executor
- Thread-pool used to execute the given tasktimeout
- Timeout in milliseconds, by default it's 0 which means timeout watcher is disabled.onTimeout
- Timeout listener executed when TimeoutException is thrown in specified task.
-
async
CompletableFuture<?> async(Long timeout, Function0<Unit> onTimeout, Runnable task)
Launch async task with default, globally predefined executor service stored in appAttribute as ASYNC_EXECUTOR_KEY. You can change this default in io.javalin.config.JavalinConfig.
-
async
CompletableFuture<?> async(Runnable task)
Launch async task with default async executor and without custom timeout
-
future
abstract <T extends Any> Context future(CompletableFuture<T> future, Runnable launch, Consumer<T> callback)
The main entrypoint for all async related functionalities exposed by Context.
- Parameters:
future
- Future represents any delayed in time result.launch
- Optional callback that provides a possibility to launch any kind of async execution in a thread-safe way.callback
- Optional callback used to process result from the specified future.
-
future
<T extends Any> Context future(CompletableFuture<T> future)
See the main
future(CompletableFuture<T>, Runnable, Consumer<T>)
method for details.
-
future
<T extends Any> Context future(CompletableFuture<T> future, Consumer<T> callback)
See the main
future(CompletableFuture<T>, Runnable, Consumer<T>)
method for details.
-
resultFuture
abstract CompletableFuture<?> resultFuture()
Gets the current context result as a CompletableFuture (if set).
-
redirect
Unit redirect(String location, HttpStatus status)
Redirects to location with given status. Skips HTTP handler if called in before-handler
-
redirect
Unit redirect(String location)
Redirects to location with status HttpStatus.FOUND. Skips HTTP handler if called in before-handler
-
status
Context status(HttpStatus status)
Sets the response status.
-
status
HttpStatus status()
Gets the response status. For non-standard codes, HttpStatus.UNKNOWN is returned, the specific code can be obtained using statusCode
-
statusCode
Integer statusCode()
Gets the response status code
-
removeCookie
Context removeCookie(String name, String path)
Removes cookie specified by name and path (optional).
-
removeCookie
Context removeCookie(String name)
Removes cookie specified by name
-
json
Context json(Object obj)
Serializes object to a JSON-string using the registered io.javalin.plugin.json.JsonMapper and sets it as the context result. Also sets content type to application/json.
-
jsonStream
Context jsonStream(Object obj)
Serializes object to a JSON-stream using the registered io.javalin.plugin.json.JsonMapper and sets it as the context result. Also sets content type to application/json.
-
html
Context html(String html)
Sets context result to specified html string and sets content-type to text/html.
-
render
Context render(String filePath, Map<String, Object> model)
Renders a file with specified values and sets it as the context result. Also sets content-type to text/html. Determines the correct rendering-function based on the file extension.
-
-
-