### Basic Spark Java Hello World Source: https://sparkjava.com/documentation/index A simple Java example demonstrating how to create a basic web application using Spark Java. It defines a GET route for '/hello' that returns 'Hello World'. Requires static import of Spark methods. ```java import static spark.Spark.*; public class HelloWorld { public static void main(String[] args) { get("/hello", (req, res) -> "Hello World"); } } ``` -------------------------------- ### Define Basic HTTP GET Route Source: https://sparkjava.com/documentation/index An example of defining a simple GET route in Spark Java for the root path '/'. It includes a lambda expression that takes request and response objects and returns a string. ```java get("/", (request, response) -> { // Show something }); ``` -------------------------------- ### Echo WebSocket Handler Example Source: https://sparkjava.com/documentation/index An example implementation of a WebSocket handler class. It manages connected sessions, handles connection closures, and echoes received messages back to the client. It uses Jetty's WebSocket API. ```java import org.eclipse.jetty.websocket.api.*; import org.eclipse.jetty.websocket.api.annotations.*; import java.io.*; import java.util.*; import java.util.concurrent.*; @WebSocket public class EchoWebSocket { // Store sessions if you want to, for example, broadcast a message to all users private static final Queue sessions = new ConcurrentLinkedQueue<>(); @OnWebSocketConnect public void connected(Session session) { sessions.add(session); } @OnWebSocketClose public void closed(Session session, int statusCode, String reason) { sessions.remove(session); } @OnWebSocketMessage public void message(Session session, String message) throws IOException { System.out.println("Got: " + message); // Print message session.getRemote().sendString(message); // and send it back } } ``` -------------------------------- ### Define Basic HTTP PUT Route Source: https://sparkjava.com/documentation/index An example of defining a PUT route in Spark Java for the root path '/'. This is commonly used for updating existing resources. ```java put("/", (request, response) -> { // Update something }); ``` -------------------------------- ### Spark Java: Before-Filter Example Source: https://sparkjava.com/documentation/index Define a before-filter to execute code before each request. This example shows how to check for authentication and halt the request with a 401 status and message if the user is not authenticated. Before-filters can read the request and modify the response. ```java before((request, response) -> { boolean authenticated; // ... check if authenticated if (!authenticated) { halt(401, "You are not welcome here"); } }); ``` -------------------------------- ### Spark Java: Patterned Before-Filter Source: https://sparkjava.com/documentation/index Create a before-filter that only executes if the request path matches a specified pattern. This example halts requests to any path starting with '/protected/' with a 401 status. ```java before("/protected/*", (request, response) -> { // ... check if authenticated halt(401, "Go Away!"); }); ``` -------------------------------- ### Spark Java: After-Filter Example Source: https://sparkjava.com/documentation/index Define an after-filter to execute code after each request. This example demonstrates setting a custom header on the response. After-filters can read the request and modify the response. ```java after((request, response) -> { response.header("foo", "set by after filter"); }); ``` -------------------------------- ### Unmap Route by Path and Verb Source: https://sparkjava.com/documentation/index Shows how to unmap routes more specifically by providing both the path string and the HTTP verb (e.g., 'get') to the `unmap()` function in Spark Java. ```java unmap("/hello", "get"); // unmaps all 'GET' routes with path 'hello' ``` -------------------------------- ### Spark Java Request Information Access Source: https://sparkjava.com/documentation/index Provides examples of how to retrieve various pieces of information from an incoming HTTP request in Spark Java. This includes attributes, body, headers, parameters, cookies, IP address, and more. ```java request.attributes(); // the attributes list request.attribute("foo"); // value of foo attribute request.attribute("A", "V"); // sets value of attribute A to V request.body(); // request body sent by the client request.bodyAsBytes(); // request body as bytes request.contentLength(); // length of request body request.contentType(); // content type of request.body request.contextPath(); // the context path, e.g. "/hello" request.cookies(); // request cookies sent by the client request.headers(); // the HTTP header list request.headers("BAR"); // value of BAR header request.host(); // the host, e.g. "example.com" request.ip(); // client IP address request.params("foo"); // value of foo path parameter request.params(); // map with all parameters request.pathInfo(); // the path info request.port(); // the server port request.protocol(); // the protocol, e.g. HTTP/1.1 request.queryMap(); // the query map request.queryMap("foo"); // query map for a certain parameter request.queryParams(); // the query param list request.queryParams("FOO"); // value of FOO query param request.queryParamsValues("FOO") // all values of FOO query param request.raw(); // raw request handed in by Jetty request.requestMethod(); // The HTTP method (GET, ..etc) request.scheme(); // "http" request.servletPath(); // the servlet path, e.g. /result.jsp request.session(); // session management request.splat(); // splat (*) parameters request.uri(); // the uri, e.g. "http://example.com/foo" request.url(); // the url. e.g. "http://example.com/foo" request.userAgent(); // user agent ``` -------------------------------- ### Cookie Management API Source: https://sparkjava.com/documentation/index Details the methods for managing cookies, including setting, getting, and removing them. ```APIDOC ## Cookie Management API ### Description Provides functionalities for handling cookies in both requests and responses. This includes retrieving cookies from incoming requests and setting or removing cookies in outgoing responses. ### Request Cookie Methods - `request.cookies()`: Get a map of all request cookies. - `request.cookie(String name)`: Access a specific request cookie by name. ### Response Cookie Methods - `response.cookie(String name, String value)`: Set a cookie with a value. - `response.cookie(String name, String value, int maxAge)`: Set a cookie with a value and max age. - `response.cookie(String name, String value, int maxAge, boolean secure)`: Set a secure cookie. - `response.removeCookie(String name)`: Remove a cookie. ``` -------------------------------- ### Spark Java: Static Files Location (External) Source: https://sparkjava.com/documentation/index Configure Spark Java to serve static files from an external folder on the file system, not within the classpath. This example uses the system's temporary directory. ```java staticFiles.externalLocation(System.getProperty("java.io.tmpdir")); ``` -------------------------------- ### Spark Java: AfterAfter-Filter Example Source: https://sparkjava.com/documentation/index Define an afterAfter-filter, which executes after all other after-filters. This acts similarly to a 'finally' block in exception handling. This example sets a custom header on the response. ```java afterAfter((request, response) -> { response.header("foo", "set by afterAfter filter"); }); ``` -------------------------------- ### Define Route with Named Parameter Source: https://sparkjava.com/documentation/index An example of defining a Spark Java route with a named path parameter ':name'. The value of this parameter can be accessed using `request.params(":name")` within the route handler. ```java // matches "GET /hello/foo" and "GET /hello/bar" // request.params(":name") is 'foo' or 'bar' get("/hello/:name", (request, response) -> { return "Hello: " + request.params(":name"); }); ``` -------------------------------- ### Spark Java: Redirect with Status Code Source: https://sparkjava.com/documentation/index Trigger a browser redirect with a specific HTTP 3XX status code. This example performs a 'moved permanently' redirect. ```java response.redirect("/bar", 301); // moved permanently ``` -------------------------------- ### Spark Java: Static Files Cache/Expire Time Source: https://sparkjava.com/documentation/index Set the cache expiration time in seconds for static files. By default, no caching is applied. This example sets the expire time to ten minutes. ```java staticFiles.expireTime(600); // ten minutes ``` -------------------------------- ### Initialize Spark Server with Exception Handler Source: https://sparkjava.com/documentation/index Shows how to manually initialize the Spark server using `init()` and how to provide a custom exception handler for initialization failures. The provided handler prints an error message. ```java initExceptionHandler((e) -> System.out.println("Uh-oh")); ``` -------------------------------- ### Define Basic HTTP OPTIONS Route Source: https://sparkjava.com/documentation/index Shows how to define an OPTIONS route for the root path '/' in Spark Java. This is often used for CORS preflight requests. ```java options("/", (request, response) -> { // Appease something }); ``` -------------------------------- ### Build Javadoc with Maven Source: https://sparkjava.com/documentation/index Command to generate Javadoc documentation for the project using Maven. The output will be placed in the `/target/site/apidocs` directory. ```bash mvn javadoc:javadoc ``` -------------------------------- ### Configure SparkFilter for External Servers Source: https://sparkjava.com/documentation/index This XML configuration is used in web.xml to deploy Spark on an external web server. It requires implementing `spark.servlet.SparkApplication` and specifying the application class. ```xml SparkFilter spark.servlet.SparkFilter applicationClass com.company.YourApplication SparkFilter /* ``` -------------------------------- ### Spark Java: Not Found (404) Handling - String/HTML Source: https://sparkjava.com/documentation/index Configure custom handling for 404 Not Found errors using a simple string or HTML content. ```java // Using string/html notFound("

Custom 404 handling

"); ``` -------------------------------- ### Define Basic HTTP POST Route Source: https://sparkjava.com/documentation/index This Java code snippet shows how to define a POST route for the root path '/'. It accepts request and response objects and is typically used for creating resources. ```java post("/", (request, response) -> { // Create something }); ``` -------------------------------- ### Create Utility Method for Rendering Templates in SparkJava Source: https://sparkjava.com/documentation/index Illustrates how to create a static utility method to encapsulate template rendering logic within SparkJava. This promotes code reusability and simplifies route definitions by abstracting the process of creating and rendering a ModelAndView. ```java get("template-example", (req, res) -> { Map model = new HashMap<>(); return render(model, "path-to-template"); }); // declare this in a util-class public static String render(Map model, String templatePath) { return new VelocityTemplateEngine().render(new ModelAndView(model, templatePath)); } ``` -------------------------------- ### Path Grouping API Source: https://sparkjava.com/documentation/index Demonstrates how to group API routes using the `path()` method for better organization and modularity. ```APIDOC ## Path Grouping API ### Description This section details how to group related API routes using the `path()` method in Spark Java. It allows for prefixing routes and applying filters within a specific scope. ### Example Usage ```java path("/api", () -> { before("/*", (q, a) -> log.info("Received api call")); path("/email", () -> { post("/add", EmailApi.addEmail); put("/change", EmailApi.changeEmail); delete("/remove", EmailApi.deleteEmail); }); path("/username", () -> { post("/add", UserApi.addUsername); put("/change", UserApi.changeUsername); delete("/remove", UserApi.deleteUsername); }); }); ``` ``` -------------------------------- ### Render Template Directly in SparkJava Route Source: https://sparkjava.com/documentation/index Demonstrates the recommended way to render templates within a SparkJava route. It involves creating a model, instantiating a template engine, and calling its render method directly. This approach ensures templates are processed before the response is sent. ```java // do this get("template-example", (req, res) -> { Map model = new HashMap<>(); return new VelocityTemplateEngine().render( new ModelAndView(model, "path-to-template") ); }); ``` -------------------------------- ### Add Spark Java Ivy Dependency Source: https://sparkjava.com/documentation/index Shows the Ivy XML configuration for including the Spark Java core dependency in a project's ivy.xml file. ```xml ``` -------------------------------- ### Define WebSocket Route Source: https://sparkjava.com/documentation/index Creates a WebSocket route for full-duplex communication. This must be defined before regular HTTP routes and requires a path and a handler class. The `init()` method is needed if no HTTP routes follow. ```java webSocket("/echo", EchoWebSocket.class); init(); // Needed if you don't define any HTTP routes after your WebSocket routes ``` -------------------------------- ### Spark Java: Basic Redirect Source: https://sparkjava.com/documentation/index Trigger a browser redirect to a specified URL using the `redirect` method on the response object. ```java response.redirect("/bar"); ``` -------------------------------- ### Spark Java: Not Found (404) Handling - Route Source: https://sparkjava.com/documentation/index Configure custom handling for 404 Not Found errors using a Spark Route. This allows for dynamic response generation, such as returning JSON. ```java // Using Route notFound((req, res) -> { res.type("application/json"); return "{\"message\":\"Custom 404\"}"; }); ``` -------------------------------- ### Spark Java Static File Refresh (Development) Source: https://sparkjava.com/documentation/index Configures Spark Java to serve static files from an external directory during development for instant refreshes. ```java if (localhost) { String projectDir = System.getProperty("user.dir"); String staticDir = "/src/main/resources/public"; staticFiles.externalLocation(projectDir + staticDir); } else { staticFiles.location("/public"); } ``` -------------------------------- ### Define Basic HTTP DELETE Route Source: https://sparkjava.com/documentation/index Demonstrates the definition of a DELETE route for the root path '/' in a Spark Java application. Used for removing resources. ```java delete("/", (request, response) -> { // Annihilate something }); ``` -------------------------------- ### Configure Secure (HTTPS/SSL) Connection Source: https://sparkjava.com/documentation/index Enables secure HTTPS/SSL connections for the embedded Jetty server. Requires keystore and truststore file paths and passwords. Must be called before route mapping. ```java secure("keystoreFilePath", "keystorePassword", "truststoreFilePath", "truststorePassword"); ``` -------------------------------- ### Request Information API Source: https://sparkjava.com/documentation/index Details the various methods available through the `request` object to access client request information. ```APIDOC ## Request Information API ### Description Provides a comprehensive list of methods available on the `request` object to retrieve details about the incoming HTTP request, such as headers, parameters, body, IP address, and more. ### Available Request Methods - `request.attributes()`: Get all attributes. - `request.attribute(String key)`: Get a specific attribute. - `request.attribute(String key, String value)`: Set an attribute. - `request.body()`: Get the request body as a String. - `request.bodyAsBytes()`: Get the request body as byte array. - `request.contentLength()`: Get the content length of the request body. - `request.contentType()`: Get the content type of the request body. - `request.contextPath()`: Get the context path of the request. - `request.cookies()`: Get all request cookies. - `request.headers()`: Get all HTTP headers. - `request.headers(String name)`: Get a specific header value. - `request.host()`: Get the request host. - `request.ip()`: Get the client IP address. - `request.params(String name)`: Get a path parameter by name. - `request.params()`: Get all path parameters. - `request.pathInfo()`: Get the request path info. - `request.port()`: Get the server port. - `request.protocol()`: Get the request protocol. - `request.queryMap()`: Get the query map. - `request.queryMap(String key)`: Get a query map by key. - `request.queryParams()`: Get all query parameters. - `request.queryParams(String name)`: Get a query parameter by name. - `request.queryParamsValues(String name)`: Get all values for a query parameter. - `request.raw()`: Get the raw request object. - `request.requestMethod()`: Get the HTTP request method. - `request.scheme()`: Get the request scheme (http or https). - `request.servletPath()`: Get the servlet path. - `request.session()`: Get the session object. - `request.splat()`: Get splat parameters. - `request.uri()`: Get the request URI. - `request.url()`: Get the request URL. - `request.userAgent()`: Get the user agent string. ``` -------------------------------- ### Spark Java: Convenience Redirect API Source: https://sparkjava.com/documentation/index Use the convenience `redirect` API for redirects without needing direct access to the response object. Supports different HTTP methods and status codes. ```java // redirect a GET to "/fromPath" to "/toPath" redirect.get("/fromPath", "/toPath"); // redirect a POST to "/fromPath" to "/toPath", with status 303 redirect.post("/fromPath", "/toPath", Redirect.Status.SEE_OTHER); // redirect any request to "/fromPath" to "/toPath" with status 301 redirect.any("/fromPath", "/toPath", Redirect.Status.MOVED_PERMANENTLY); ``` -------------------------------- ### Default Spark Initialization Exception Handler Source: https://sparkjava.com/documentation/index Illustrates the default behavior of Spark Java's initialization exception handler. It logs the error and exits the application with a status code of 100. ```java private Consumer initExceptionHandler = (e) -> { LOG.error("ignite failed", e); System.exit(100); }; ``` -------------------------------- ### Spark Java SSL/HTTPS Configuration Source: https://sparkjava.com/documentation/index Configures Spark Java to use SSL/HTTPS by providing the keystore location and password. ```java String keyStoreLocation = "deploy/keystore.jks"; String keyStorePassword = "password"; secure(keyStoreLocation, keyStorePassword, null, null); ``` -------------------------------- ### Session Management API Source: https://sparkjava.com/documentation/index Explains how to manage user sessions on the server side, including creating, accessing, and modifying session attributes. ```APIDOC ## Session Management API ### Description This API enables server-side session management, allowing the application to maintain state across multiple requests from the same client. It covers session creation, attribute manipulation, and retrieval of session details. ### Session Methods - `request.session(boolean create)`: Create and return the session if it doesn't exist. - `request.session().attribute(String name)`: Get a session attribute. - `request.session().attribute(String name, Object value)`: Set a session attribute. - `request.session().removeAttribute(String name)`: Remove a session attribute. - `request.session().attributes()`: Get all session attributes. - `request.session().id()`: Get the session ID. - `request.session().isNew()`: Check if the session is new. - `request.session().raw()`: Return the underlying servlet session object. ``` -------------------------------- ### Query Maps API Source: https://sparkjava.com/documentation/index Illustrates how to use query maps to group and access request parameters with a common prefix. ```APIDOC ## Query Maps API ### Description This API allows for grouping request parameters that share a common prefix into maps, simplifying access to related parameters like `user[name]` and `user[age]`. ### Example Usage - `request.queryMap().get("user", "name").value()`: Get the value of `user[name]`. - `request.queryMap().get("user").get("name").value()`: Alternative way to get the value of `user[name]`. - `request.queryMap("user").get("age").integerValue()`: Get the integer value of `user[age]`. - `request.queryMap("user").toMap()`: Convert the "user" query map to a standard Map. ``` -------------------------------- ### Add Spark Java Gradle Dependency Source: https://sparkjava.com/documentation/index Provides the Gradle dependency declaration for the Spark Java core library, to be added to a project's build.gradle file. ```gradle compile "com.sparkjava:spark-core:2.9.4" ``` -------------------------------- ### Spark Java Query Map Handling Source: https://sparkjava.com/documentation/index Demonstrates how to group query parameters by prefix into maps using Spark Java's `queryMap()` functionality. This is useful for organizing parameters with similar naming conventions, such as those used in forms with nested structures. ```java request.queryMap().get("user", "name").value(); request.queryMap().get("user").get("name").value(); request.queryMap("user").get("age").integerValue(); request.queryMap("user").toMap(); ``` -------------------------------- ### Spark Java: Static Files Location (Classpath) Source: https://sparkjava.com/documentation/index Configure Spark Java to serve static files from a specified folder within the classpath. Files in the 'public' sub-directory of the classpath root will be accessible via URL paths without the 'public/' prefix. ```java // root is 'src/main/resources', so put files in 'src/main/resources/public' staticFiles.location("/public"); // Static files ``` -------------------------------- ### Add Jetbrick Template Engine Dependency Source: https://sparkjava.com/documentation/index This snippet shows how to add the Jetbrick template engine dependency to your Maven project. It's used for rendering HTML with Jetbrick. ```xml com.sparkjava spark-template-jetbrick 2.7.1 ``` -------------------------------- ### Stop Spark Server Source: https://sparkjava.com/documentation/index Demonstrates how to gracefully stop the Spark Java web server and clear all defined routes by calling the `stop()` method. ```java stop(); ``` -------------------------------- ### Spark Java File Upload Form Source: https://sparkjava.com/documentation/index HTML form for uploading files using the POST method and multipart/form-data enctype. Includes an input field for file selection. ```html
``` -------------------------------- ### Define Route with Splat Parameters Source: https://sparkjava.com/documentation/index This Java code illustrates defining a Spark Java route that uses splat (*) wildcards to capture multiple path segments. Captured segments are available as an array via `request.splat()`. ```java // matches "GET /say/hello/to/world" // request.splat()[0] is 'hello' and request.splat()[1] 'world' get("/say/*/to/*", (request, response) -> { return "Number of splat parameters: " + request.splat().length; }); ``` -------------------------------- ### Add Spark Java SBT Dependency Source: https://sparkjava.com/documentation/index This snippet provides the library dependency declaration for Spark Java core using SBT (Simple Build Tool), intended for build.sbt files. ```scala libraryDependencies += "com.sparkjava" % "spark-core" % "2.9.4" ``` -------------------------------- ### Spark Java Logging Dependency Source: https://sparkjava.com/documentation/index Maven dependency for enabling SLF4j logging in a Spark Java project. ```xml org.slf4j slf4j-simple 1.7.21 ``` -------------------------------- ### SparkJava Maven Dependency for Freemarker Template Engine Source: https://sparkjava.com/documentation/index Specifies the Maven dependency needed to use the Freemarker template engine with SparkJava. This enables the rendering of dynamic web content using Freemarker's templating capabilities. ```xml com.sparkjava spark-template-freemarker 2.7.1 ``` -------------------------------- ### SparkJava Maven Dependency for Pebble Template Engine Source: https://sparkjava.com/documentation/index Provides the Maven dependency coordinates for using the Pebble template engine with SparkJava. Pebble is a modern, Java-based template engine inspired by the Twig template language. ```xml com.sparkjava spark-template-pebble 2.7.1 ``` -------------------------------- ### Spark Java Route Grouping with Path Source: https://sparkjava.com/documentation/index Demonstrates how to group related routes in Spark Java using the `path()` method. This enhances organization for applications with numerous routes by allowing nested path declarations and shared filters. ```java path("/api", () -> { before("/*", (q, a) -> log.info("Received api call")); path("/email", () -> { post("/add", EmailApi.addEmail); put("/change", EmailApi.changeEmail); delete("/remove", EmailApi.deleteEmail); }); path("/username", () -> { post("/add", UserApi.addUsername); put("/change", UserApi.changeUsername); delete("/remove", UserApi.deleteUsername); }); }); ``` -------------------------------- ### Add Spark Kotlin Gradle Dependency Source: https://sparkjava.com/documentation/index This Gradle dependency snippet is for adding the Spark Kotlin library to a project's build.gradle file, specifically for Kotlin users. ```gradle compile "com.sparkjava:spark-kotlin:1.0.0-alpha" ``` -------------------------------- ### SparkJava Route Using Template Engine as Third Parameter (Deprecated) Source: https://sparkjava.com/documentation/index Shows a SparkJava route declaration where the template engine is provided as the third parameter. This method is noted as likely to be removed in future versions and is generally discouraged in favor of direct rendering within the route handler. ```java // don't do this get("template-example", (req, res) -> { Map model = new HashMap<>(); return new ModelAndView(model, "path-to-template"); }, new VelocityTemplateEngine()); ``` -------------------------------- ### Spark Java Session Management Source: https://sparkjava.com/documentation/index Details how to interact with server-side sessions in Spark Java, including creating sessions, retrieving and setting attributes, removing attributes, and accessing session metadata like ID and new status. ```java request.session(true); // create and return session request.session().attribute("user"); // Get session attribute 'user' request.session().attribute("user","foo"); // Set session attribute 'user' request.session().removeAttribute("user"); // Remove session attribute 'user' request.session().attributes(); // Get all session attributes request.session().id(); // Get session id request.session().isNew(); // Check if session is new request.session().raw(); // Return servlet object ``` -------------------------------- ### SparkJava Maven Dependency for Water Template Engine Source: https://sparkjava.com/documentation/index Lists the Maven dependency required to enable the Water template engine within a SparkJava application. Water is a template engine for Java. ```xml com.sparkjava spark-template-water 2.7.1 ``` -------------------------------- ### SparkJava Maven Dependency for Handlebars Template Engine Source: https://sparkjava.com/documentation/index Provides the Maven dependency configuration for using the Handlebars template engine within a SparkJava application. This allows developers to leverage Handlebars for templating HTML. ```xml com.sparkjava spark-template-handlebars 2.7.1 ``` -------------------------------- ### Wait for Server Initialization Source: https://sparkjava.com/documentation/index Causes the current thread to wait until the embedded Jetty server has been initialized. Useful for health checks or ensuring readiness before further operations. Initialization is triggered by defining routes/filters. ```java awaitInitialization(); // Wait for server to be initialized ``` -------------------------------- ### Configure ThreadPool with Min Threads and Timeout Source: https://sparkjava.com/documentation/index Configures the thread pool for the embedded Jetty server, specifying maximum threads, minimum threads, and idle timeout in milliseconds. This provides finer control over resource usage. ```java int maxThreads = 8; int minThreads = 2; int timeOutMillis = 30000; threadPool(maxThreads, minThreads, timeOutMillis); ``` -------------------------------- ### SparkJava Maven Dependency for Velocity Template Engine Source: https://sparkjava.com/documentation/index Provides the Maven dependency information required to integrate the Velocity template engine with SparkJava. This allows for rendering HTML views using Velocity templates. ```xml com.sparkjava spark-template-velocity 2.7.1 ``` -------------------------------- ### Spark Java: Internal Server Error (500) Handling - String/HTML Source: https://sparkjava.com/documentation/index Configure custom handling for 500 Internal Server Errors using a simple string or HTML content. ```java // Using string/html internalServerError("

Custom 500 handling

"); ``` -------------------------------- ### SparkJava Maven Dependency for Mustache Template Engine Source: https://sparkjava.com/documentation/index Lists the Maven dependency necessary for integrating the Mustache template engine with SparkJava. This facilitates the use of Mustache templates for generating HTML responses. ```xml com.sparkjava spark-template-mustache 2.7.1 ``` -------------------------------- ### Spark Java Cookie Management Source: https://sparkjava.com/documentation/index Shows how to manage cookies in Spark Java, covering both reading request cookies and setting, updating, and removing response cookies. Options for setting expiration and security flags are also included. ```java request.cookies(); // get map of all request cookies request.cookie("foo"); // access request cookie by name response.cookie("foo", "bar"); // set cookie with a value response.cookie("foo", "bar", 3600); // set cookie with a max-age response.cookie("foo", "bar", 3600, true); // secure cookie response.removeCookie("foo"); // remove cookie ``` -------------------------------- ### Response Manipulation API Source: https://sparkjava.com/documentation/index Details the methods available on the `response` object for manipulating the HTTP response. ```APIDOC ## Response Manipulation API ### Description Explains how to use the `response` object to control the content, headers, status code, and redirection of the HTTP response sent back to the client. ### Available Response Methods - `response.body()`: Get the current response body. - `response.body(String body)`: Set the response body. - `response.header(String name, String value)`: Set an HTTP header. - `response.raw()`: Get the raw response object. - `response.redirect(String location)`: Redirect the client to a new location. - `response.status()`: Get the current response status code. - `response.status(int statusCode)`: Set the response status code. - `response.type()`: Get the current content type. - `response.type(String contentType)`: Set the content type of the response. ``` -------------------------------- ### Spark Java: Static Files Custom Headers Source: https://sparkjava.com/documentation/index Set custom HTTP headers for static files. Multiple headers can be set, and using the same key multiple times will overwrite the previous value. ```java staticFiles.header("Key-1", "Value-1"); staticFiles.header("Key-1", "New-Value-1"); // Using the same key will overwrite value staticFiles.header("Key-2", "Value-2"); staticFiles.header("Key-3", "Value-3"); ``` -------------------------------- ### Spark Java File Upload Handler Source: https://sparkjava.com/documentation/index Spark Java route handler for processing file uploads. It configures multipart handling and reads the uploaded file's InputStream. ```java post("/yourUploadPath", (request, response) -> { request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp")); try (InputStream is = request.raw().getPart("uploaded_file").getInputStream()) { // Use the input stream to create a file } return "File uploaded"; }); ``` -------------------------------- ### Add Jinjava Template Engine Dependency Source: https://sparkjava.com/documentation/index This snippet shows how to add the Jinjava template engine dependency to your Maven project. It's used for rendering HTML with Jinjava. ```xml com.sparkjava spark-template-jinjava 2.7.1 ``` -------------------------------- ### Add Spark Kotlin Maven Dependency Source: https://sparkjava.com/documentation/index This snippet demonstrates how to include the Spark Kotlin library dependency in a Maven project's pom.xml. It is intended for projects using Kotlin with Spark Java. ```xml com.sparkjava spark-kotlin 1.0.0-alpha ``` -------------------------------- ### GZIP All Responses Using After-Filter Source: https://sparkjava.com/documentation/index Applies GZIP compression to all responses by adding the 'Content-Encoding: gzip' header in an after-filter. This ensures all outgoing data is compressed. ```java after((request, response) -> { response.header("Content-Encoding", "gzip"); }); ``` -------------------------------- ### Spark Java Response Manipulation Source: https://sparkjava.com/documentation/index Illustrates how to control and modify HTTP responses in Spark Java. This includes setting the response body, headers, status codes, and performing redirects. ```java response.body(); // get response content response.body("Hello"); // sets content to Hello response.header("FOO", "bar"); // sets header FOO with value bar response.raw(); // raw response handed in by Jetty response.redirect("/example"); // browser redirect to /example response.status(); // get the response status response.status(401); // set status code to 401 response.type(); // get the content type response.type("text/xml"); // set content type to text/xml ``` -------------------------------- ### Add Spark Java Maven Dependency Source: https://sparkjava.com/documentation/index This snippet shows how to add the Spark Java core dependency to a Maven project's pom.xml file. It specifies the group ID, artifact ID, and version required for the Spark Java library. ```xml com.sparkjava spark-core 2.9.4 ``` -------------------------------- ### Spark Java: Internal Server Error (500) Handling - Route Source: https://sparkjava.com/documentation/index Configure custom handling for 500 Internal Server Errors using a Spark Route. This allows for dynamic response generation, such as returning JSON. ```java // Using Route internalServerError((req, res) -> { res.type("application/json"); return "{\"message\":\"Custom 500 handling\"}"; }); ``` -------------------------------- ### Configure Spark Server Port Source: https://sparkjava.com/documentation/index Sets the port for the embedded Jetty web server. This must be called before declaring routes and filters. Default is 4567. ```java port(8080); // Spark will run on port 8080 ``` -------------------------------- ### Spark Java: Exception Mapping Source: https://sparkjava.com/documentation/index Handle specific custom exceptions across all routes and filters. Define a route that throws an exception and then map the exception type to a handler. ```java get("/throwexception", (request, response) -> { throw new YourCustomException(); }); exception(YourCustomException.class, (exception, request, response) -> { // Handle the exception here }); ``` -------------------------------- ### SparkJava Maven Dependency for Jade Template Engine Source: https://sparkjava.com/documentation/index Details the Maven dependency required to incorporate the Jade template engine into a SparkJava project. Jade is a high-performance template engine for Node.js and browsers, also available for Java. ```xml com.sparkjava spark-template-jade 2.7.1 ``` -------------------------------- ### SparkJava Maven Dependency for Thymeleaf Template Engine Source: https://sparkjava.com/documentation/index Specifies the Maven dependency for integrating the Thymeleaf template engine with SparkJava. Thymeleaf is a modern server-side Java template engine for both web and standalone environments. ```xml com.sparkjava spark-template-thymeleaf 2.7.1 ``` -------------------------------- ### SparkJava Maven Dependency for Jtwig Template Engine Source: https://sparkjava.com/documentation/index Specifies the Maven dependency for integrating the Jtwig template engine with SparkJava. Jtwig is a powerful template engine for Java, offering features similar to Jinja2. ```xml com.sparkjava spark-template-jtwig 2.7.1 ``` -------------------------------- ### Manually GZIP a Single Response Source: https://sparkjava.com/documentation/index Adds the 'Content-Encoding: gzip' header to a specific response within a route. This is done manually when GZIP is required for a single endpoint. ```java get("/some-path", (request, response) -> { // code for your get response.header("Content-Encoding", "gzip"); }); ``` -------------------------------- ### Unmap Route by Path Source: https://sparkjava.com/documentation/index Demonstrates how to remove all routes associated with a specific path string using the `unmap()` function in Spark Java. ```java unmap("/hello"); // unmaps all routes with path 'hello' ``` -------------------------------- ### Configure Maximum Threads for ThreadPool Source: https://sparkjava.com/documentation/index Sets the maximum number of threads for the embedded Jetty server's thread pool. This influences how many concurrent requests can be handled. ```java int maxThreads = 8; threadPool(maxThreads); ``` -------------------------------- ### Transform Response to JSON using Gson in SparkJava Source: https://sparkjava.com/documentation/index Implements a ResponseTransformer to convert model objects into JSON format using the Gson library. This is useful for API endpoints that return JSON data. It extends the ResponseTransformer interface and overrides the render method. ```java import com.google.gson.Gson; public class JsonTransformer implements ResponseTransformer { private Gson gson = new Gson(); @Override public String render(Object model) { return gson.toJson(model); } } ``` ```java get("/hello", "application/json", (request, response) -> { return new MyMessage("Hello World"); }, new JsonTransformer()); ``` ```java Gson gson = new Gson(); get("/hello", (request, response) -> new MyMessage("Hello World"), gson::toJson); ``` -------------------------------- ### Spark Java: Halt Request Execution Source: https://sparkjava.com/documentation/index Immediately stop a request within a filter or route using the `halt()` method. It can be used with or without HTTP status codes and custom messages. Note: `halt()` is not intended for use within exception mappers. ```java halt(); // halt halt(401); // halt with status halt("Body Message"); // halt with message halt(401, "Go away!"); // halt with status and message ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.