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,470 thoughts on “Spring Web Flow – displaying your JSR-303 validation messages using FreeMarker

  1. так что бро не стоит беспокоиться по поводу порядочности этого магазина они отправляют достаточно быстро и конспирация хорошая и качество на высоте купить мефедрон Как и было обещано адрес оператор прислал где-то в 23.

  2. Всем привет с наступивщимидавно не работал с этим магазиномподскажите как у него работа все ттакже четко? купить мефедрон Не бро ну одно дело 250 заместо 50мг а другое когда даже 250мг не берет.

  3. 2 Bedroom Apartment Dubai For Sale dubai latest news on propertydowntown dubai rentbest villas in dubai for rent

  4. Нашёл интересный материал по этому вопросу — где предлагают адекватные условия для перевода денег за границу онлайн. Вот здесь всё по полочкам расписано: комиссия за международный перевод https://mezhdunarodnye-platezhi-fra.ru Суть в следующем — разница в итоговой сумме бывает значительной. Дело в том что любой международный перевод — требует предварительного сравнения условий. Дополнительная информация — перед подтверждением перевода стоит проверить итоговую сумму. В противном случае можно получить менее выгодные условия. В итоге — стоит потратить время на анализ перед любой отправкой средств.

  5. Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear.

    She never wants to go back! LoL I know this is totally off topic
    but I had to tell someone!

  6. Удачных продаж и с наступающим НОВЫМ ГОДОМ…. купить мефедрон Либо вы прекращаете оффтопить в ветке магазина к оффтопу относятся: сообщения НЕ по теме личная переписка и т.п. либо я буду банить.

  7. Ребята всем привет. Обещают одно а по факту другое. То ДСП сыпется. Короче нашел наконец нормальную контору — купить кухню от производителя в спб недорого. Проект бесплатно. В общем там цены и каталог — купить готовую кухню в спб от производителя https://zakazat-kuhnyu-qwe.ru Проверяйте по этому списку. Перешлите кому надо.

  8. Ребята всем привет. Оббегал все салоны в городе — везде одно и то же. То фасады покоробились от пара. Короче реальный цех в СПб без наценок — заказать кухню без посредников. Сделали за 2 недели включая замер. В общем вся инфа вот тут — купить готовую кухню от производителя купить готовую кухню от производителя Не ведитесь на салоны-прокладки с накруткой. Перешлите другу кто тоже мучается.

  9. Ça faisait un moment que je voulais essayer ce site. Télécharger un fichier fiable devenait vraiment galère. Après avoir suivi les étapes dans le bon ordre tout a fonctionné. Jai finalement déniché la bonne source et je voulais vous partager tous les détails vous pouvez consulter les informations à jour ici: apk 1xbet apk 1xbet. Voilà pour être clair — la dernière version est super fluide et intuitive. Je nai rencontré aucun problème lors du téléchargement. Jai comparé plusieurs apps mais celle-ci est la meilleure — croyez-moi vous ne serez pas déçus essayez-la sans hésiter. Je vous souhaite plein de réussite et de bons gains…

  10. Сегодня сделал заказ пока все ровно обещали к вечеру трек магаз робит купить мефедрон Прошу обратить внимание на кидок со стороны магазина на 50000 рублей в Украинской ветке.

  11. Слушайте кто недавно кухню делал. Задолбался я уже два месяца мучиться. То сроки изготовления по полгода обещают. Короче единственные кто не наваривается в тридорога — купить кухню от производителя в спб из массива. Сделали 3D-визуализацию бесплатно. В общем жмите чтобы не потерять контакт — где купить готовую кухню в спб https://zakazat-kuhnyu-rty.ru Проверяйте производителя по этому списку. Перешлите тому кто тоже мучается выбором.

  12. Real estate business for sale in dubai small flat for rent in dubairent for town house in dubaicheapest apartments for sale in uae

  13. Ребята здесь только курёха? купить мефедрон Магазин супер.от души мужики все как всегда оплатил поехал забрал 5

  14. Питерцы отзовитесь. То материалы фуфло — картон а не фасады. Икею всю излазил — не то. Короче реальные производители с совестью — заказать кухню напрямую у производителя. Фурнитура Blum а не говно. В общем там каталог и цены и отзывы реальные — купить заказать кухню https://zakazat-kuhnyu-gkl.ru Проверяйте производителя в этом списке. Сам полгода мучился теперь делюсь.

  15. Je cherchais une application mobile fiable pour mes paris. Tout le monde donnait des liens différents je ne savais plus où aller. Jai vérifié les dernières mises à jour pour lancer le processus sans erreur. Jai finalement déniché la bonne source et je voulais vous partager tous les détails vous pouvez consulter les informations à jour ici: 1xbet nouvelle version à télécharger 1xbet nouvelle version à télécharger. En deux mots laissez-moi vous expliquer — la dernière version est super fluide et réactive. Je nai eu aucun souci lors du téléchargement. Je vous parle de mon expérience personnelle — croyez-moi vous ne serez pas déçus essayez-la sans hésiter. Bonne chance à tous…

  16. Народ всем привет Цены космос а качество мыло То ДСП крошится Короче нашел наконец нормальное производство — кухни СПб от производителя напрямую Замерщик приехал на следующий день В общем вся инфа вот здесь — кухни на заказ санкт петербург https://kuhni-spb-uio.ru Проверяйте производителя по этому списку Сам столько нервов потратил теперь делюсь

  17. Купить Мефедрон Бошки Марихуану Гашиш Экстази Не знаю как в этом магазеа вот у всеми так уважаемой Мануфактуры тоже весной всплыло такое гавницо.В результате я попал на 50к и никакого возмещения от них не дождался между прочим.вот опять сегодня получил что заказал всё прошло ровно .быстро качество в этом магазине лучшее больше не где не заказываю .если нужно что то подождать я лучше подожду чем кидал буду кормить тоже влитал поначалу пока нашёл этот магазин по этому сам беру и друзьям советую .спасибо всей команде за отличную работу.с наступающими праздниками всех поздравляю.вообщем всем благодарочка.конечно была задержка которая заставила по нервничать но всё прошло на уровне и я получил свою посылочку

  18. Oceana Residences guideedward towers real estate dubai 971 50 345 44387ei8ht6 properties llc 2 Bedroom Townhouse for Sale in Dubai villa rooms for rent in deira dubaimarina apartments for salebarsha south villas for rent

  19. Ça faisait un bail que je voulais tester cette plateforme. Tout le monde donnait des liens différents impossible de sy retrouver. Jai vérifié les dernières mises à jour pour lancer le processus sans erreur. Jai finalement trouvé la bonne source et je voulais vous partager tous les détails vous pouvez consulter les informations à jour ici: télécharger 1xbet gratuit télécharger 1xbet gratuit. Bref ce que je voulais vous dire — lappli tourne super bien sur mon téléphone. les mises à jour se font toutes seules sans intervention. Jai comparé plusieurs applis mais celle-ci est la meilleure — croyez-moi vous ne le regretterez pas tentez le coup. Je vous souhaite plein de réussite et de gros gains…

  20. dubai properties rent villalanovo dubai propertyreal estate advisor dubai Ajman Villa for Sale tameer al sharjah real estate co llc dubaichannels to sell property in dubaidubai court property

  21. Купить Мефедрон Бошки Марихуану Гашиш Экстази я в среду оплатил ещё тс сразу сказал что отправка будет на следующей недели во вторник-среду.2с на высоте прет огого как сыпали по чуточки кто на что горазд у меня до сих пор постэффектыда иногда просто не можем находиться у компано мы стараемся всем ответить пытаемся все оптимизировать поймите нас тоже у всех разные часовые пояса и находиться 24 часа в онлайн нереально…

  22. dubai properties cordoba the villa floor planApartment for Sale in Opera District DubaiApartments for sale in Imperial Avenue Apartments for Sale in Dubai Emaar khalil dubai propertiesdubai property slumptop reasons to invest in dubai real estate

  23. Купить Мефедрон Бошки Марихуану Гашиш Экстази Для совсем новичков 1 к 15 будет даже много.чтоб расширенный был глаз.но только если мусора захотят найдут. просто мусора еслиб хотели найти то давно бы уже посыль пришла с сопровождением.

  24. Слушайте кто ремонт затеял. Оббегал все салоны в городе — везде одно и то же. То фасады покоробились от пара. Короче нашел нормальных производителей — купить кухню в спб с установкой. Сделали за 2 недели включая замер. В общем жмите чтобы не потерять — купить кухню от производителя в спб купить кухню от производителя в спб Не ведитесь на салоны-прокладки с накруткой. Сам полгода выбирал теперь знаю.

  25. Купить Мефедрон Бошки Марихуану Гашиш Экстази да конспирацию отработали ; стараемсяХочу выразить благодарность менеджерам данного магазина.Респектос бразы радуете не только Россию но и Украину отличный магаз

  26. Ребята всем привет. Качество пластилин. То ручки через месяц шатаются. Короче нашел наконец нормальную контору — купить кухню от производителя в спб недорого. Проект бесплатно. В общем сохраняйте — купить заказать кухню https://zakazat-kuhnyu-qwe.ru Проверяйте по этому списку. Перешлите кому надо.

  27. The IVYdubai investment property for salereal estate agent dubai exam Jumeirah Villas for Sale dusit thani dubai real estate exhibition febproperties for sale in dubai creek harbour the lagoonshow many property sold in dubai

  28. Купить Мефедрон Бошки Марихуану Гашиш Экстази Ты думаешь АМ под запретом уже будет? Откуда инфа?трипы почитайте кто уже бралЗа время работы легалрц сколько магазинов я повидал мама дорогая столько ушло в топку кто посливался кто уехал # но chemical-mix поражает своей стойкостью напором и желанием идти в перед не отступать и не сдаваться:superman:

  29. Jai testé plusieurs plateformes sans jamais être satisfait. Je ne trouvais pas la version officielle sur le Play Store. Jai vérifié les dernières mises à jour pour lancer le processus sans erreur. Jai finalement déniché la bonne source et je voulais vous partager tous les détails vous pouvez consulter les informations à jour ici: 1xbet com mobile 1xbet com mobile. Voilà pour être clair — après lavoir installée jai été agréablement surpris. linstallation était rapide et sans complication. Jai comparé plusieurs apps mais celle-ci est la meilleure — cest clairement lapplication la plus performante du marché. Bonne chance à tous…

  30. Слушайте кто в теме. Менеджеры врут про сроки. Короче реальные производители с цехом — купить готовую кухню в спб. Фасады из массива. В общем смотрите по ссылке — купить кухню спб купить кухню спб Не ведитесь на салоны. Перешлите тому кто ищет.

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>