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

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

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

  2. Женский онлайн портал https://stepandstep.com.ua все о жизни стиле и здоровье. Статьи о красоте отношениях семье и саморазвитии. Полезный контент для женщин любого возраста.

  3. Женский журнал https://a-k-b.com.ua все о стиле здоровье и отношениях. Практические советы тренды и вдохновение для повседневной жизни.

  4. Туристический портал https://swiss-watches.com.ua для путешественников: направления маршруты советы и лайфхаки. Подбор отелей билетов и экскурсий идеи для отдыха и полезные рекомендации. Планируйте поездки легко и открывайте новые страны с комфортом.

  5. Посмотрите здесь https://happyholi.ru мебель на заказ. Работа супер цены адекватные а сроки не затягивают. Нам понравилось.

  6. гнойный хирург на дом частная перевозка лежачих больных

  7. Latest Liberian business news https://forbesliberia.com market analysis economic trends and technology developments. Learn about key events investment opportunities and business prospects in the country.

  8. Если бизнес масштабируется manage top демо помогает убрать хаос в задачах документообороте и рабочем взаимодействии между командами. Решение сводит ключевые процессы в одной системе чтобы руководитель получал реальную картину по команде задачам согласованиям и финансам без Excel и ручных таблиц. Это удобное решение для компаний которым важны контроль прозрачность работы и уверенное масштабирование без лишней рутины и ежедневных потерь времени каждый день.

  9. Фундамент под ключ https://fundament-v-spb.ru любой сложности: ленточный плитный свайный. Профессиональный подход современные технологии и точный расчет для долговечности и безопасности здания.

  10. На сайті 500pokupok.com зібрано багато статей із оглядами товарів підбірками та рекомендаціями. Зручний ресурс для тих хто хоче зробити правильний вибір перед покупкою.

  11. портал новин inews.in.ua висвітлює події в Україні та світі а також теми технологій. Тут можна знайти новини про гаджети техніку ІТ та актуальні тренди.

  12. Покупка шаблона Аспро Next — готовое решение для быстрого запуска современного интернет-магазина на 1С-Битрикс. Переходите по запросу цена Аспро Next на Битрикс. Шаблон сочетает стильный дизайн, удобный каталог, адаптивную верстку и широкий набор маркетинговых инструментов для увеличения продаж. Подходит для разных ниш бизнеса, легко настраивается и интегрируется с необходимыми сервисами. Оптимальный выбор для тех, кто хочет запустить эффективный онлайн-магазин без лишних затрат времени.

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>