如何避免在JSF方法表达式中跳过NullPointerException?

时间:2018-04-27 13:17:15

标签: jsf nullpointerexception jsf-2.2

我了解JSF可以配置为将null转换为""(反之亦然?)。我认为这很可怕,因为它有可能隐藏错误,但我看到了这一点,因为它用于网络前端/网络前端 - 后端数据传输environemnt。

但是,在下面的示例中,我想知道是否跳过因NullPointerExceptionbackingBean0.property0而应该抛出的null是否有点过分而且看起来微不足道如果您不立即开始提取MCVE,这可能会花费您数小时的调试时间:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:outputLabel value="#{backingBean0.createLabel(backingBean0.property0.property0)}"/>
    </h:body>
</html>

BackingBean0

@Named
@ViewScoped
public class BackingBean0 implements Serializable {
    private Entity0 property0 = null;

    public Entity0 getProperty0() {
        return property0;
    }

    public void setProperty0(Entity0 property0) {
        this.property0 = property0;
    }

    public String createLabel(String value) {
        if(value == null) {
            throw new IllegalArgumentException("value mustn't be null");
        }
        return value;
    }
}

Entity0

public class Entity0 {
    private String property0;

    public String getProperty0() {
        return property0;
    }

    public void setProperty0(String property0) {
        this.property0 = property0;
    }
}

如何关闭此行为,即由于EL评估期间抛出NullPointerException而导致页面加载失败?我可能没有在这里获得JSF的核心概念吗?

我在Payara 4.1.2.181上使用PrimeFaces 6.2。

2 个答案:

答案 0 :(得分:0)

以简单的方式,这可以是一个解决方案:

@Named
@ViewScoped
public class BackingBean0 implements Serializable {

    private Entity0 property0;
    // serialVersionUID is important to serialize your bean
    private static final long serialVersionUID = 1L;

    // Try to instance your variable before render page, see below:
    @PostConstruct
    public void beanInit(){
        property0 = new Entity0();
    }
    ...
}

或者在.xhtml文件中:

</html>
...
<h:body>
  <h:panelGrid id="grid" columns="1">
    <h:outputLabel value="#{backingBean0.createLabel(backingBean0.property0.property0)}"
                   rendered="#{backingBean0.property0 != null}">/>
  </h:panelGrid>
</h:body>
</html>

或者在web.xml中配置错误页面:

<error-page>
    <error-code>500</error-code>
    <location>/faces/error.xhtml</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/faces/error-page-not-found.xhtml</location>
</error-page>

答案 1 :(得分:-1)

https://docs.oracle.com/javaee/7/tutorial/bean-validation002.htm#top

<context-param>
    <param-name>
        javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
    </param-name>
    <param-value>true</param-value>
</context-param>