Wednesday, 14 January 2015

spark java and freemarker integration


hello.ftl
<html>
<head>
  <title>Hello File Marker</title>
</head>
<body>
  <ul>
    <#list employees as employee>
      <li>${employee.firstName}  ${employee.lastName}</li>
    </#list>
  </ul>

</body>
</html>

package com.freemarker;

public class Employee {

 private String firstName;
 private String lastName;
 
 Employee(String firstName, String lastName){
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}

package com.freemarker;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import static spark.Spark.*;
import spark.Request;
import spark.Response;
import spark.Route;

public class MainTest {

 public static void main(String[] args) throws Exception {
  get("/welcome", new Route(){
   @Override
   public Object handle(Request request, Response response)  throws Exception{
    /* The main entry point into the FreeMarker API;
     *  encapsulates the configuration settings of FreeMarker, 
     *  also serves as a central template-loading and caching service. */
    Configuration cfg = new Configuration();
    
    StringWriter writer = new StringWriter();
    
    Map<String, List<Employee>> input = new HashMap<String, List<Employee>> ();
    
    List<Employee> employees = new ArrayList<Employee>();
    employees.add(new Employee("Hari Krishna", "Gurram"));
    employees.add(new Employee("Keerthi", "S"));
    employees.add(new Employee("Upasana", "Ads"));
    employees.add(new Employee("Ankit", "Suyal"));
    input.put("employees", employees);

    /* Retrieves the template with the given name */
    Template template = cfg.getTemplate("src\\hello.ftl");
    template.process(input, writer);
    
    return writer;
   }
  });

 }
}


Directory structure looks like below.


Run “MainTest.java”, you will get output like below in console.

[Thread-0] INFO spark.webserver.SparkServer - == Spark has ignited ...
[Thread-0] INFO spark.webserver.SparkServer - >> Listening on 0.0.0.0:4567
[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.0.2.v20130417
[Thread-0] INFO org.eclipse.jetty.server.ServerConnector - Started ServerConnector@15e3ab0{HTTP/1.1}{0.0.0.0:4567}

Hit below link
 






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment