Wednesday, 14 January 2015

Spark java : Response parameter


As you observe implementation of get method, it takes request and response objects as parameters.

get("/hello/*/welcome/*", (request, response) -> {     
        return "Hello";
});


Response object provides number of APIs to set response body, cookie values etc.

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(401);          // set status code to 401
response.type("text/xml");     // set content type to text/xml


For cookie support
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");

import static spark.Spark.*;

public class HelloSpark {
  public static void main(String[] args) {  
    get("/hello", (request, response) -> {
       response.redirect("https://self-learning-java-tutorial.blogspot.com");
       return "Hi";
    });
  }

}



Hit above URL, it redirect request to my blog home page.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment