JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

FreeMarker Template + Servlet Integration Example

November 28, 2013 by Krishna Srinivasan Leave a Comment

This is my second tutorial about FreeMarker template engine. In my previous tutorial I have explained about how to create stand alone freemarker template. This tutorial explains how to integrate freemarker template to a servlet.

1. Setup FreeMarker Environemnt

It is very simple to setup the freemarker environment by downloading the JAR distribution from its official web page. You can follow my previous tutorial to set up the freemarker project. Only difference is you have to create this project as web project and add the libraries to the lib folder. Once you have created the project, the finel project structure would look like this:

freemarker-project-structure

2. Create a Bean

Create a bean for storing the values.

[code lang=”java”]
package javabeat.net.freemarker;
public class Employee {
private String id;
private String name;
private String city;

public Employee() {
}

public Employee(String id, String name, String city) {
this.id = id;
this.name = name;
this.city = city;

}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

}
[/code]

3. Create a Servlet

[code lang=”java”]
package javabeat.net.freemarker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private List<Employee> employeesList = new ArrayList<Employee>();
{
employeesList.add(new Employee("001", "Rahul", "Bangalore"));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("employees", employeesList);
request.getRequestDispatcher("/index.ftl").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String city = request.getParameter("city");
if(null != name && !name.isEmpty() ) {
employeesList.add(new Employee(id,name, city));
}
doGet(request, response);
}
}
[/code]

4. Create FTL Template

FreeMarket template has .ftl extension. It is plain HTML page with the freemarker syntax embeded with the HTML elements. When this page is executed, the values passed from servlets are dynamically inserted to the templates.

[code lang=”xml”]
<html>
<head><title>FreeMarker Hello World</title>

<body>
<form name="user" action="hello" method="post">
Id: <input type="text" name="id" /> <br/>
Name: <input type="text" name="name" /> <br/>
City: <input type="text" name="city" /> <br/>
<input type="submit" value="Save" />
</form>

<table class="datatable">
<tr>
<th>ID</th> <th>Name</th> <th>City</th>
</tr>
<#list employees as employee>
<tr>
<td>${employee.id}</td> <td>${employee.name}</td><td>${employee.city}</td>
</tr>
</#list>
</table>
</body>
</html>
[/code]

5. Create Deployment Descriptor For FreeMarker Servlet

We have to configure FreemarkerServlet in the deployment descriptor to detuct the freemarker request. Look at the below entries in the web.xml.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>FreeMarker Servlet Example</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<!– FreemarkerServlet settings: –>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html; charset=UTF-8</param-value>
<!– Forces UTF-8 output encoding! –>
</init-param>
<!– FreeMarker settings: –>
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value>
<!– 0 is for development only! Use higher value otherwise. –>
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>ISO-8859-1</param-value>
<!– The encoding of the template files. –>
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##########</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>FreeMarketServletExample</servlet-name>
<servlet-class>javabeat.net.freemarker.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FreeMarketServletExample</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
[/code]

6. Run The Application

If you run the above example, you would see the below screen as output.

freemarker-servlet

Filed Under: FreeMarker Tagged With: template engine

FreeMarker Template Hello World Example

November 27, 2013 by Krishna Srinivasan Leave a Comment

1. Introduction to FreeMarker

FreeMarker is a Java based template engine which can be used as stand-alone or servlet bases Java programs. You write a FreeMarker template in a plain text file with the place holders like ${id}. This file is saved with .ftl extension. Not only the simple text, we can also use the conditions, loops, switch statements, etc. in the templates that can be dynamically supplied by the Java program. The Java program passes the actual value for the place holders defined in the FreeMarker template files.

The output of the template is written to the Writer object which you have provide and then this object can be passed to HTTP, File, etc. for printing the result. Programmer can configure the location of the templates and where the files has to be created with the results. This tutorial explains on how to create a simple FreeMarker template implementation in the stand alone mode.

2. How to Install FreeMarker?

Installing FreeMarker template engine is as simple as adding a JSR files to your project. You can download the latest version of the lobraries from freemarker website. At this time of writing this article, the latest version available for download is 2.3.20. If you are using the Maven build for your project, the add the following entry in your POM.xml.

[code lang=”xml”]
<!–
Attention: Be sure nothing pulls in an old dependency with groupId
"freemarker" (without the "org."), because then you will end up with
two freemarker.jar-s and unpredictable behavior!
–>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
[/code]

freemarker-project-structure

3. FreeMarker Java Template Processing

This is the important part of supplying the template place holders to the actual templates.

[code lang=”java”]package javabeat.net.freemarker;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
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 freemarker.template.TemplateException;

public class FreeMarkerHelloWorld {

public static void main(String[] args) {

// Configurae Freemarker
Configuration cfg = new Configuration();
try {
// Load the template
Template template = cfg.getTemplate("src/template.ftl");

Map<String, Object> data = new HashMap<String, Object>();
data.put("message", "Hello World!");

// Language list
List<String> language = new ArrayList<String>();
language.add("Java");
language.add("C++");
language.add("Ceylon");
language.add("Cobol");

data.put("languages", language);

Writer out = new OutputStreamWriter(System.out);
template.process(data, out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}[/code]

4. Create FreeMarker Template

[code]FreeMarker Hello World Example : ${message}

<#list languages as language>
${language_index + 1}. ${language}
</#list>[/code]

5. Run Sample Application

If you run the above program, you would get the following output.

[code]</span>
<pre>FreeMarker Hello World Example : Hello World!

1. Java
2. C++
3. Ceylon
4. Cobol
[/code]

Filed Under: FreeMarker Tagged With: FreeMarker, template engine

How To Use Switch Statement (th:switch) In Thymeleaf Template?

November 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to use the switch statements inside Thymeleaf template. Thymeleaf provides th:switch attribute for using switch functionality. This feature is extension of my previous example on iteration in thymeleaf template.

1. Set Up Thymeleaf Application

To demonstrate this example, I am using our previous hello world example.Use the same example and replace our code snippet as below. You can use the set up details as mentioned in the hello world example.

2. Create Template with th:switch

If you look at the below example, the tamplate has the th:switch which is replaced with the dynamic values by the template engine.

employees.xml

[code lang=”xml”]
&amp;lt;!DOCTYPE html SYSTEM &amp;quot;http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd&amp;quot;&amp;gt;
&amp;lt;html xmlns=&amp;quot;http://www.w3.org/1999/xhtml&amp;quot;
xmlns:th=&amp;quot;http://www.thymeleaf.org&amp;quot;&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;title&amp;gt;Iteration in Thymeleaf Template Engine!!&amp;lt;/title&amp;gt;
&amp;lt;meta http-equiv=&amp;quot;Content-Type&amp;quot; content=&amp;quot;text/html; charset=UTF-8&amp;quot; /&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;h1&amp;gt;Employees&amp;lt;/h1&amp;gt;
&amp;lt;table&amp;gt;
&amp;lt;tr&amp;gt;
&amp;lt;th&amp;gt;SNO&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;ID&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;NAME&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;CITY&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;COUNTRY&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;ROLE&amp;lt;/th&amp;gt;
&amp;lt;/tr&amp;gt;
&amp;lt;tr th:each=&amp;quot;emp,iterationStatus : ${employees}&amp;quot;&amp;gt;
&amp;lt;td th:text=&amp;quot;${iterationStatus.count}&amp;quot;&amp;gt;1&amp;lt;/td&amp;gt;
&amp;lt;td th:text=&amp;quot;${emp.id}&amp;quot;&amp;gt;001&amp;lt;/td&amp;gt;
&amp;lt;td th:text=&amp;quot;${emp.name}&amp;quot;&amp;gt;Name&amp;lt;/td&amp;gt;
&amp;lt;td th:text=&amp;quot;${emp.city}&amp;quot;&amp;gt;City&amp;lt;/td&amp;gt;
&amp;lt;td th:text=&amp;quot;${emp.country}&amp;quot;&amp;gt;Country&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;
&amp;lt;div th:switch=&amp;quot;${emp.role}&amp;quot;&amp;gt;
&amp;lt;p th:case=&amp;quot;’Admin’&amp;quot;&amp;gt;User is an Administrator&amp;lt;/p&amp;gt;
&amp;lt;p th:case=&amp;quot;’Manager’&amp;quot;&amp;gt;User is a Manager&amp;lt;/p&amp;gt;
&amp;lt;p th:case=&amp;quot;’Engineer’&amp;quot;&amp;gt;User is an Engineer&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/td&amp;gt;
&amp;lt;/tr&amp;gt;
&amp;lt;/table&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

[/code]

3. Create Bean Employee

Employee.java

[code lang=”java”]
package javabeat.net.thymeleaf;

public class Employee {
private String id;
private String name;
private String role;
private String city;
private String country;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

[/code]

4. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafSwitchExample.java

[code lang=”java”]
package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafSwitchExample extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
// XHTML is the default mode, but we will set it anyway for better understanding of code
templateResolver.setTemplateMode(&amp;quot;XHTML&amp;quot;);
templateResolver.setPrefix(&amp;quot;/WEB-INF/&amp;quot;);
templateResolver.setSuffix(&amp;quot;.html&amp;quot;);
templateResolver.setCacheTTLMs(3600000L);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
WebContext ctx = new WebContext(req, resp, getServletConfig().getServletContext(), req.getLocale());
ArrayList&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;();
Employee employee = new Employee();
employee.setId(&amp;quot;001&amp;quot;);
employee.setName(&amp;quot;Rahul&amp;quot;);
employee.setRole(&amp;quot;Manager&amp;quot;);
employee.setCity(&amp;quot;Bangalore&amp;quot;);
employee.setCountry(&amp;quot;India&amp;quot;);
employees.add(employee);
employee = new Employee();
employee.setId(&amp;quot;002&amp;quot;);
employee.setName(&amp;quot;Deepan&amp;quot;);
employee.setRole(&amp;quot;Admin&amp;quot;);
employee.setCity(&amp;quot;Namakkal&amp;quot;);
employee.setCountry(&amp;quot;India&amp;quot;);
employees.add(employee);
employee = new Employee();
employee.setId(&amp;quot;003&amp;quot;);
employee.setName(&amp;quot;Ashwanth&amp;quot;);
employee.setRole(&amp;quot;Engineer&amp;quot;);
employee.setCity(&amp;quot;Bangalore&amp;quot;);
employee.setCountry(&amp;quot;India&amp;quot;);
employees.add(employee);

// This will be prefixed with /WEB-INF/ and suffixed with .html
ctx.setVariable(&amp;quot;employees&amp;quot;, employees);
templateEngine.process(&amp;quot;employees&amp;quot;, ctx, resp.getWriter());

resp.setContentType(&amp;quot;text/html;charset=UTF-8&amp;quot;);
resp.setHeader(&amp;quot;Pragma&amp;quot;, &amp;quot;no-cache&amp;quot;);
resp.setHeader(&amp;quot;Cache-Control&amp;quot;, &amp;quot;no-cache&amp;quot;);
resp.setDateHeader(&amp;quot;Expires&amp;quot;, 1000);
}
}
[/code]

5. Run The Thymeleaf Application

If you execute the above code, you would see the below output as below.

switch-thymeleaf

Filed Under: Web Frameworks Tagged With: switch, template engine, Thymeleaf

How To Use th:each For Iteration In Thymeleaf Template?

November 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to iterate the list of values from an object. For Iteration In Thymeleaf Template, it provides th:each attribue for using inside a table element to iterate over the list of objects and display the list. This feature also provides iterationStatus context to retrieve the extra details about size of the list, row count, whether that is the first or last element, etc. This feature is very useful for creating the table list with the dynamic values.

1. Set Up Thymeleaf Application

To demonstrate this example, I am using our previous hello world example.Use the same example and replace our code snippet as below. You can use the set up details as mentioned in the hello world example.

2. Create Template with th:each

If you look at the below example, the tamplate has the th:each which is replaced with the dynamic values by the template engine.

employees.xml

[code lang=”xml”]
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Iteration in Thymeleaf Template Engine!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Employees</h1>
<table>
<tr>
<th>SNO</th>
<th>ID</th>
<th>NAME</th>
<th>CITY</th>
<th>COUNTRY</th>
</tr>
<tr th:each="emp,iterationStatus : ${employees}">
<td th:text="${iterationStatus.count}">1</td>
<td th:text="${emp.id}">001</td>
<td th:text="${emp.name}">Name</td>
<td th:text="${emp.city}">City</td>
<td th:text="${emp.country}">Country</td>
</tr>
</table>
</body>
</html>

</body>
</html>

[/code]

3. Create Bean Employee

Employee.java

[code lang=”java”]
package javabeat.net.thymeleaf;

public class Employee {
private String id;
private String name;
private String city;
private String country;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
[/code]

4. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafIterationExample.java

[code lang=”java”]
package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafIterationExample extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
// XHTML is the default mode, but we will set it anyway for better understanding of code
templateResolver.setTemplateMode("XHTML");
templateResolver.setPrefix("/WEB-INF/");
templateResolver.setSuffix(".html");
templateResolver.setCacheTTLMs(3600000L);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
WebContext ctx = new WebContext(req, resp, getServletConfig().getServletContext(), req.getLocale());
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee employee = new Employee();
employee.setId("001");
employee.setName("Rahul");
employee.setCity("Bangalore");
employee.setCountry("India");
employees.add(employee);
employee = new Employee();
employee.setId("002");
employee.setName("Deepan");
employee.setCity("Namakkal");
employee.setCountry("India");
employees.add(employee);
employee = new Employee();
employee.setId("003");
employee.setName("Ashwanth");
employee.setCity("Bangalore");
employee.setCountry("India");
employees.add(employee);

// This will be prefixed with /WEB-INF/ and suffixed with .html
ctx.setVariable("employees", employees);
templateEngine.process("employees", ctx, resp.getWriter());

resp.setContentType("text/html;charset=UTF-8");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 1000);
}
}

[/code]

5. Run The Thymeleaf Application

If you execute the above code, you would see the below output as below.

iteration-thymeleaf

Filed Under: Web Frameworks Tagged With: template engine, Thymeleaf

How To Set Attributes in Thymeleaf Template using th:attr?

November 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to set the attribute to the template at the time of processing. This feature is very useful for creating the templates. Thymeleaf provides very easy syntax for just adding the attributes dynamically from the properties files or context variables.

1. Set Up Thymeleaf Application

To demonstrate using the attribute values, I am using our previous hello world example.Use the same example and replace our code snippet below.

2. Create Template with th:attr

If you look at the below example, the tamplate has the th:attr which is replaced with the dynamic values by the template engine. Note that there are number of attributes and many other features are supported for setting the attribute values. Here I am explaining with a very simple example.

attributes.html

[code lang=”xml”]
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>How to set Attribute Values!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p><b>Use th:attr</b></p>
<fieldset>
<input type="text" name="email" th:attr="class=#{input.class}"/>
<input type="submit" value="Subscribe me!" th:attr="value=#{input.submit}"/>
</fieldset>
<a href="register.html" th:attr="href=@{/LoginRegister.html}">Register Here</a>
<p><b>Use Specific Attributes</b></p>
<fieldset>
<input type="text" name="email" th:class="#{input.class}"/>
<input type="submit" value="Subscribe me!" th:value="#{input.submit}"/>
</fieldset>
<a href="register.html" th:href="@{/LoginRegister.html}">Register Here</a>
<p><b>Append Using th:attrappend</b></p>
<fieldset>
<input type="text" name="email" class="input" th:attrappend="class=’ ‘ + #{input.class}"/>
<input type="submit" value="Subscribe me!" th:attr="value=#{input.submit}"/>
</fieldset>
<a href="register.html" th:attr="href=@{/LoginRegister.html}">Register Here</a>

</body>
</html>

[/code]

3. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafSetAttributeExample.java

[code lang=”java”]
package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafSetAttributeExample extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
// XHTML is the default mode, but we will set it anyway for better understanding of code
templateResolver.setTemplateMode("XHTML");
templateResolver.setPrefix("/WEB-INF/");
templateResolver.setSuffix(".html");
templateResolver.setCacheTTLMs(3600000L);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
WebContext ctx = new WebContext(req, resp, getServletConfig().getServletContext(), req.getLocale());

// This will be prefixed with /WEB-INF/ and suffixed with .html
templateEngine.process("attribute", ctx, resp.getWriter());
resp.setContentType("text/html;charset=UTF-8");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 1000);
}
}

[/code]

4. Create Property File

attributes_en.properties/strong>

[code]
input.class=inputstyle
input.submit=Form Submit
input.href=LoginRegister.html
[/code]

5. Run The Thymeleaf Application

If you execute the above code, you would see the below screen.

set-attribute-thymeleaf

If you look at the view source, the above template converted as below.

[code lang=”xml”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to set Attribute Values!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p><b>Use th:attr</b></p>
<fieldset>
<input type="text" name="email" class="inputstyle" />
<input type="submit" value="Form Submit" />
</fieldset>
<a href="/Thymeleaf/LoginRegister.html" shape="rect">Register Here</a>
<p><b>Use Specific Attributes</b></p>
<fieldset>
<input type="text" name="email" class="inputstyle" />
<input type="submit" value="Form Submit" />
</fieldset>
<a href="/Thymeleaf/LoginRegister.html" shape="rect">Register Here</a>
<p><b>Append Using th:attrappend</b></p>
<fieldset>
<input type="text" name="email" class="input inputstyle" />
<input type="submit" value="Form Submit" />
</fieldset>
<a href="/Thymeleaf/LoginRegister.html" shape="rect">Register Here</a>

</body>
</html>
[/code]

Filed Under: Web Frameworks Tagged With: template engine, Thymeleaf

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved