### Create a Basic Blade Hello World Application Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This Java code snippet provides a minimal `main` method to bootstrap a Blade web application. It initializes Blade, defines a GET route for the root path ('/'), and responds with 'Hello Blade' text. Running this will start the server, typically on port 9000. ```Java public static void main(String[] args) { Blade.create().get("/", ctx -> ctx.text("Hello Blade")).start(); } ``` -------------------------------- ### Configure SSL properties for INettySslCustomizer Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This snippet provides example `application.properties` settings required when using a custom `INettySslCustomizer`, including keystore details. ```bash server.ssl.enable=true server.keystore.path=fully qualified path server.keystore.type=PKCS12 server.keystore.password=mypass server.keystore.alias=optional alias ``` -------------------------------- ### Register INettySslCustomizer with Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This Java snippet demonstrates how to register a custom `INettySslCustomizer` implementation with the Blade application instance before starting it. ```java MyNettySslCustomizer nc = new MyNettySslCustomizer(); Blade.create() .setNettySslCustomizer(nc) .start(App.class, args); } ``` -------------------------------- ### Configure Logging in Blade with SLF4J Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to use SLF4J for logging in a Blade application. It shows examples of logging messages at different levels: info, warn, debug, and error. ```Java private static final Logger log = LoggerFactory.getLogger(Hello.class); public static void main(String[] args) { log.info("Hello Info, {}", "2017"); log.warn("Hello Warn"); log.debug("Hello Debug"); log.error("Hello Error"); } ``` -------------------------------- ### SLF4J SimpleLogger Configuration Properties Example Source: https://github.com/lets-blade/blade/blob/v2.1.3/blade-core/src/test/resources/log_config.txt An illustrative .properties file showcasing the configurable parameters for SLF4J's SimpleLogger. These settings allow fine-grained control over logging verbosity, output format, and the inclusion of contextual information in log messages. ```Configuration # SLF4J's SimpleLogger configuration file # Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err. # Default logging detail level for all instances of SimpleLogger. # Must be one of ("trace", "debug", "info", "warn", or "error"). # If not specified, defaults to "info". #blade.log.defaultLogLevel=info # Logging detail level for a SimpleLogger instance named "xxxxx". # Must be one of ("trace", "debug", "info", "warn", or "error"). # If not specified, the default logging detail level is used. #blade.log.logger.xxxxx= # Set to true if you want the current date and time to be included in output messages. # Default is false, and will output the number of milliseconds elapsed since startup. #blade.log.showDateTime=false # The date and time format to be used in the output messages. # The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. # If the format is not specified or is invalid, the default format is used. # The default format is yyyy-MM-dd HH:mm:ss:SSS Z. #blade.log.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z # Set to true if you want to output the current thread name. # Defaults to true. #blade.log.showThreadName=true # Set to true if you want the Logger instance name to be included in output messages. # Defaults to true. #blade.log.showLogName=true # Set to true if you want the last component of the name to be included in output messages. # Defaults to false. #blade.log.showShortLogName=false ``` -------------------------------- ### Handle Redirects in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows how to implement a server-side redirect in a Blade application using the `ctx.redirect()` method within a route handler. This example redirects to an external URL. ```Java @GET("redirect") public void redirectToGithub(RouteContext ctx){ ctx.redirect("https://github.com/hellokaton"); } ``` -------------------------------- ### Implement Web Hooks in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Explains how to use Blade's `WebHook` interface to intercept requests before or after route execution. The example shows a global `before` hook that prints a message for all incoming requests. ```Java public static void main(String[] args) { // All requests are exported before execution before Blade.create().before("/*", ctx -> { System.out.println("before..."); }).start(); } ``` -------------------------------- ### Write Cookies in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to set cookies in a Blade application using `ctx.cookie()`. It shows examples of setting a simple key-value cookie and a cookie with an expiration time. ```Java @GET("write-cookie") public void writeCookie(RouteContext ctx){ ctx.cookie("hello", "world"); ctx.cookie("UID", "22", 3600); } ``` -------------------------------- ### Handle Form Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Demonstrates how to retrieve form parameters using `RouteContext` or the `@Form` annotation in Blade. Includes a `curl` example for testing form data submission. ```java public static void main(String[] args) { Blade.create().get("/user", ctx -> { Integer age = ctx.fromInt("age"); System.out.println("age is:" + age); }).start(); } ``` ```java @POST("/save") public void savePerson(@Form String username, @Form Integer age){ System.out.println("username is:" + username + ", age is:" + age); } ``` ```bash curl -X POST http://127.0.0.1:9000/save -F username=jack -F age=16 ``` -------------------------------- ### Register Routes with Hardcoded Paths in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to register GET, POST, PUT, and DELETE routes directly using the Blade instance in the main method. This approach hardcodes the paths and their corresponding handlers for simple route definitions. ```java public static void main(String[] args) { // Create multiple routes GET, POST, PUT, DELETE using Blade instance Blade.create() .get("/user/21", getting) .post("/save", posting) .delete("/remove", deleting) .put("/putValue", putting) .start(); } ``` -------------------------------- ### Handle Restful Path Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Shows how to extract path parameters from URLs using `RouteContext` or the `@PathParam` annotation in Blade. Includes examples for single and multiple path parameters, and a `curl` command for testing. ```java public static void main(String[] args) { Blade blade = Blade.create(); // Create a route: /user/:uid blade.get("/user/:uid", ctx -> { Integer uid = ctx.pathInt("uid"); ctx.text("uid : " + uid); }); // Create two parameters route blade.get("/users/:uid/post/:pid", ctx -> { Integer uid = ctx.pathInt("uid"); Integer pid = ctx.pathInt("pid"); String msg = "uid = " + uid + ", pid = " + pid; ctx.text(msg); }); // Start blade blade.start(); } ``` ```java @GET("/users/:username/:page") public void userTopics(@PathParam String username, @PathParam Integer page){ System.out.println("username is:" + username + ", page is:" + page); } ``` ```bash curl -X GET http://127.0.0.1:9000/users/hellokaton/2 ``` -------------------------------- ### Get Environment Variables in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to access application environment variables configured in Blade. It retrieves the 'app.version' property, providing a default value if not found. ```java Environment environment = WebContext.blade().environment(); String version = environment.get("app.version", "0.0.1"); ``` -------------------------------- ### Retrieve Request Body Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Illustrates how to read the entire request body as a string using `RouteContext.bodyToString()` and the `@Body` annotation. A `curl` example demonstrates sending a JSON body to the endpoint. ```java public static void main(String[] args) { Blade.create().post("/body", ctx -> { System.out.println("body string is:" + ctx.bodyToString()); }).start(); } ``` ```java @POST("/body") public void readBody(@Body String data){ System.out.println("data is:" + data); } ``` ```bash curl -X POST http://127.0.0.1:9000/body -d '{"username":"hellokaton","age":22}' ``` -------------------------------- ### Perform CORS GET Request with jQuery Source: https://github.com/lets-blade/blade/blob/v2.1.3/blade-examples/cors.html This JavaScript snippet uses jQuery to perform a GET request to a user-defined URL. It includes logic to add an Authorization Bearer token to the request header if provided. The request uses 'application/x-www-form-urlencoded' content type and alerts 'success' on a successful response. ```JavaScript $("#cors").on('click', function (event) { event.preventDefault(); var url2 = $("#urlText").val(); $.get({ contentType: 'application/x-www-form-urlencoded;charset=UTF-8', url: url2, beforeSend: function (xhr) { if ($("#tokenTxt").val().trim()) { /* Authorization header */ xhr.setRequestHeader("Authorization", "Bearer " + $("#tokenTxt").val()); } }, success: function (data) { alert("success"); } }) }); ``` -------------------------------- ### Read HTTP Headers in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Provides examples for accessing HTTP headers like 'Host', 'User-Agent', and client IP address using `RouteContext` or by injecting specific headers with the `@Header` annotation. ```java @GET("header") public void readHeader(RouteContext ctx){ System.out.println("Host => " + ctx.header("Host")); // get useragent System.out.println("UserAgent => " + ctx.userAgent()); // get client ip System.out.println("Client Address => " + ctx.address()); } ``` ```java @GET("header") public void readHeader(@Header String host){ System.out.println("Host => " + host); } ``` -------------------------------- ### Handle File Uploads in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates two methods for handling file uploads in Blade: accessing the `FileItem` from the `Request` object or directly injecting it using the `@Multipart` annotation. Both examples show how to move the uploaded file to a new location. ```java @POST("upload") public void upload(Request request){ request.fileItem("img").ifPresent(fileItem -> { fileItem.moveTo(new File(fileItem.getFileName())); }); } ``` ```java @POST("upload") public void upload(@Multipart FileItem fileItem){ // Save to new path fileItem.moveTo(new File(fileItem.getFileName())); } ``` -------------------------------- ### Handle Request Body Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Illustrates how to read the request body as a string using `RouteContext.bodyToString()` or by injecting it directly with the `@Body` annotation. A `curl` example demonstrates sending JSON data in the request body. ```java public static void main(String[] args) { Blade.create().post("/body", ctx -> { System.out.println("body string is:" + ctx.bodyToString()); }).start(); } ``` ```java @POST("/body") public void readBody(@Body String data){ System.out.println("data is:" + data); } ``` ```bash curl -X POST http://127.0.0.1:9000/body -d '{"username":"hellokaton","age":22}' ``` -------------------------------- ### Retrieve Path Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Explains how to capture values directly from URL paths using `RouteContext.pathInt()` for single or multiple parameters, and through the `@PathParam` annotation. Includes a `curl` example for testing path variable extraction. ```java public static void main(String[] args) { Blade blade = Blade.create(); // Create a route: /user/:uid blade.get("/user/:uid", ctx -> { Integer uid = ctx.pathInt("uid"); ctx.text("uid : " + uid); }); // Create two parameters route blade.get("/users/:uid/post/:pid", ctx -> { Integer uid = ctx.pathInt("uid"); Integer pid = ctx.pathInt("pid"); String msg = "uid = " + uid + ", pid = " + pid; ctx.text(msg); }); // Start blade blade.start(); } ``` ```java @GET("/users/:username/:page") public void userTopics(@PathParam String username, @PathParam Integer page){ System.out.println("username is:" + usernam + ", page is:" + page); } ``` ```bash curl -X GET http://127.0.0.1:9000/users/hellokaton/2 ``` -------------------------------- ### Register Routes using Controller Annotations in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Illustrates how to define routes within a controller class using `@Path`, `@GET`, and `@POST` annotations. This method promotes a more structured and modular approach to route management, including handling JSON responses. ```java @Path public class IndexController { @GET("/login") public String login(){ return "login.html"; } @POST(value = "/login", responseType = ResponseType.JSON) public RestResponse doLogin(RouteContext ctx){ // do something return RestResponse.ok(); } } ``` -------------------------------- ### Set HTTP Cookies in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Explains how to set cookies in the HTTP response using `RouteContext.cookie()` in Blade. This includes examples for setting a simple key-value cookie and a cookie with a specified expiration time. ```Java @GET("write-cookie") public void writeCookie(RouteContext ctx){ ctx.cookie("hello", "world"); ctx.cookie("UID", "22", 3600); } ``` -------------------------------- ### Retrieve URL Query Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows two methods for accessing URL query parameters: directly via `RouteContext` and declaratively using the `@Query` annotation. Includes a `curl` example to test the endpoint by sending an 'age' parameter. ```java public static void main(String[] args) { Blade.create().get("/user", ctx -> { Integer age = ctx.queryInt("age"); System.out.println("age is:" + age); }).start(); } ``` ```java @GET("/user") public void savePerson(@Query Integer age){ System.out.println("age is:" + age); } ``` ```bash curl -X GET http://127.0.0.1:9000/user?age=25 ``` -------------------------------- ### Map Request Parameters to Java Objects in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Explains how to automatically map form or body parameters to a Java POJO (Plain Old Java Object) using the `@Form` or `@Body` annotations. Includes examples for custom model names and `curl` commands for testing. ```java public class User { private String username; private Integer age; // getter and setter } ``` ```java @POST("/users") public void saveUser(@Form User user) { System.out.println("user => " + user); } ``` ```bash curl -X POST http://127.0.0.1:9000/users -F username=jack -F age=16 ``` ```java @POST("/users") public void saveUser(@Form(name="u") User user) { System.out.println("user => " + user); } ``` ```bash curl -X POST http://127.0.0.1:9000/users -F u[username]=jack -F u[age]=16 ``` ```java @POST("/body") public void body(@Body User user) { System.out.println("user => " + user); } ``` ```bash curl -X POST http://127.0.0.1:9000/body -d '{"username":"hellokaton","age":22}' ``` -------------------------------- ### Read HTTP Cookies in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Illustrates two ways to read HTTP cookies in Blade: accessing them via the `RouteContext` or directly injecting a specific cookie value using the `@Cookie` annotation. An example shows retrieving a 'UID' cookie. ```java @GET("cookie") public void readCookie(RouteContext ctx){ System.out.println("UID => " + ctx.cookie("UID")); } ``` ```java @GET("cookie") public void readCookie(@Cookie String uid){ System.out.println("Cookie UID => " + uid); } ``` -------------------------------- ### Read HTTP Headers in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows two methods to read HTTP request headers in Blade: directly from the `RouteContext` or by injecting a specific header value using the `@Header` annotation. Examples include retrieving Host, User-Agent, and Client IP. ```java @GET("header") public void readHeader(RouteContext ctx){ System.out.println("Host => " + ctx.header("Host")); // get useragent System.out.println("UserAgent => " + ctx.userAgent()); // get client ip System.out.println("Client Address => " + ctx.address()); } ``` ```java @GET("header") public void readHeader(@Header String host){ System.out.println("Host => " + host); } ``` -------------------------------- ### Sample INettySslCustomizer implementation for custom SSL context Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This Java class provides a sample implementation of `INettySslCustomizer` to create a custom `SslContext` by loading a keystore from application properties. It includes error handling for keystore validation. ```java public class MyNettySSLCustomizer implements INettySslCustomizer { public SslContext getCustomSslContext(Blade blade) { SslContext sslctx = null; // get my custom properties from the environment String keystoreType = blade.getEnv("server.keystore.type", null); String keystorePath = blade.getEnv("server.keystore.path", null); String keystorePass = blade.getEnv("server.keystore.password", null); if (verifyKeystore(keystoreType, keystorePath, keystorePass)) { try (FileInputStream instream = new FileInputStream(new File(keystorePath))) { // verify I can load store and password is valid KeyStore keystore = KeyStore.getInstance(keystoreType); char[] storepw = keystorePass.toCharArray(); keystore.load(instream, storepw); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, storepw); sslctx = SslContextBuilder.forServer(kmf).build(); } catch (Exception ex) { log.error("Keystore validation failed " + ex.getMessage()); } } else { log.error("Unable to load keystore, sslContext creation failed."); } return sslctx; } ``` -------------------------------- ### Handle File Downloads and Previews in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Demonstrates how to serve files for download (`ResponseType.STREAM`) or for in-browser preview (`ResponseType.PREVIEW`) using `Response.write()`. ```java @GET(value = "/download", responseType = ResponseType.STREAM) public void download(Response response) throws IOException { response.write("abcd.pdf", new File("146373013842336153820220427172437.pdf")); } ``` ```java @GET(value = "/preview", responseType = ResponseType.PREVIEW) public void preview(Response response) throws IOException { response.write(new File("146373013842336153820220427172437.pdf")); } ``` -------------------------------- ### Serve Files for Download or Preview in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows how to serve files from a Blade application, either for direct download (`ResponseType.STREAM`) or for in-browser preview (`ResponseType.PREVIEW`). Both methods use `response.write()` to send the file content. ```java @GET(value = "/download", responseType = ResponseType.STREAM) public void download(Response response) throws IOException { response.write("abcd.pdf", new File("146373013842336153820220427172437.pdf")); } ``` ```java @GET(value = "/preview", responseType = ResponseType.PREVIEW) public void preview(Response response) throws IOException { response.write(new File("146373013842336153820220427172437.pdf")); } ``` -------------------------------- ### Configure and Render Jetbrick Template Engine in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Illustrates how to integrate and use the Jetbrick template engine with Blade. It includes configuration via a BladeLoader, passing complex objects (like a User) to the template, and demonstrating conditional logic within the Jetbrick HTML template. ```Java @Bean public class TemplateConfig implements BladeLoader { @Override public void load(Blade blade) { blade.templateEngine(new JetbrickTemplateEngine()); } } ``` ```Java public static void main(String[] args) { Blade.create().get("/hello", ctx -> { User user = new User("hellokaton", 50); ctx.attribute("user", user); ctx.render("hello.html"); }).start(Hello.class, args); } ``` ```HTML Hello Page

Hello, ${user.username}

#if(user.age > 18)

Good Boy!

#else

Gooood Baby!

#end ``` -------------------------------- ### Access Environment Configuration in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Demonstrates how to retrieve application environment properties using `WebContext.blade().environment()`. Also shows how to configure static resources via `application.properties`. ```java Environment environment = WebContext.blade().environment(); String version = environment.get("app.version", "0.0.1"); ``` -------------------------------- ### Configure SSL using application.properties Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This snippet shows basic SSL configuration parameters for `application.properties` in a Blade application, enabling SSL and specifying paths for the certificate and private key. ```bash server.ssl.enable=true server.ssl.cert-path=cert.pem server.ssl.private-key-path=private_key.pem server.ssl.private-key-pass=123456 ``` -------------------------------- ### Configure and Render Default Blade Templates Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Explains how to set up and render templates using Blade's default built-in template engine. By default, template files are expected to be located in the `templates` directory. ```Java public static void main(String[] args) { Blade.create().get("/hello", ctx -> { ctx.attribute("name", "hellokaton"); ctx.render("hello.html"); }).start(Hello.class, args); } ``` ```HTML Hello Page

Hello, ${name}

``` -------------------------------- ### Implement Basic Authentication in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Demonstrates how to enable Basic Authentication using Blade's built-in `BasicAuthMiddleware`. It also explains how to configure the required username and password credentials within the `application.properties` file. ```Java public static void main(String[] args) { Blade.create().use(new BasicAuthMiddleware()).start(); } ``` ```Bash http.auth.username=admin http.auth.password=123456 ``` -------------------------------- ### Configure and Render Default Blade Template Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to set up a basic Blade application to render an HTML template using the built-in default template engine. It shows how to pass data from the server to the template. ```Java public static void main(String[] args) { Blade.create().get("/hello", ctx -> { ctx.attribute("name", "hellokaton"); ctx.render("hello.html"); }).start(Hello.class, args); } ``` ```HTML Hello Page

Hello, ${name}

``` -------------------------------- ### Integrate and Use Jetbrick Template Engine with Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Details how to integrate the Jetbrick template engine into a Blade application by implementing `BladeLoader` and configuring it. It also shows how to pass data to the template and use conditional logic within the Jetbrick template. ```Java @Bean public class TemplateConfig implements BladeLoader { @Override public void load(Blade blade) { blade.templateEngine(new JetbrickTemplateEngine()); } } ``` ```Java public static void main(String[] args) { Blade.create().get("/hello", ctx -> { User user = new User("hellokaton", 50); ctx.attribute("user", user); ctx.render("hello.html"); }).start(Hello.class, args); } ``` ```HTML Hello Page

Hello, ${user.username}

#if(user.age > 18)

Good Boy!

#else

Gooood Baby!

#end ``` -------------------------------- ### Implement Basic Authentication in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows how to enable basic authentication using Blade's built-in `BasicAuthMiddleware`. It also explains how to configure the username and password in the `application.properties` file. ```Java public static void main(String[] args) { Blade.create().use(new BasicAuthMiddleware()).start(); } ``` ```Bash http.auth.username=admin http.auth.password=123456 ``` -------------------------------- ### Configure and Use Sessions in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Explains how to enable session functionality programmatically or via configuration, and how to store attributes in the session using `Session.attribute()`. ```java Blade.create() .http(HttpOptions::enableSession) .start(Application.class, args); ``` ```properties http.session.enabled=true ``` ```java public void login(Session session){ // if login success session.attribute("login_key", SOME_MODEL); } ``` -------------------------------- ### Configure and Use Logging in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Describes how Blade uses `slf4j-api` as its logging interface, providing a simple default implementation. It demonstrates how to obtain a logger instance and output messages at various log levels (info, warn, debug, error). ```Java private static final Logger log = LoggerFactory.getLogger(Hello.class); public static void main(String[] args) { log.info("Hello Info, {}", "2017"); log.warn("Hello Warn"); log.debug("Hello Debug"); log.error("Hello Error"); } ``` -------------------------------- ### Configure SSL for Blade Server Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Details how to enable and configure SSL for a Blade server using properties in `application.properties`. This includes specifying the certificate path, private key path, and private key password. ```Bash server.ssl.enable=true server.ssl.cert-path=cert.pem server.ssl.private-key-path=private_key.pem server.ssl.private-key-pass=123456 ``` -------------------------------- ### Configure Static Resources in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Explains how to add custom static resource directories programmatically using `Blade.addStatics()` or declaratively in `application.properties`. ```java Blade.create().addStatics("/mydir"); ``` ```properties mvc.statics=/mydir ``` -------------------------------- ### Handle File Uploads in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Illustrates how to process file uploads using `Request.fileItem()` or by directly injecting `FileItem` with the `@Multipart` annotation. Shows how to save the uploaded file. ```java @POST("upload") public void upload(Request request){ request.fileItem("img").ifPresent(fileItem -> { fileItem.moveTo(new File(fileItem.getFileName())); }); } ``` ```java @POST("upload") public void upload(@Multipart FileItem fileItem){ // 保存到新位置 fileItem.moveTo(new File(fileItem.getFileName())); } ``` -------------------------------- ### Blade Response Render API Documentation Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Provides a link to the Javadoc for the `render` method in Blade's `Response` class, which is used for rendering views with a `ModelAndView` object. ```APIDOC http://static.javadoc.io/com.hellokaton/blade-core/2.1.2.RELEASE/com/hellokaton/blade/mvc/http/Response.html#render-com.ModelAndView- ``` -------------------------------- ### Blade Response Redirect API Documentation Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Provides a link to the Javadoc for the `redirect` method in Blade's `Response` class, used for performing HTTP redirects. ```APIDOC http://static.javadoc.io/com.hellokaton/blade-core/2.1.2.RELEASE/com/hellokaton/blade/mvc/http/Response.html#redirect-java.lang.String- ``` -------------------------------- ### Add Blade Core Dependency with Gradle Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This line demonstrates how to add the `blade-core` library as a compile-time dependency in your Gradle `build.gradle` file. Place this within the `dependencies` block of your project. ```Gradle compile 'com.hellokaton:blade-core:2.1.2.RELEASE' ``` -------------------------------- ### Implement Route Interceptors (WebHooks) in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Shows how to use Blade's `WebHook` interface to intercept requests before they are executed. This allows for implementing global pre-processing logic or security checks across all routes. ```Java public static void main(String[] args) { // All requests are exported before execution before Blade.create().before("/*", ctx -> { System.out.println("before..."); }).start(); } ``` -------------------------------- ### Add Blade Core Dependency with Maven Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This XML snippet shows how to include the `blade-core` library as a dependency in your Maven `pom.xml` file. Ensure you place this within the `` section of your project. ```XML com.hellokaton blade-core 2.1.2.RELEASE ``` -------------------------------- ### Blade Application Core Configuration Source: https://github.com/lets-blade/blade/blob/v2.1.3/blade-core/src/test/resources/demo_config.txt Defines core application settings including development mode, application name, monitoring, HTTP GZIP, session management, MVC view mappings, static resource handling, template paths, and server address/port. ```Properties app.devMode=false app.name=hello app.monitor.enable=true http.gzip.enable=true http.session.key=SESSION http.session.timeout=7200 mvc.view.404=/comm/page_404.html mvc.view.500=/comm/page_404.html mvc.statics=/upload/ mvc.statics.list=false mvc.template.path=/templates/ server.address=127.0.0.1 server.port=9000 ``` -------------------------------- ### Blade Response Cookie API Documentation Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Provides a link to the Javadoc for the `cookie` methods in Blade's `Response` class, used for setting HTTP cookies. ```APIDOC http://static.javadoc.io/com.hellokaton/blade-core/2.1.2.RELEASE/com/hellokaton/blade/mvc/http/Response.html#cookie-java.lang.String-java.lang.String- ``` -------------------------------- ### Enable and Use Sessions in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Explains how to enable sessions in Blade, either programmatically or via configuration, and demonstrates how to set a session attribute using the `Session` object. Sessions are disabled by default. ```java Blade.create() .http(HttpOptions::enableSession) .start(Application.class, args); ``` ```java public void login(Session session){ // if login success session.attribute("login_key", SOME_MODEL); } ``` -------------------------------- ### Configure Static Resources in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Explains how to configure custom static resource directories in Blade, either programmatically using `Blade.create().addStatics()` or declaratively in the `application.properties` file. By default, resources are served from the classpath's 'static' directory. ```java Blade.create().addStatics("/mydir"); ``` ```bash mvc.statics=/mydir ``` -------------------------------- ### Configure Server Port in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Explains three methods to change the server port for a Blade application: hardcoding the port in Java code, specifying it in the `application.properties` configuration file, and passing it as a command-line argument during application startup. ```Java Blade.create().listen(9001).start(); ``` ```Bash server.port=9001 ``` ```Bash java -jar blade-app.jar --server.port=9001 ``` -------------------------------- ### SLF4J SimpleLogger Configuration Properties Source: https://github.com/lets-blade/blade/blob/v2.1.3/blade-kit/src/test/resources/log_config.txt Details the various configuration properties available for customizing SLF4J's SimpleLogger behavior, including log levels, output format, and content. ```APIDOC Property: blade.log.defaultLogLevel Description: Default logging detail level for all instances of SimpleLogger. Values: "trace", "debug", "info", "warn", or "error" Default: "info" Property: blade.log.logger.xxxxx Description: Logging detail level for a SimpleLogger instance named "xxxxx". Values: "trace", "debug", "info", "warn", or "error" Default: Uses defaultLogLevel Property: blade.log.showDateTime Description: Set to true if you want the current date and time to be included in output messages. Values: true, false Default: false (outputs the number of milliseconds elapsed since startup) Property: blade.log.dateTimeFormat Description: The date and time format to be used in the output messages. Format: The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. Default: yyyy-MM-dd HH:mm:ss:SSS Z Property: blade.log.showThreadName Description: Set to true if you want to output the current thread name. Values: true, false Default: true Property: blade.log.showLogName Description: Set to true if you want the Logger instance name to be included in output messages. Values: true, false Default: true Property: blade.log.showShortLogName Description: Set to true if you want the last component of the name to be included in output messages. Values: true, false Default: false ``` -------------------------------- ### Perform HTTP Redirects in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Demonstrates how to redirect a client to a different URL using the `RouteContext.redirect()` method in Blade. This is useful for navigating users to external sites or other routes within the application. ```Java @GET("redirect") public void redirectToGithub(RouteContext ctx){ ctx.redirect("https://github.com/hellokaton"); } ``` -------------------------------- ### Implement Custom Exception Handling in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Shows how to extend Blade's `DefaultExceptionHandler` to implement custom logic for specific exception types. This allows developers to provide tailored error responses or perform specific actions based on the type of exception caught. ```Java @Bean public class GolbalExceptionHandler extends DefaultExceptionHandler { @Override public void handle(Exception e) { if (e instanceof CustomException) { CustomException customException = (CustomException) e; String code = customException.getCode(); // do something } else { super.handle(e); } } } ``` -------------------------------- ### Render HTML Responses in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Illustrates how to render HTML content in Blade. You can achieve this by using the `RouteContext.html()` method or by specifying `ResponseType.HTML` in the route annotation. ```Java @GET("html") public void printHtml(RouteContext ctx){ ctx.html("

I Love Blade!

"); } ``` ```Java @GET(value = "/html", responseType = ResponseType.HTML) public String printHtml(RouteContext ctx){ return "

I Love Blade!

"; } ``` -------------------------------- ### APIDOC: Response.redirect Method Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Documentation for the `redirect` method within Blade's `Response` class, used for performing HTTP redirects. This method takes a string representing the target URL for the redirection. ```APIDOC com.hellokaton.blade.mvc.http.Response redirect(location: java.lang.String) ``` -------------------------------- ### Render HTML Response in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates two approaches to render HTML responses in Blade: using `RouteContext.html()` to send an HTML string, or by returning an HTML string directly from a method annotated with `ResponseType.HTML`. ```java @GET("html") public void printHtml(RouteContext ctx){ ctx.html("

I Love Blade!

"); } ``` ```java @GET(value = "/html", responseType = ResponseType.HTML) public String printHtml(RouteContext ctx){ return "

I Love Blade!

"; } ``` -------------------------------- ### Render Text Responses in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Shows how to return plain text responses in Blade. This can be done by using the `RouteContext.text()` method or by setting `ResponseType.TEXT` in the route annotation for a cleaner syntax. ```Java @GET("text") public void printText(RouteContext ctx){ ctx.text("I Love Blade!"); } ``` ```Java @GET(value = "/text", responseType = ResponseType.TEXT) public String printText(RouteContext ctx){ return "I Love Blade!"; } ``` -------------------------------- ### APIDOC: Response.render Method Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Documentation for the `render` method within Blade's `Response` class, used for rendering views or templates. This method typically takes a `ModelAndView` object to specify the view name and data. ```APIDOC com.hellokaton.blade.mvc.http.Response render(modelAndView: com.ModelAndView) ``` -------------------------------- ### Parse Form Parameters to Model by Annotation in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to bind form parameters directly to a Java model using the `@Form` annotation in Blade. The `User` object is automatically populated from the request parameters. Includes a curl command to test the endpoint. ```java @POST("/users") public void saveUser(@Form User user) { System.out.println("user => " + user); } ``` ```bash curl -X POST http://127.0.0.1:9000/users -F username=jack -F age=16 ``` -------------------------------- ### Render JSON Responses in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Demonstrates how to render JSON data using the Blade framework. This can be achieved either by directly using the `RouteContext.json()` method or by specifying `ResponseType.JSON` in the route annotation for a more concise approach. ```Java @GET("users/json") public void printJSON(RouteContext ctx){ User user = new User("hellokaton", 18); ctx.json(user); } ``` ```Java @GET(value = "/users/json", responseType = ResponseType.JSON) public User printJSON(){ return new User("hellokaton", 18); } ``` -------------------------------- ### Change Server Port in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Outlines three methods to modify the server port for a Blade application: hardcoding it in Java, configuring it in `application.properties`, and passing it as a command-line argument during startup. ```Java Blade.create().listen(9001).start(); ``` ```Bash server.port=9001 ``` ```Bash java -jar blade-app.jar --server.port=9001 ``` -------------------------------- ### APIDOC: Response.cookie Methods Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Documentation for the `cookie` methods within Blade's `Response` class, used for setting HTTP cookies. Overloaded methods allow setting a simple key-value cookie or a cookie with an additional `maxAge` parameter for expiration. ```APIDOC com.hellokaton.blade.mvc.http.Response cookie(name: java.lang.String, value: java.lang.String) cookie(name: java.lang.String, value: java.lang.String, maxAge: int) ``` -------------------------------- ### Read HTTP Cookies in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README_CN.md Shows how to retrieve cookie values using `RouteContext.cookie()` or by injecting a specific cookie value with the `@Cookie` annotation. ```java @GET("cookie") public void readCookie(RouteContext ctx){ System.out.println("UID => " + ctx.cookie("UID")); } ``` ```java @GET("cookie") public void readCookie(@Cookie String UID){ System.out.println("Cookie UID => " + UID); } ``` -------------------------------- ### Define User Model for Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Defines a simple Java POJO (Plain Old Java Object) representing a User with username and age properties. This model is used for data binding in Blade applications. ```java public class User { private String username; private Integer age; // getter and setter } ``` -------------------------------- ### Retrieve Form Parameters in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Demonstrates how to extract form parameters from requests using `RouteContext`'s `fromInt` method and the `@Form` annotation. A `curl` command is provided for testing form data submission with 'username' and 'age' fields. ```java public static void main(String[] args) { Blade.create().get("/user", ctx -> { Integer age = ctx.fromInt("age"); System.out.println("age is:" + age); }).start(); } ``` ```java @POST("/save") public void savePerson(@Form String username, @Form Integer age){ System.out.println("username is:" + username + ", age is:" + age); } ``` ```bash curl -X POST http://127.0.0.1:9000/save -F username=jack -F age=16 ``` -------------------------------- ### Render Plain Text Response in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows two methods to render plain text responses in Blade: using `RouteContext.text()` to send a string, or by returning a string directly from a method annotated with `ResponseType.TEXT`. ```java @GET("text") public void printText(RouteContext ctx){ ctx.text("I Love Blade!"); } ``` ```java @GET(value = "/text", responseType = ResponseType.TEXT) public String printText(RouteContext ctx){ return "I Love Blade!"; } ``` -------------------------------- ### Implement custom exception handler in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md This Java snippet shows how to create a custom exception handler by extending `DefaultExceptionHandler` and overriding the `handle` method to process specific exception types like `CustomException`. ```java @Bean public class GlobalExceptionHandler extends DefaultExceptionHandler { @Override public void handle(Exception e) { if (e instanceof CustomException) { CustomException customException = (CustomException) e; String code = customException.getCode(); // do something } else { super.handle(e); } } } ``` -------------------------------- ### Parse Request Body to Model in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Illustrates how to bind a JSON request body directly to a Java model using the `@Body` annotation in Blade. This is useful for handling JSON payloads. Includes a curl command to test the endpoint with a JSON body. ```java @POST("/body") public void body(@Body User user) { System.out.println("user => " + user); } ``` ```bash curl -X POST http://127.0.0.1:9000/body -d '{"username":"hellokaton","age":22}' ``` -------------------------------- ### Render JSON Response in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Provides two ways to render JSON responses in Blade: using `RouteContext.json()` to send a Java object as JSON, or by returning the object directly from a method annotated with `ResponseType.JSON`. ```java @GET("users/json") public void printJSON(RouteContext ctx){ User user = new User("hellokaton", 18); ctx.json(user); } ``` ```java @GET(value = "/users/json", responseType = ResponseType.JSON) public User printJSON(){ return new User("hellokaton", 18); } ``` -------------------------------- ### Parse Form Parameters to Model with Custom Name in Blade Source: https://github.com/lets-blade/blade/blob/v2.1.3/README.md Shows how to bind form parameters to a Java model using a custom name for the model in the request, specified by `@Form(name="u")`. This allows for nested form data. Includes a curl command to test the endpoint. ```java @POST("/users") public void saveUser(@Form(name="u") User user) { System.out.println("user => " + user); } ``` ```bash curl -X POST http://127.0.0.1:9000/users -F u[username]=jack -F u[age]=16 ``` -------------------------------- ### Handle File Upload with jQuery AJAX Source: https://github.com/lets-blade/blade/blob/v2.1.3/blade-core/src/test/resources/templates/upload.html This JavaScript snippet uses jQuery to attach a click event listener to an element with the ID 'upload'. When clicked, it initiates an AJAX POST request to '/upload'. It sends form data from '#uploadForm' without processing the data or setting a content type, which is typical for file uploads. Upon successful response, it logs the result and displays an alert indicating success or failure based on the server's response. ```javascript $('#upload').click(function () { $.ajax({ url: '/upload', type: 'POST', cache: false, data: new FormData($('#uploadForm')[0]), processData: false, contentType: false }).done(function (res) { console.log(res); if(res.success){ alert('上传成功.'); } else { alert(res.msg || '上传失败'); } }).fail(function (res) { }); }); ``` -------------------------------- ### Displaying User Variable in Blade Template Source: https://github.com/lets-blade/blade/blob/v2.1.3/blade-core/src/test/resources/templates/test.html This snippet demonstrates how to display a variable named 'user' within a Blade template. The '${}' syntax is used for variable interpolation, allowing dynamic content to be rendered into the HTML output. ```Blade user is ${user} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.