Dropwizard Tutorial : HTML Page Using Freemarker

Prerequisite

Before you start this, Its good to follow the following articles.

Running Rest API using Dropwizard

Reading From Database Using Dropwizard 

Writing To Database Using Dropwizard

I will assume that your dropwizard project is running.

Dependency

Add dependency of dropwizard-freemarker-views in your pom.xml

Your pom.xml should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordpress.nullpointerexception1</groupId>
<artifactId>myRestProject</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<dropwizard.version>1.3.5</dropwizard.version>
</properties>
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-hibernate</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<!– https://mvnrepository.com/artifact/io.dropwizard/dropwizard-views-freemarker –>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-views-freemarker</artifactId>
<version>${dropwizard.version}</version>
</dependency>
</dependencies>
</project>

view raw
pom.xml
hosted with ❤ by GitHub

Freemarker Template Language

Apache FreeMarker™ is a template engine. It’s a Java library to generate text output based on templates and data. Templates are written in the FreeMarker Template Language (FTL), which is a simple and specialized language. Template allows us to focus on how to present the data. Outside the template you are focusing on what data to present.

Further reading here.

Template Configuration Context

import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
import java.io.File;
import java.io.IOException;
/**
* Created by harshvardhan on 19/07/18.
*/
public class TemplateConfigurationContext {
private static Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
public static Configuration getConfiguration() {
try {
configuration.setDirectoryForTemplateLoading(new File("templates"));
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setLogTemplateExceptions(false);
configuration.setWrapUncheckedExceptions(true);
} catch (IOException e) {
e.printStackTrace();
}
return configuration;
}
}

Hello World FTL

Add a directory at src level and add helloWorld.ftl

<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
</body>
</html>

view raw
helloWorld.ftl
hosted with ❤ by GitHub

Hello World GET API

Add a get API to render HelloWorld FTL in browser

import com.codahale.metrics.annotation.Timed;
import freemarker.template.Template;
import io.dropwizard.hibernate.UnitOfWork;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by harshvardhan on 12/07/18.
*/
@Path("/resource")
public class MyResource {
private InfoDao infoDao;
public MyResource(InfoDao infoDao) {
this.infoDao = infoDao;
}
@GET
@Timed
@Produces({MediaType.APPLICATION_JSON})
@Path("/getName")
public String getName() {
return "Harsh";
}
@POST
@Timed
@Produces({MediaType.APPLICATION_JSON})
@Path("/postName")
public String postName(String name) {
System.out.println("Name given by : "+name);
return "Ok";
}
@GET
@Timed
@Produces({MediaType.APPLICATION_JSON})
@UnitOfWork
@Path("/findAllEmp")
public List<Info> findAllEmp() {
return infoDao.findAll();
}
@POST
@Timed
@UnitOfWork
@Produces({MediaType.APPLICATION_JSON})
@Path("/saveEmp")
public String saveEmp(Info info) {
return infoDao.create(info);
}
@GET
@Timed
@Produces({MediaType.TEXT_HTML})
@Path("/helloWorld")
public Response getHelloWorld() {
try {
Template temp = TemplateConfigurationContext.getConfiguration().getTemplate("helloWorld.ftl");
Map root = new HashMap();
root.put("user", "Harsh");
Writer writer = new StringWriter();
temp.process(root, writer);
return Response.status(Response.Status.ACCEPTED).entity((writer.toString())).build();
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(("Oops! Try again later")).build();
}
}

view raw
MyResource.java
hosted with ❤ by GitHub

Run The Project

Open the API in the browser to see your helloWorld rendered.

Screen Shot 2018-07-19 at 3.30.13 PM.png


Further Reading:

https://freemarker.apache.org/

https://www.dropwizard.io/0.7.1/docs/manual/views.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: