Overview

A real ROCA using Bootstrap, jQuery, Thymeleaf, Spring HATEOAS and Spring MVC

9 Comments

There’s now a newer post about the same topic at Self-Contained Systems and ROCA: A complete example using Spring Boot, Thymeleaf and Bootstrap.

What is the best way to build a web application?

I know, tough question, and in the end, there cannot be one definitive answer, because otherwise there wouldn’t exist an armada of different architectures, frameworks and libraries. During the last years, Single Page Applications (SPA) based on JavaScript became more and more popular, and it seemed to me a little bit like it’s the only way to go for the future. It makes sense to have no server-side session, for scalability (Cloud! Commodity hardware!) on the one hand, and for the user experience on the other hand. And there’s no way of avoiding to accept JavaScript as a first class citizen anyway, so why not go JavaScript all the way?
On the other hand there’s one word in the term ‘Single Page App’ that makes me afraid: Single. Everything in one page? Really? I mean, it could be really a lot. Think of a medium or big sized web application with a lot of developers working on it. Initial loading times are a small problem compared to organizing the work: client software design, namespaces, merging, testing. Even if that’s just new to us old Java developers, we still have one application for everything. It’s not easy to exchange certain parts, it’s not easy to integrate with other applications, and it’s not easy to integrate other applications into it.

ROCA – Resource-oriented Client Architecture

So what do you do if you don’t want to build a single page application? While working at a customer I came across ROCA (Resource-oriented Client Architecture) which is a set of rules for a web application architecture. It’s a short list, so before I repeat them here, please read them there.

Ready?

So now you know the rules, but that doesn’t mean you can instantly imagine how such an application would look like. At least I couldn’t. I learned that there are two important aspects:

RESTful style

RESTful communication is stateless, so we have no session state. We have meaningful bookmarkable URIs for each resource and sub-resource, and a resource ideally represents an object from our domain, or a list of objects from our domain. I say ideally, because that’s not a must. In a lot of use cases, a resource made for a web frontend cannot be mapped 1-on-1 to domain objects, but if it does, our life gets easier. To interact with those resources we use the four HTTP methods GET, POST, PUT and DELETE. So if our domain happens to be a movie database, usage could be:

  • GET on /movies for displaying all movies
  • POST on /movies for adding a movie
  • GET on /movies/42 for displaying the movie with id 42
  • PUT on /movies/42 for updating the movie with id 42
  • DELETE on /movies/42 for deleting the movie with id 42

A GET returns HTML markup (possibly through a template engine), PUT and DELETE are tunneled through a POST, and POST, PUT and DELETE return a redirect URI to follow the POST/REDIRECT/GET pattern.

Progressive enhancement

By now we have a Web 1.0 application that works perfectly without JavaScript. In a progressive enhancement style we can add all those little things that make up a Web 2.0 application, like partial page rendering, inline-editing, search term suggestion, instant search, context menus, mouse over previews turning into a form on click, and so on. It means that we probably need more than one representation of a resource, for example one that contains the whole page with all menus, one that contains just the content, and maybe one that presents the data in a popup style.
Progressive enhancement is done in an unobtrusive way, so we don’t have JavaScript generating HTML, we just use JavaScript for rendering, history management, refreshing and validating based on server-generated data.

The movie database – an example application

You learn the most if you try it out – so I built a web application following the ROCA rules (with a little help and inspiration of some people that know more about it than I do). It’s a movie database, and you can find it here on Github. I used Bootstrap, jQuery, Thymeleaf, Spring HATEOAS and Spring MVC for building it, and that’s why:

Bootstrap

I really didn’t have much to do with CSS and web design in general before I did this project, so Bootstrap came as a rescue. Everybody can do good-looking user interfaces with Bootstrap. And in a real world project there would probably be someone professional doing the web design.

jQuery

I really didn’t have much to do with JavaScript before I did this project – wait, did I write this before? Sounds familiar. However, jQuery seems to be the library of choice when working with JavaScript, and it worked out well.

Thymeleaf

If you want to generate HTML on the server in a normal request/response way, a standard way to do this is using some kind of template engine. Thymeleaf uses valid HTML as templates and adds template expressions as additional attributes with a th prefix. This way you can build working mock-ups and integrate them directly into your codebase. People specialised on web design may create CSS, HTML and JavaScript which can be used for presentations, and we can be sure that our product will look the same in the end.

Spring HATEOAS

Spring HATEOAS is a library for dealing with the hypermedia part in RESTful applications. I guess it was intended to use in RESTful web services, but there is no reason for not using it here. We have our domain objects delivered by our services. They have relations to other domain objects. In the browser, those relations are represented by links to another resource or sub-resource, for example the resource /movies/42 has a relation to its list of comments, which can be found following the URI /movies/42/comments. To convert our domain object into a resource, we need to create those links. Spring HATEOAS brings structure into this process by providing a Link and a Resource class, where the latter may contain a domain object and a list of Link objects. Furthermore it contains a ResourceAssembler interface which can be implemented to build special domain-resource-converters for domain classes, doing the conversion in exactly one place. This way it becomes a three-stepped process: getting domain data from a service, converting it into resources and inserting it into the template.

Spring MVC

I needed a request/response style web framework, and Spring MVC is one of them. I wanted to check if it fits well. And also I wanted to write a web application without a line of XML, and since that’s possible with Servlet 3.0 and Spring 3.1, I did it here. Note that you need a container capable of Servlet 3.0 to run the application (Tomcat 7 will do).

What now?

I encourage you to have a look at the code and let it run. Does it feel good? Or is an SPA maybe a better solution? Let me know what you think.

Kommentare

  • Dirk

    Great article and coding. Wondering why so much people
    are building SPA? Maybe because we can get complete
    technology stacks like angularjs to build such apps.

    But with your demo application, we got one for Roca-Style
    Apps, too ­čśë

  • Paul

    When I enter the date in the form dd.MM.YYYY I get the error:
    Field error in object ‘movieForm’ on field ‘startDate’: rejected value [01.02.2003]; codes [typeMismatch.movieForm.startDate,typeMismatch.startDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [movieForm.startDate,startDate]; arguments []; default message [startDate]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’ for property ‘startDate’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Date for value ‘01.02.2003’; nested exception is java.lang.IllegalArgumentException: Unable to parse ‘01.02.2003’]

    What environment are you running your code under? Thanks!

  • Paul

    Ah, I see. Contrary to your internal documentation the date format is expected to be
    YYYY-MM-DD

  • Arjan

    7. April 2013 von Arjan

    Nice. The solution to define WEB-INF/templates/movie/partial/ with templates that simply include only a partial, is nice too, especially when not defining too many templates.

    Just as a reference: the Spring Travel MVC demo nowadays uses Thymeleaf with Apache Tiles and Spring Web Flow, also supporting Ajax-loaded partials. I think those partials are only used for “Change Search” on the search results, then requesting /search?...&fragments=searchForm. See a blog post on SpringSource, Bringing new life to Spring Travel with Thymeleaf.

    (Thanks for the clean demo code!)

  • lenin

    Thanks for sharing such a nice application code for study. I can run it using Jetty. But when i convert this as a eclipse project and load into spring suit tool (eclipse: maven) project, and run using tomcat 7. I cant access the application. it cant able to find the right dispatcher for \movies path..any suggestions? I keep debugging for some time..any help would be appreciated..

  • lenin

    I see this pom.xml has jetty configuration..i removed it and tried to run with tomcat and spring tool suite, but cant access applicaitn.no error!!

    • MiB

      Lenin, if you run mvn package tomcat:run instead of using the server you added to STS you would see the URL to your application that tomcat peruses in the console when the app is starting on Tomcat.

      If you don’t like that path you can set “finalName” under the build element to something easier to remember.

  • Henri

    Hi Tobias,

    Thanks for this great article.
    In your article you mention about the code, but I can’t find it on he page.
    Could you please provide it ?

    Thanks
    Henri

    • Tobias Flohre

      2. December 2014 von Tobias Flohre

      Hey Henri, there’s a link in the text to the Github repo, maybe hard to find. It’s https://github.com/tobiasflohre/movie-database.
      Note that I updated it recently to use Spring Boot. And now there are three applications, one for movies, one for actors and one for the navigation. Feedback is always welcome.

Comment

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