Spring Web Flow – displaying your JSR-303 validation messages using FreeMarker

Instead of creating a custom validator in the traditional sense I’m relying on JSR-303 annotations to specify validation constraints, because, it is the future, and I shouldn’t have to do a load of coding to specify common validation requirements like an email address regular expression or a numeric value that is required to be within a defined range.

Using Spring web flow, I found that binding error messages weren’t available when I called “<@spring.showErrors ‘<br/>’/>” in my freemarker view (after I had bound the field I wanted to show errors for of course).

So where are my error messages?

It turns out that Spring Web Flow has a different way of providing the user with feedback messages. The Spring Web Flow reference documentation says: “Spring Web Flow’s MessageContext is an API for recording messages during the course of flow executions”.

The message context (with all your binding error messages in it) can be found here: flowRequestContext.messageContext. I’ve written a couple of macros to make retrieving error messages from this object a little easier:

<#--
 * Shows flow messages (which reside in flowRequestContext.messageContext)
 *
 * @param source Name of the field that caused the error
 * @param severity String representation of org.springframework.binding.message.Severity
 * @param separator the html tag or other character list that should be used to
 *    separate each option. Typically '<br>'.
 * @param classOrStyle either the name of a CSS class element (which is defined in
 *    the template or an external CSS file) or an inline style. If the value passed in here
 *    contains a colon (:) then a 'style=' attribute will be used, else a 'class=' attribute
 *    will be used.
 * @param tag The HTML tag to wrap the error in
-->
<#macro showFlowMessages source severity separator classOrStyle="" tag="">
  <#assign messages = flowRequestContext.messageContext.getMessagesBySource(source)/>
  <#if (messages?size > 0)>
    <#list messages as message>
      <#if message.severity?string == severity>
        <#if classOrStyle == "" && tag == "">
          ${message.getText()}
        <#else>
          <#if classOrStyle == "">
            <${tag}>${message.getText()}</${tag}>
          <#else>
            <#if tag == ""><#local tag = "span" /></#if>
            <#if classOrStyle?index_of(":") == -1><#local attr="class"><#else><#local attr="style"></#if>
            <${tag} ${attr}="${classOrStyle}">${message.getText()}</${tag}>
          </#if>
        </#if>
        <#if message_has_next>${separator}</#if>
      </#if>
    </#list>
  </#if>
</#macro>

<#--
 * Shows flow messages (which reside in flowRequestContext.messageContext) in an ordered or unordered list
 *
 * @param source Name of the field that caused the error
 * @param severity String representation of org.springframework.binding.message.Severity
 * @param classOrStyle either the name of a CSS class element (which is defined in
 *    the template or an external CSS file) or an inline style. If the value passed in here
 *    contains a colon (:) then a 'style=' attribute will be used, else a 'class=' attribute
 *    will be used.
 * @param ordered Whether or not the macro should output the list as an <ol> or <ul>
-->
<#macro showFlowMessagesList source severity classOrStyle="" ordered=false>
  <#local errorsList><@showFlowMessages source, severity, "", "", "li" /></#local>
  <#if errorsList?trim != "">
    <#if classOrStyle == "">
      <#local attr="">
    <#elseif classOrStyle?index_of(":") == -1>
      <#local attr=" class=" + classOrStyle>
    <#else>
      <#local attr=" style=" + classOrStyle>
    </#if>
    <#if ordered><ol${attr}><#else><ul${attr}></#if>
    ${errorsList}
    <#if ordered></ol><#else></ul></#if>
  </#if>
</#macro>

I’ve added these to my spring extensions, which you can download here: springx.ftl

3,477 thoughts on “Spring Web Flow – displaying your JSR-303 validation messages using FreeMarker

  1. 1 bedroom apartment for sale in dubai silicon oasis real estate open house events dubaistp real estate dubaimonthly rental apartments in bur dubai

  2. привет бразы хочу нахватить вот реги что за качество скажите? надеюсь не 15 минутка? купить кокаин

  3. Property For Sale In Dubai Palm Jumeirah Dubai property market data 2025 explained for real estate agentslong term hotel rentals in dubaivilla on rent for labours in dubai

  4. Такое бывает у СПСР у меня то же он не бился а потом все нормально было хотя мне ей вчера должны были привезти но не привезли купить кокаин

  5. Apartments for Sale in Dubai Emaar what is the new project in dubaito let flatApartments for sale in Damac City

  6. Разработка интернет-магазина под ключ — эффективный способ вывести продажи в онлайн и расширить клиентскую базу. Переходите по запросу цена разработки сайта интернет магазина. Создаем современные, быстрые и удобные магазины с каталогом товаров, онлайн-оплатой, интеграцией с CRM и службами доставки. Адаптивный дизайн, SEO-оптимизация и готовность к продвижению помогут вашему бизнесу привлекать больше покупателей и увеличивать прибыль. Индивидуальные решения для любых ниш и масштабов бизнеса.

  7. Хороший магазин тоже не раз уже к нему обращался я считаю что этот магазин достоин огромного внимание Мир тебе бро и процветания удачи в работе :o k:;ОБРАЩУСЬ ЕЩЕ К ТЕБЕ БРО ОБЯЗАТЕЛЬНО ЕЩЕ РАЗ УДАЧИ купить кокаин

  8. 5 Bedroom Villa for Sale in Dubai uptown motor city dubai apartments for rentdecription of polo residence meydan dubai by provident real estatebest place to invest in property in dubai

  9. Okay folks gather around because this Miami rental nightmare needs to be discussed. Then you show up and its a whole different story. Plus they want a 2000 hold on your debit card. Ive lived here for years and still get burned occasionally. miami car rental luxury — dont just grab the cheapest option on Kayak. ask anyone whos tried Ubering across the 305 during rush hour. leather seats that dont fuse to your skin in August. most are smoke and mirrors with decent SEO. no games no bait-and-switch no hidden asterisks. Heres the only honest broker for premium vehicles across South Florida miami beach fl car rentals https://luxury-car-rental-miami-5.com Yeah finding parking in Wynwood will test your patience — but thats not on them. Anyway glad theres at least one straight shooter left in this rental jungle.

  10. Apartments for Sale in Dubai Emaar uphill real estate brokers office in dubaiPrincess Towershare rent house in karama dubai

  11. жте907? Вроде говорят что пока не доступен – находиться на экспертизе… Откуда инфа? купить кокаин

  12. 2 Bedroom Apartment In Dubai Apartments for sale in Iconic TowerSolen Residencevilla for rent in mamzar dubai

  13. отпишите народ за 5 iai кто брал спс заранее купить кокаин

  14. Why to Invest in Dubai Real Estate? investing in dubai propertiesJLT Cluster Mfully furnished flat for rent in dubai

  15. Been through enough garbage to last a lifetime. You spot a tempting offer online: brand new Porsche unlimited miles price that makes you click instantly. Plus they lock up 3500 on your card for who knows how long. Fool me ten times? Thats just the 305 experience. When you need a reliable luxury car rental miami. anyone whos taken public transport here knows the struggle is real. South Beach night out Bal Harbour shopping spree or a spontaneous Keys adventure — AC must be ice cold and unlimited miles non-negotiable. most are shiny websites hiding the same beat-up fleet with fresh wax. no games no bait-and-switch no hidden fees in the fine print. prices change by the hour so dont wait around: luxury car rental coral gables miami https://luxury-car-rental-miami-10.com also bring quality shades unless you enjoy driving into the sun like a vampire. Anyway glad theres at least one honest rental joint left in this town.

  16. Уточнять не у кого купить кокаин

  17. Flats for Sale in Dubai Villas for sale in The Valleyapartment for rent in discovery gardens dubaistudio for rent in business bay

  18. Flat For Rent In Dubai sell any property dubaidubai industrial real estate marketdowntown dubai apartments sale

  19. Все верно до сих пор разгребаем купить кокаин

  20. Okay folks gather around because this Miami rental nightmare needs to be discussed. You see a sweet ride online — clean spec fair price looks legit. Different car scratches all over and that all-inclusive price? Yeah that didnt include insurance fees or the mandatory cleaning charge. Ive lived here for years and still get burned occasionally. thats exactly how they hook you. Miami without proper wheels is basically a hostage situation. Design District shopping late-night South Beach cruising or a spontaneous drive down to Homestead — AC must freeze your teeth and unlimited miles or bust. most are smoke and mirrors with decent SEO. no games no bait-and-switch no hidden asterisks. check availability before spring break crowds wipe them out: opf fl luxury car rentals https://luxury-car-rental-miami-5.com also bring quality shades unless you enjoy driving into a nuclear flare every evening. drive safe and maybe decline that premium roadside upsell — its always a scam.

  21. Palm Jumeirah Villas for Sale dubai property show india1 night cheap hotel apartments in dubaifreehold property in dubai festival city

  22. сделать татуировку салоны сделать тату в питере

  23. здравствуйте. магазин работает? купить кокаин

  24. Trust me Ive learned everything the hard way so you dont have to. Then you actually show up to grab the keys. Completely different car sitting there — dents everywhere smells like cheap air freshener covering something worse and that dream price? Doesnt include the mandatory 50 daily insurance or the 300 administrative fee they invent at checkout. Eleven years in South Florida and these clowns still almost get me. luxury car rental in miami. anyone whos tried the bus here knows exactly what I mean. Key Biscayne sunset Design District shopping or a spontaneous drive down to the Everglades — AC must be arctic and unlimited miles non-negotiable. Ive tested maybe 60 rental companies across Dade Broward and Collier. Finally found one outfit that actually delivers whats in the photos. prices change hourly so check before the weekend crowd wipes them out: miami car rental luxury miami car rental luxury also bring polarized shades unless you enjoy driving into the sun like a blind bat. Anyway glad theres at least one straight operator left in this rental circus.

  25. Flat for Sale in Dubai 2 bedroom Apartments for sale in World Trade Centerdubai property valuesmudon dubai properties group

  26. Alright real talk about the Miami rental game — its a straight-up jungle out here. You find this amazing deal online: brand new Beamer unlimited miles price that makes you smile. Different car waiting — scratches everywhere smells like an ashtray and that amazing price? Doesnt include the mandatory 400 cleaning fee or the 30 per day toll pass you cant waive. Fool me eight times? Thats just another Tuesday in the 305. luxury car for rent. Miami without decent wheels is basically a hostage situation. leather seats that wont weld themselves to your thighs in July. Ive run through maybe 45 rental companies across Dade Broward and Monroe. what you book is what shows up no surprises no fine print nightmares. Heres the only honest source for premium wheels across South Florida premium vehicle rental premium vehicle rental Yeah parking in South Beach will cost you a nice bottle of wine — but thats the Miami tax. drive safe and absolutely skip that windshield protection upsell — pure profit for them zero value for you.

  27. Всем привет Мой Трипчик купить кокаин

  28. Alright listen up because Im about to save you a massive headache. Miami rental game is wild — half these clowns show you a Mercedes online and hand you a busted Charger with mismatched tires. You land at MIA tired grab an Uber to the rental office and bam — surprise 1500 hold on your card. No thanks Im too old for this nonsense. luxury car for rent. any local will tell you the same thing. leather that doesnt glue to your legs in July heat. Ive tested maybe 25 rental outfits across Dade and Broward. Finally stumbled on one that doesnt play games. Heres the only straight-up source for premium wheels in South Florida luxury car rental coral gables miami luxury car rental coral gables miami Yeah parking in Brickell will cost you a small mortgage — but thats city life. Anyway at least theres one honest rental joint left in this town.

  29. 3 Bedroom Villa For Sale In Dubai dubai property financing 10-year interest freeKeturah Resortcheap apartment for rent in dubai monthly

  30. Alright let me drop some truth about the Miami rental scene — its an absolute minefield. You spot a tempting offer online: brand new Porsche unlimited miles price that makes you click instantly. Plus they lock up 3500 on your card for who knows how long. Ten years in South Florida and these jokers still almost catch me slipping. luxury car rental in miami. Miami without solid wheels is basically a punishment. South Beach night out Bal Harbour shopping spree or a spontaneous Keys adventure — AC must be ice cold and unlimited miles non-negotiable. Ive run through maybe 55 rental companies across Dade Broward and Palm Beach. no games no bait-and-switch no hidden fees in the fine print. prices change by the hour so dont wait around: rent luxury sedan https://luxury-car-rental-miami-10.com Yeah parking in Brickell will cost you a nice dinner — but thats just how it is down here. drive safe and absolutely skip that paint protection upsell — pure robbery.

  31. все как обычно работает купить кокаин

  32. сделать тату в питере тату салон спб цены

  33. apartments for sale in dubai marina dubai nice home real estatedubai properties new projectmonthly apartment dubai

  34. Swear Ive seen every scam in the book by now. You find a killer listing online: sleek Audi convertible price almost too good to be true. Different car sitting there — bald tires dashboard lit up like a Christmas tree and that killer price? Yeah doesnt include the non-negotiable 45 daily insurance or the 500 deposit they forget to mention. Fool me nine times? Thats just the Miami welcome committee. luxury car rental in miami. anyone whos tried the trolley system knows what Im talking about. leather seats that dont glue to your skin in August. most are polished turds with fake five-star reviews. what you reserve is what you get period end of story. rates change daily so check before the holiday crowd hits: rent a porsche miami https://luxury-car-rental-miami-9.com also bring polarized shades unless you enjoy driving blind into the sunset every night. Anyway glad theres at least one honest operator left in this rental jungle.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>