-
- 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(Type type)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.json.JsonMapper <T extends Any> T
bodyAsClass(Class<T> clazz)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.json.JsonMapper <T extends Any> T
bodyStreamAsClass(Type type)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.json.JsonMapper InputStream
bodyInputStream()
Gets the underlying InputStream for the request body <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(). <T extends Any> T
attributeOrCompute(String key, Function1<Context, T> callback)
Gets specified attribute, or computes the value from callback (and sets the attribute) 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. Map<String, List<UploadedFile>>
uploadedFileMap()
Gets a map of all uploaded files as a map where the key is the name of the parameter the file was uploaded as and the value is the list of files uploaded under that parameter. Charset
responseCharset()
Gets the current response Charset. abstract ServletOutputStream
outputStream()
Gets output-stream you can write to. Unit
writeSeekableStream(InputStream inputStream, String contentType, Long totalBytes)
Writes the specified inputStream as a seekable stream. Unit
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. abstract Context
result(InputStream resultStream)
Sets context result to the specified InputStream. String
result()
Gets the current io.javalin.http.servlet.JavalinServletContext.resultInputStream as a String (if set), and reset the underlying stream abstract InputStream
resultInputStream()
Gets the underlying InputStream for the result (io.javalin.http.servlet.JavalinServletContext.resultInputStream) Unit
async(ExecutorService executor, Long timeout, Runnable onTimeout, ThrowingRunnable<Exception> task)
Utility function that allows to run async task on top of the Context.future method. Unit
async(Long timeout, Runnable onTimeout, ThrowingRunnable<Exception> task)
Unit
async(ThrowingRunnable<Exception> task)
abstract Unit
future(Supplier<out CompletableFuture<?>> future)
The main entrypoint for all async related functionalities exposed by Context. abstract 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, Type type)
Serializes object to a JSON-string using the registered io.javalin.json.JsonMapper and sets it as the context result. Context
json(Object obj)
Context
jsonStream(Object obj, Type type)
Serializes object to a JSON-stream using the registered io.javalin.json.JsonMapper and sets it as the context result. Context
jsonStream(Object obj)
Unit
writeJsonStream(Stream<?> stream)
Consumes the specified stream with the configured JsonMapper, which transforms the stream's content to JSON, writing the results directly to the response's outputStream
as the stream is consumed.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.config.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(Type type)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.json.JsonMapper
-
bodyAsClass
<T extends Any> T bodyAsClass(Class<T> clazz)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.json.JsonMapper
-
bodyStreamAsClass
<T extends Any> T bodyStreamAsClass(Type type)
Maps a JSON body to a Java/Kotlin class using the registered io.javalin.json.JsonMapper
-
bodyInputStream
InputStream bodyInputStream()
Gets the underlying InputStream for the request body
-
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
-
attributeOrCompute
<T extends Any> T attributeOrCompute(String key, Function1<Context, T> callback)
Gets specified attribute, or computes the value from callback (and sets the attribute)
-
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.
-
uploadedFileMap
Map<String, List<UploadedFile>> uploadedFileMap()
Gets a map of all uploaded files as a map where the key is the name of the parameter the file was uploaded as and the value is the list of files uploaded under that parameter.
If called on a non-multipart request this returns an empty map
-
responseCharset
Charset responseCharset()
Gets the current response Charset.
-
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
Unit writeSeekableStream(InputStream inputStream, String contentType, Long totalBytes)
Writes the specified inputStream as a seekable stream. You can change this default in io.javalin.config.JavalinConfig.
-
writeSeekableStream
Unit 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
abstract Context result(InputStream resultStream)
Sets context result to the specified InputStream. Will overwrite the current result if there is one.
-
result
String result()
Gets the current io.javalin.http.servlet.JavalinServletContext.resultInputStream as a String (if set), and reset the underlying stream
-
resultInputStream
abstract InputStream resultInputStream()
Gets the underlying InputStream for the result (io.javalin.http.servlet.JavalinServletContext.resultInputStream)
-
async
Unit async(ExecutorService executor, Long timeout, Runnable onTimeout, ThrowingRunnable<Exception> 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 task, You can change this default in io.javalin.config.JavalinConfig.timeout
- 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
Unit async(ThrowingRunnable<Exception> task)
-
future
abstract Unit future(Supplier<out CompletableFuture<?>> future)
The main entrypoint for all async related functionalities exposed by Context.
- Parameters:
future
- Future represents any delayed in time result.
-
redirect
abstract 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, Type type)
Serializes object to a JSON-string using the registered io.javalin.json.JsonMapper and sets it as the context result. Also sets content type to application/json.
-
jsonStream
Context jsonStream(Object obj, Type type)
Serializes object to a JSON-stream using the registered io.javalin.json.JsonMapper and sets it as the context result. Also sets content type to application/json.
-
jsonStream
Context jsonStream(Object obj)
-
writeJsonStream
Unit writeJsonStream(Stream<?> stream)
Consumes the specified stream with the configured JsonMapper, which transforms the stream's content to JSON, writing the results directly to the response's
outputStream
as the stream is consumed. This function call is synchronous, and may be wrapped inctx.async { }
if needed.
-
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.
-
-
-
-