如何检查JSP变量并隐藏值是否为null / empty或某些特定的字符串?

时间:2018-08-27 07:10:38

标签: java jsp

我正在创建一个项目,在该项目中我从数据库获取JSP页面中的设置数据。 如果任何字段数据值为null,则jsp页面显示为null,但我不想在jsp页面上显示它。请帮忙。我正在从bean中获取数据。

<%=p.getOffer()%>
<% String s = p.getOffer() %>
<% if (<%=s ==null) { %> 
show nothing
  

2 个答案:

答案 0 :(得分:1)

如果要在jsp中编码Java,则需要使用scriptlet标签(<%%>)。因此,如果要检查条件,则需要打开scriptlet标签。

<%    
    String s = p.getOffer();
    if (s != null && !s.equals("")) {
        out.print(s);
    } else { %>
<!-- s is either null or empty. Show nothing -->
<% }%>

答案 1 :(得分:0)

当值为null时,您想显示什么?无论如何,您的方法看起来不错:

<%=p.getOffer()%>               // Here you print the value "offer". If you don't want to show it when it is null, remove this line
<% String s = p.getOffer() %>   
<% if (<%=s ==null) { %>        // the <%= is unnecessary. if(s==null) is enough
show nothing                    // show nothing, why not inverse the if and show something

这是另一种方法:

 <%
    String s= p.getOffer();
    if(s != null){ %>
        Offer: <%= s%>
 <% }%>

这样,您仅在变量不为null时打印报价。 顺便说一句:不建议将String变量命名为“ s”,将其命名为“ offer”或其他便于阅读的内容。