Sunday 19 November 2017

Thymeleaf integration with Spring


Hi in this post I am Integrating Thymeleaf3 with Spring 4.

My System configuration:

Windows 10
Spring Tool Suite
Platform: Eclipse Neon.1 (4.6.1)
java version "1.8.0_131"

To create Thymeleaf Integration with Spring we have to follow these stesp:



1)Create a maven project




2)Select Maven project





3) Select option create a simple project(skip archetype selection)




4) Give group id and artifact id and some extra details and then finish.




After this step our maven project will be created but showing some error.
One error is inside pom.xml




If u hold your mouse on cross sign/error place then u can see this



and the message is:
                             web.xml is missing and <failOnMissingWebXml> is set to true

To avoid this problem we have to add some code in pom.xml (I will show u shortly).

Second thing is not an error but it is showing older version of Deployment Descriptor. We have to change this too.

Now my pom.xml

<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>org.asif.thymeleaf3</groupId>
  <artifactId>ThymeleafIntegration</artifactId>
  <version>0.0.1</version>
  <packaging>war</packaging>
  <name>Thymeleaf3 Integration with Spring4</name>
  <description>In this project I am Integrating Thyemealf3 with Spring4</description>
 
  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.version>1.8</jdk.version>
        <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
        <spring.version>4.2.2.RELEASE</spring.version>
        <maven.compiler.version>3.1</maven.compiler.version>
        <maven.war.version>2.6</maven.war.version>
    </properties>

   <!-- To avoid compiler and jre version -->
   <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
            <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>${maven.compiler.version}</version>
          <configuration>
              <source>${jdk.version}</source>
              <target>${jdk.version}</target>
          </configuration>
      </plugin>
      <!-- removing web.xml file error problem -->
      <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-war-plugin</artifactId>
             <version>${maven.war.version}</version>
             <configuration>
                 <failOnMissingWebXml>false</failOnMissingWebXml>
             </configuration>
         </plugin>
        </plugins>
    </build>

<dependencies>
        <!-- Provided dependencies -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- Compile dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>${thymeleaf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>${thymeleaf.version}</version>
        </dependency>
    </dependencies>
   
</project>


After saving pom.xml you have to upate maven project.
Even after this if you observe deployment descriptor still it is showing old version like this



To change it to latest version we have to close project and then open again.

Now once I closed project and open again then you can see change





You can check that now Deployment descriptor becomes 3.1.

Simply maven update your project.
Now our project is created and having no error.

We will see our coding part now.
In this project for all configurations we are using Java class only, no xml file.

First we are creating ThymeleafConfig class in which we will do configuration of our thymeleaf.
Here is our class

package org.asif.thymeleaf3.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
@EnableWebMvc
@ComponentScan("org.asif.thymeleaf3")
public class ThymeleafConfig  extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private static final String UTF8 = "UTF-8";

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding(UTF8);
        return resolver;
    }

    private TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

}

*NOTE: If you change your package name then please don't forget to change @ComponentScan("Here please give your package name")

Even you can see your project in tomcat manager but if you try to access your project it gives you error that path not found.
Please take care of this.

 resolver.setPrefix("/WEB-INF/views/");
This is the place where I have to keep my html pages.

 resolver.setSuffix(".html");
we have to return only name of html page n complete path and extension will be add from here automatically.


Spring web Initializer class 

package org.asif.thymeleaf3.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class SpringWebInitializer implements WebApplicationInitializer {

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(ThymeleafConfig.class);
        context.setServletContext(servletContext);
        // Spring MVC front controller
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }

}

So our integration is ok now we have to write our controller class.

package org.asif.thymeleaf3.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

@RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView myModelMethod(Model model){
    ModelAndView mav = new ModelAndView("home");
    mav.addObject("myName", "Md Asif Aftab");
    mav.addObject("myEmail", "asifaftab87@gmail.com");
    return mav;
    }

}


This is very simple controller class where I am returning two attribute to html page which I can display in my html page using Thymeleaf tag.

ModelAndView mav = new ModelAndView("home");
Here home is name of my html file -> home.html 

Inside 

     src->main->webapp

we will create folder WEB-INF, so final path 
      
     src -> main -> webapp -> WEB-INF

We have to create one more folder views 

     src -> main -> webapp -> WEB-INF -> views

This path we given in our ThymeleafConfig.templateResolver() - method so we have to follow the same to place our html page.

You can modify this but whatever path you are going to give same path you have to follow to create your html files.

Location of home.html 
           src/main/webapp/WEB-INF/views/home.html


home.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Name: <span th:text="${myName}" />
<br>
Email: <span th:text="${myEmail}" />
</body>
</html>


Done.
Thanks





No comments:

Post a Comment