Search code examples
jspjstljavabeansel

NPE in JSTL foreach: Getting Null Pointer Exception when access Child Class variable in JSTL foreach


Getting Null Pointer Exception when access Child Class variable in JSTL foreach, even when data is there for that variable.

I have class structure like this -

public class Question implements Serializable {
    @Getter
    private String type;

    @Getter
    private String question;
}


final public class OptionSingleSelectQuestion extends Question {
    static class Option {
        @Getter
        private String uuid;
        @Getter
        private String label;

    }

    @Getter
    private List<Option> options;

    @Getter
    private String optionChosen;
}

I accessing options like this in JSP -

<c:forEach var ="option"  items="${question.getOptions()}">
      ${option.getLabel()}
</c:forEach>

Getting error for the line ${option.getLabel()} -

java.lang.NullPointerException
    javax.el.BeanELResolver.invoke(BeanELResolver.java:159)
    org.apache.jasper.el.JasperELResolver.invoke(JasperELResolver.java:147)
    org.apache.el.parser.AstValue.getValue(AstValue.java:159)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:943)

Solution

  • This particular NPE coming from javax.el.BeanELResolver#invoke(),

    java.lang.NullPointerException
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:159)
    

    has one of the probable causes that bean class couldn't be found. And indeed, in your specific case the Option class is package-private. You need to ensure that the bean class is public (and also that it has a default constructor). This is also specified in the JavaBeans Specification.

    Unrelated to the concrete problem, ${option.getLabel()} can be simplified to ${option.label}. See also the Expression Language (EL) Specification.