• Home
KodEduKodEdu
  • Home

Integration of Spring MVC and Mustache

  • Posted by Rahman Usta
  • Categories Genel, Uncategorized, Yazılar
  • Date 2 August 2013

Spring MVC, as it is known, is a Web infrastructure system in the Spring ecosystem.

Spring MVC uses InternalResourceViewResolver class as default resolver, and this resolver class works with JSP view objects. But in Spring MVC, there are also resolvers that can resolve the different view technology. Here you will be introduced with the MustacheViewResolver class which resolves the Mustache template architecture.

MustacheResolver does not exist as default in Spring MVC libraries but every developer who wishes to do that is free to develop his own view resolver.

I want to leave the Advantage / Disadvantage comparison to you, precious developer, and I would like to explain the issue step by step.

Step 1: Prototyping Spring MVC Maven archetype.

The following Maven command set is run on the command-line and then the prototype number, seen on console is selected.

> mvn archetype:generate

spring-mvc-archetype

The above Maven project prototype contains configuration of XML independent Spring MVC. Of course if it is desired, this project can be used easily in the form of XML-structured.

Step 2: Adding MustacheViewResolver dependency to pom.xml. This dependency is being developed by Sean Scanlon. This dependency uses JMustache library in the background.


<dependency>
<groupId>com.github.sps.mustache</groupId>
<artifactId>mustache-spring-view</artifactId>
<version>1.1.1</version>
</dependency>

Step 3: Adding MustacheViewResolver into MvcConfiguration constructor class.

This class is used instead of InternalResourceViewResolver which is used as default in Spring MVC.

@Bean
public ViewResolver getViewResolver(ResourceLoader resourceLoader) {
    MustacheViewResolver mustacheViewResolver = new MustacheViewResolver();
    mustacheViewResolver.setPrefix("/WEB-INF/views/");
    mustacheViewResolver.setSuffix(".html");
    mustacheViewResolver.setCache(false);
    mustacheViewResolver.setContentType("text/html;charset=utf-8");

    MustacheTemplateLoader mustacheTemplateLoader = new MustacheTemplateLoader();
    mustacheTemplateLoader.setResourceLoader(resourceLoader);

    mustacheViewResolver.setTemplateLoader(mustacheTemplateLoader);
    return mustacheViewResolver;
}

Step 4: Creating Book-Model object.

This model class is read by Spring MVC and then placed into Mustache placeholders according to data field names.

public class Book {

    private String name;
    private Double price;
    private String author;
    private Boolean visibility;

    public Book(String name, Double price, String author, Boolean visibility) {
        this.name = name;
        this.price = price;
        this.author = author;
        this.visibility = visibility;
    }

    public Book() {
    }

    public Boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(Boolean visibility) {
        this.visibility = visibility;
    }

    public String getName() {
        return name;
    }

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

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

Step 5: Assigning the List Model data to the ROOT ( / ) resource and then assigning this model data to the “home” page in HomeController class.

Spring MVC defragments the Model and View components in the defined ModelAndView object and then html page which placeholders’ were filled is returned to the user.

@Controller
public class HomeController {

    @RequestMapping(value = "/")
    public ModelAndView test() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("home");

        List<Book> bookList=
                Arrays.asList(
                        new Book("Java ve Yazılım Tasarımı", 35d, "Altuğ B. Altıntaş", true),
                        new Book("Java Mimarisiyle Kurumsal Çözümler", 23d, "Rahman Usta", true),
                        new Book("Veri Yapıları ve Algoritmalar", 40d, "Rifat Çölkesen", false),
                        new Book("Veri Yapıları ve Algoritmalar", 40d, "Rifat Çölkesen", false),
                        new Book("Veri Yapıları ve Algoritmalar", 40d, "Rifat Çölkesen", true),
                        new Book("Mobil Pazarlama - SoLoMo", 15d, "Kahraman-Pelin Arslan", false),
                        new Book("Mobil Pazarlama - SoLoMo", 15d, "Kahraman-Pelin Arslan", true));

        modelAndView.addObject("bookList", bookList);

        return modelAndView;
    }
}

Step 6: Creating the page “home(.html)” view.

Neither an external XML element and a Java code, nor a JSP component that is contrary to HTML standard can be seen when you look home.html page. So, absolute Mustache placeholders that exist in absolute HTML and text format are the striking elements of this page.


<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset=UTF-8>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<table class="table" border="1" bordercolor="grey" style="margin: 30px auto 0 auto;width: 500px;">
    <thead>
    <tr>
        <th>
            <lablel>Book name</lablel>
        </th>
        <th>
            <lablel>Price</lablel>
        </th>
        <th>
            <lablel>Author</lablel>
        </th>
    </tr>
    </thead>
    <tbody>
    {{#bookList}}
    {{#visibility}}
    <tr>
        <td>
            {{name}}
        </td>
        <td>
            {{price}}
        </td>
        <td>
            {{author}}
        </td>
    </tr>
    {{/visibility}}
    {{/bookList}}
    </tbody>
</table>
</body>
</html>

Step 7:Running the Project.

You can access to the application directory by”cd” (change directory) command and then “mvn jetty:run” command set.

Application Access Address: http://localhost:8080/

You can obtain the source code from here.

Output:

mvc-mustache

Hope to see you again, good bye.

Tag:backend, mustache, spring mvc

  • Share:
author avatar
Rahman Usta
Java* Trainer and Author. JCP Expert, Istanbul JUG and Adopt a JSR member. Duke's Choice Award 2015 winner. Ex-Voxxed Istanbul Organizer. Creator of AsciidocFX.

Previous post

Java API for JSON Processing – Reading and Writing JSON objects
2 August 2013

Next post

Combine JaxRS 2.0 Rest Client, Java FX 2, Spring MVC and Hibernate
15 August 2013

You may also like

collector
Distributed Map-Reduce Model using Java 8 and Java EE 7 WebSocket
16 November, 2014
server-sent-events-jax-rs-2
HTML 5 Server Sent Events on Glassfish 4
27 November, 2013
concurrency
Java EE 7 – Concurrency Utilities
23 October, 2013

Leave A Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • TürkçeTürkçe

Gözde yazılar

Jax-RS 2 and LongPolling based Chat Application
25Jun2013
Java API for JSON Processing – Reading and Writing JSON objects
23Jul2013
Integration of Spring MVC and Mustache
02Aug2013
Combine JaxRS 2.0 Rest Client, Java FX 2, Spring MVC and Hibernate
15Aug2013

Recent Posts

  • First look at HTTP/2 Server Push in Java Servlet 4.0 Specification 26 April 2017
  • Distributed Map-Reduce Model using Java 8 and Java EE 7 WebSocket 16 November 2014
  • HTML 5 Server Sent Events on Glassfish 4 27 November 2013
  • Java EE 7 – Concurrency Utilities 23 October 2013
  • Combine JaxRS 2.0 Rest Client, Java FX 2, Spring MVC and Hibernate 15 August 2013

Get Java Software

React.js Eğitimi Başlıyor
11-22 Eylül, 2017
Eğitmen
Rahman Usta
İletişim

merhaba@kodedu.com

  • Hakkında
  • Gizlilik Politikası
  • İletişim
  • Referanslar
Kodedu Bilişim Danışmanlık
Cemil Meriç mah. Çelebi sok.
No:16/3 Ümraniye/İSTANBUL
Tel: 0850 885 38 65
Alemdağ V.D.: 8960484815

KODEDU © Tüm hakları saklıdır.