Thymeleaf Integration With Spring

Integrating thymeleaf with Spring framework
Note: This is intended for advanced programmers who already knows the spring,Maven, thymeleaf basics.

Thymeleaf will provide view templates for spring web applications like JSP’s.

1. Thymeleaf dependencies configuration
Add following dependencies in pom.xml

<dependency >
      <groupId> org.thymeleaf</groupId >
      <artifactId> thymeleaf</artifactId >
      <version> ${thymeleaf.version}</version >
      <scope> compile</scope >
      <groupId> org.thymeleaf</groupId >
      <artifactId> thymeleaf-spring3 </artifactId>
      <version> ${thymeleaf.version}</version >
      <scope> compile</scope >

2. Configure following belans spring applicationContext.xml file. The view resolver will handle all the view request.

 <bean id="templateResolver"
    <property name="prefix" value="/WEB-INF/templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <!-- Template cache is true by default. Set to false if you want -->
    <!-- templates to be automatically updated when modified.        -->
    <property name="cacheable" value="true" />

  <bean id="templateEngine"
    <property name="templateResolver" ref="templateResolver" />

  <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />

3. write the template pages to for displaying in web site.


Thymeleaf Templating Engine for Web Application Views

Thymeleaf is a templating Engine, which will processes views which are in the form of HTML5/XHTML etc. These view templates will be parsed, cached, cloned and processes for each request. As it cached the templates, it will reduce lot of I/O operation time while displaying pages.
Note: Thymeleaf template engine will construct in memory DOM objects, hence we should avoid larger page templates.

Some of the features of thymeleaf…

1. Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications.
2. Thymeleaf is a template engine framework, which will apply set of processors+data on a template and produce the web pages.
3. Processors + set of artifacts are called dialect in thymeleaf.
4. http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html
5. The minimum goal of the thymeleaf is to provide an elegant and well – formed way of creating templates.
6. Its architecture allows fast processing of templates, relying on intelligent caching of parsed files which will reduce I/O operations.
7. Thymeleaf processing engine constructs the DOM objects from view templates.
8. These DOM objects will be cached in memory. Each time this DOM object will be cloned and processed to display the view. This will reduce IO operation time.

9. Anything that can be modeled as a DOM tree could effectively be processed as a template in thymeleaf.
10. Thymeleaf is an extremely extensible template engine (in fact it should be better called a template engine framework) that
allows you to completely define the DOM nodes that will be processed in your templates and also how they will be processed.
An object that applies some logic to a DOM node is called a processor, and a set of these processors –plus some extra
artifacts– is called a dialect.
11. Natural Template is possible in thymeleaf. where designer and developer will use same template without modifying.
12. all the request, session and application level variables will be accessed in OGNL style.
13. Supports internationalization of the application, where locale specific messages will be externalized to property files.

As of now Thymeleaf supports following formats,
Valid XML
Legacy HTML5

Highlevel view of thymeleaf processing
Construct in memory DOM structure from templates –> traverse each template Node –> apply processors on each Node (Even attribute/business Data to display) –> and produce final page.

How thymeleaf works in a simple web application

1. A servlet filter to direct all requests to the thymeleaf
ex: MyAppFilter
2. MyAppFilter will create thymeleaf resolver and template engine.

* thymeleaf resolver

ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();

* create template engine

templateEngine = new TemplateEngine();

* Even a messages resolver can be attached to thymeleaf to solve internationalization messages apart from out-of-the-box message resolver.
* And MyAppFilter will delegate each request to appropriate conroller

Controller controller = Application.resolveControllerForRequest(request);
            if (controller == null) {
                return false;

             * Obtain the TemplateEngine instance.
            TemplateEngine templateEngine = Application.getTemplateEngine();

             * Write the response headers
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

             * Execute the controller and process view template,
             * writing the results to the response writer. 
                    request, response, this.servletContext, templateEngine);

Controller for path =”/” –> HomeController.java

 public class HomeController implements IGTVGController {

    public HomeController() {
    public void process(
            final HttpServletRequest request, final HttpServletResponse response,
            final ServletContext servletContext, final TemplateEngine templateEngine) 
            throws Exception {
        WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
        ctx.setVariable("today", Calendar.getInstance());
        templateEngine.process("home", ctx, response.getWriter());


Note: Detailed code can be found at http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html


jmx jstatd remote debug configuration in JVM

To start the jstatd daemon, follow these steps:

Note : Close all the java based applications before starting jstatd.

Create a permissions policy (for example, jstatd.all.policy) that contains the following contents:

grant codebase "file:${java.home}/../lib/tools.jar" { permission java.security.AllPermission; };

Start the jstatd daemon, and specify the policy file and the port that you want to use. The daemon is found in the Java Development Kit (JDK) bin directory. Note: The location for that directory depends on the operating environment.
For UNIX operating environments, specify the following:

JAVA_HOME/bin/jstatd -p 1199 -J-Djava.security.policy=jstatd.all.

For Windows operating environments, specify the following:

JAVA_HOME\bin\jstatd -p 1199 -J-Djava.security.policy=jstatd.all.policy

Remote Monitoring via JMX

To monitor a Java virtual machine (JVM) via JMX, follow these steps:

Add the following arguments to the target JVM:

-Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=4090

Restart the JVM so that the new arguments take effect.
Verify that the JMX port (4090 in this example) is open and listening. Once you verify that the port is open and listening, you can connect to the port for remote monitoring.


Datasource Configuration In Jboss 7

Follow the below steps to add datasource in jboss 7

1. edit standalone.xml to add datasource in subsystem

Note: standalone.xml location jboss-as-7.1.1.Final/standalone/configuration

 <datasource jndi-name="java:/jdbc/mydatasource" pool-name="mydatasource" enabled="true" use-java-context="true">

2. Add the MySql Driver in the same place

 <driver name="mysql" module="com.mysql.jdbc">

3. Create following folder structure in jboss module directory.


4. create module.xml file with following entry

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="com.mysql.jdbc">
        <resource-root path="mysql-connector-java-5.1.21.jar"/>
        <!-- Insert resources here -->
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>

5. add mysql connector jars. finally main folder should contain below files



Jboss Deployment Time Out Increase

Some of the web applications will take longer time to deploy than expected. By default JBoss has only 60 seconds deployment time out.

To Increase the JBoss time, set the following configuration value in standalone.xml in jboss 7. Deployment time out will be in milliseconds.

<subsystem xmlns=”urn:jboss:domain:deployment-scanner:1.1″>
<deployment-scanner path=”deployments” relative-to=”jboss.server.base.dir” scan-interval=”5000″ deployment-timeout=”3000″/>