JSF javax.faces.convert Converter getAsString Object null

I am working on an application and I used JSF in this application, I wrote a Java class that implements this JSF interface javax.faces.convert , and also overwrites the getAsString method for the converter, here is the Java document of this method

 java.lang.String getAsString(FacesContext context, UIComponent component, java.lang.Object value) 

But sometimes the value here is Null , sometimes it works well,

Does anyone know why this value is null here? how to prevent this?

0
source share
2 answers

This will be null if the model value is null . For instance,

 public class SomeBean { private SomeObject someObject; // Let assume, someObject is never initialized and defaults to null. } 

If you use

 <h:outputText value="#{someBean.someObject}" converter="someConverter" /> 

then getAsString() will be called with a null value.

In addition, if you use, for example,

 <h:selectOneMenu ... converter="someConverter"> <f:selectItem itemValue="#{null}" itemLabel="Please select ..." /> <f:selectItems value="#{data.availableItems}" /> </h:selectOneMenu> 

then getAsString() will be called with a null value for the "Please select ..." element.

If you encounter a NullPointerException , this is actually a bug in the version of your own converter. You cannot disable the supplied value null . Moreover, the javadoc, which you obviously already found , also explicitly indicates that the value of the model object may be zero.

value - the value of the model object to be converted (may be null )

You should just check it out yourself. Here is a typical example of what the converter should look like for a dummy User object:

 @Override public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) { if (submittedValue == null || submittedValue.isEmpty()) { return null; } try { return userService.find(Long.valueOf(submittedValue)); } catch (NumberFormatException e) { throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e); } } @Override public String getAsString(FacesContext context, UIComponent component, Object modelValue) { if (modelValue == null) { return ""; } if (modelValue instanceof User) { return String.valueOf(((User) modelValue).getId()); } else { throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e); } } 
+2
source

Look converter

 public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) { if (o == null) { return ""; } Value p = (Value) o; if (p.getId() != null) { return p.getId().toString(); } return (p.toString()); } 
-1
source

Source: https://habr.com/ru/post/1207336/


All Articles