Tag Archives: spring mvc

Model variables for all views in Thymeleaf 2.1 with Spring MVC

Recently I’ve stumbled upon quite common problem – how to inject a few variables to every Thymeleaf view in application. Of course there is @ModelParam annotation, I could use interceptor or @ControllerAdvice. All solutions are described on StackOverFlow (it is about controllers).

The problem was that I wanted to put Maven build information in that model (to show version and build time in footer). Therefore I did not need application-scope wiring, as build informations are available during Spring’s container startup. So I’ve found another solution dealing with model itself on the lower level – pure XML configuration. There is a special property in ThymeleafViewResolver that can be used – static variables. So code sample can look like this:

<bean id="thymeleafViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="staticVariables">
            <map>
                <entry key="myModelVariableIWantToSet" value="My model variable value" />
                <!-- All placeholders taken from context:property-placeholder tag can be used as value-->
            </map>
    </property>
</bean>

All defined variables are put into all Model instances that are linked to Thymeleaf views. If You are just serving plain JSON it does not go there – that can be expected behaviour or not! Be aware of that fact.

Spring MVC Revisited

Recently I had an opportunity to play with architecture of a new internal app in my company. In order to properly do my job I’ve reread whole Spring MVC documentation. It was very refreshing ( after a while of using this framework ) to discover several new things. My goal is just to present short list of features with links to docs. There is no point in reinventing the wheel 😉

Matrix Params

Ever wanted to provide more data with just URI? Matrix variables are the best way to do this. Just look at the URI presented:

http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,,+3.91;AZN=236.00,+103.00;SBRY=375.50/account;name=roger;number=105;location=stoke-on-trent,uk

Yep, you can process it and extract data very easilly. Above URI and nice blog posts about them can be found on Captain’s Debug blog (second part with code snippets here).

ModelAttribute

I am used to using ModelAttribute annotation, mostly on update/save actions in my controllers. What I did not know is that this annotation can be also used with methods. Remember all the situations when You must fill several model variables with data just in order to render them as eg. SELECT-tag values? Now you create just one method in controller and annotate it with @ModelAttribute to put method return value in model. More information can be found in spring docs.

Flash attributes with redirects

I remember problems with simple flash redirects a few years back (circa early Spring’s version 3, flash attributes were introduced in 3.1). Today they are even better handled – You do not need to manually put them into FlashMap. There is a nice class RedirectAttributes which greatly improves coders’ quality of life. Just look at this code:

@RequestMapping(value = "/accounts", method = RequestMethod.POST)
 public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
   if (result.hasErrors()) {
     return "accounts/new";
   }
   // Save account ...
   redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
   return "redirect:/accounts/{id}";
 }

Above example comes from RedirectAttributes API, but there is also short Spring doc section and simple tutorial.

BindingResult order

There is nothing new in BindingResult interface. But what cought my attention is the need for this interface be declared as first parameter after @ModelAttribute in controller’s method to work!. I was not aware of that and I assume knowing that can be real time-saver. Short example:

public String addNewBlogger(@ModelAttribute("blogger") Blogger blogger,
            ModelMap map, BindingResult results) 

The above example will not work properly. You will get either exception or application’s logic will behave strangely (depends mostly on error handling and view layer/resolver). Proper solution look like this:

public String addNewBlogger(@ModelAttribute("blogger") Blogger blogger, BindingResult results, ModelMap map) 

Simple creation of URIs

Very often there is a need to create a new URI, eg. to perform redirect. Concatenating string values with parameters is not often clean and simple (not to mention it is very error prone). In order to ease developers’ life Spring provides very dsl-like solution with MvcUriComponentsBuilder class. More can be found in documentation.