问题描述:

Is there a way for Mojarra JSF to limit the size of textfields base on the backing model?

Example, normally:

<p:inputText required="true" id="firstname" maxlength="50" value="#{user.firstName}"></p:inputText>

class User {

@Size(max=50)

String firstName;

}

While I could add a maxlength property to every field, I think in the end I'll have a problem with maintenance specially when I have several forms that use the same field. And what if I changed the length of the field?

If I remember correctly apache myfaces has this feature in 1 of their extension library, any equivalent for mojarra?

I remember now I was using myfaces's myfaces-extval-property-validation library.

http://myfaces.apache.org/extensions/validator12/validation-modules-project/myfaces-extval-property-validation/index.html

Is there an equivalent from mojarra?

Thanks,czetsuya

网友答案:

Your requirement is better handled by specifying the constraints in a JSF Resource Bundle where you configure all such properties like error/validation messages and user field constraints like field max lengths and conversion patterns.

The problem with stashing all such information in a backing bean is that those constraints/properties will only be available to views that are backed by specific beans, as against a single resource bundle file that is available to the entire JSF Webapp. Deployment best practice will also advise that you put such things outside of your codebase. For your specific use case

  1. Create a java style package in your project. Let's say com.you.jsf.resources. In this package you'll store a .properties file that contains your field settings.

       field.maxlength = 50
    
  2. Configure the resource bundle package from 1) in your faces_config.xml file, where <var> specifies the variable name by which you want to access the resource file within your application

       <application>
     <resource-bundle>
    <base-name>com.you.jsf.resources</base-name>
    <var>conf</var>
     </resource-bundle>
       </application>
    
  3. The resource file (and it's contents) will now be available in the JSF context as #{conf['field.maxlength']}. This you can now use within your view as

      <p:inputText required="true" id="firstname" maxlength="#{conf['field.maxlength']}" value="#{user.firstName}"/>
    
网友答案:

you could have a bean property defining the maxlength. Then you can atleast change the length of all textfields of this type in one place.

@ManagedBean
@ApplicationScoped
public class MyBean {

    public int getType1MaxLength() {
        return 50;
    }
}

and the xhtml:

<p:inputText ... maxlength="#{myBean.type1MaxLength}" value="#{user.firstName}">
相关阅读:
Top