Pregunta

I'm using Spring in a Java Web Application with Thymeleaf on standard HTML pages (not JSP). I have forms on several pages with several text inputs. I would like to reference some variable for maxlength on the text inputs. For example:

Current:

<input id='name' type='text' maxlength='20' />

Goal:

<input id='name' type='text' maxlength='${nameMaxlength}' />

I would prefer to put these in a file somewhere that my Java code can access, so that the client-side and server-side validation can reference the same values. Are there any best practices for this sort of functionality?

¿Fue útil?

Solución

If you are using Thymeleaf with the Spring dialect you could do the following:

package somepackage;

public final class WebConsts {

   public static final int MAX_LENGTH = 20;

   private WebConsts(){}
}

<input id="name" type="text" th:maxlength="${T(somepackage.WebConsts).MAX_LENGTH}" />

The expression in maxlength is a standard Spring EL expression

Otros consejos

In Fuwesta I used a lot of tricks to reduce such duplication of information. My standard approach for this is to put the information into MessageSource. It's pretty easy and you have a nice access via #{constant.nameMaxLength}. Another approach would be to put this information always into the model.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top