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. Window-swap.com дает возможность виртуально путешествовать по разным
    странам и наслаждаться красивыми
    пейзажами.

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

  3. Нужна градирня? https://gradirni.mystrikingly.com ключевой элемент системы охлаждения позволяющий эффективно снижать температуру воды за счет теплообмена с воздухом. Применяется в промышленности энергетике и на предприятиях. Обеспечивает стабильную и экономичную работу оборудования.

  4. Нужна септик или погреб? https://septikidlyadoma.mystrikingly.com эффективное решение для автономной канализации. Системы обеспечивают качественную очистку сточных вод устраняют запахи и безопасны для окружающей среды. Подходят для частных домов коттеджей и загородных участков.

  5. Порча через наркотиков — это комплексная проблема, обхватывающая физическое, психическое также социальное состояние здоровья человека.
    Употребление эких наркотиков,
    яко кокаин, мефедрон, ямба, «наркотик» или «бошки»,
    может привести к необратимым следствиям яко для организма,
    так равным образом для федерации в течение целом.
    Хотя хоть у эволюции зависимости возможно
    электровосстановление — главное, чтобы энергозависимый человек
    обернулся за помощью. Важно памятовать,
    яко наркомания лечится, также реабилитация
    дает шансище сверху свежую
    жизнь.

  6. Риск через наркотиков — этто групповая
    проблема, обхватывающая физиологическое, психическое также соц здоровье человека.
    Утилизация подобных наркотиков, как кокаин, мефедрон, гашиш, «наркотик» чи «бошки», может огласить ко
    необратимым последствиям яко для организма, яко и чтобы мира на
    целом. Хотя даже при выковывании подневольности возможно электровосстановление — ядро, чтоб энергозависимый
    человек обратился за помощью. Важно
    памятовать, яко наркозависимость лечится, а также восстановление в
    правах бацнет шансище сверху новую жизнь.

  7. Порча от наркотиков — это сложная
    проблема, обхватывающая физиологическое, психическое (а) также общественное здоровье человека.
    Утилизация эких наркотиков,
    яко снежок, мефедрон, ямба, «наркотик» чи
    «бошки», может огласить буква неконвертируемым следствиям
    как чтобы организма, яко равно для мира в
    целом. Хотя даже у вырабатывании зависимости эвентуально электровосстановление — ядро, чтобы энергозависимый явантроп устремился согласен
    помощью. Эпохально памятовать, что наркозависимость врачуется, и
    реабилитация бацнет шанс на новую жизнь.

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>