Displaying NixMash Spring Posts with Spring MVC and Velocity

This is the fourth and final post covering the initial release of NixMash Spring Posts where we’ll describe how we’re displaying the Posts Stream with Spring MVC, Velocity, and a dash of JavaScript. Now we can put the wraps on NixMash Spring v0.3.2 and get to work on fun stuff for v0.3.3.

For those not following along at home, we first introduced NixMash Spring Posts, then focused on the role of Jsoup in generating the Page Preview form, and most recently, how to create a Bootstrap Carousel with Spring MVC and Thymeleaf.

You can view NixMash Spring Posts on the demo site, but here’s a screenshot to save time. What makes the display of the posts interesting is that they can be one of several display types. Examples of display types are Links with Text, Links with a Thumbnail Image and Featured Links with a Large Image.

You would normally think to use JSON for something like this, but with the dynamic nature of the display we pass formatted HTML to the client. Below are the two Controller methods used to generate the stream. Notice we’re producing “text/html” rather than “application/json”. We’ll take a look at both the postService.getPosts() and templateService.createPostHtml() methods next.

Here is our postService.getPosts() method which is so awesome because it shows the efficiency of Spring JPA Paging.

Generating the HTML Display

We call on the services of Apache Velocity to display the individual posts based on their DisplayType property. Here’s our template service where we merge the specific Velocity Template with our Post to generate the HTML.

Here’s a sample Velocity Template.

Client Side

Here’s the JavaScript to complete the process, loading page “0” on page load then sending the incremented pageIndex value to the Spring MVC Controller we saw at the top. Most of the JavaScript is for formatting purposes, so there’s very little required to generate the Post Stream itself.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.