Over a million developers have joined DZone.

Integration of Spring MVC and Mustache

· Java Zone

Learn more about how the Java language, tools and frameworks have been the foundation of countless enterprise systems, brought to you in partnership with Salesforce.

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

Spring MVC uses the  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 to theMustacheViewResolver 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 ModelAndViewobject 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…

Discover how the Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services, brought to you in partnership with Salesforce.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}