繁体   English   中英

我的jsp打印'null'而不是null

[英]My jsp printing 'null' instead of null

我正在从数据库中读取String值,并通过servlet将其打印到jsp页面上。 问题在于,如果数据库中的字段为空,则在Jsp上将打印字符串'null'。 如果数据库中的值为null,则需要一个空白的editbox。

我的数据库访问对象:

 public String getVerEmpId(retailcustomervergobean rcvb) {
        String var = "";
        custid = rcvb.getCustid();
        Connection conn;
        try {
            conn = db.getDbConnection();
            String sql = "select CUST_EMP_ID from retail_cif_master where cust_id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, custid.toUpperCase());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                var = rs.getString("CUST_EMP_ID");
            }
        } catch (Exception asd) {
            System.out.println(asd.getMessage());
        }
        return var;
    }

我的Servlet:

String custempid = rcvd.getVerEmpId(rcvb);
request.setAttribute("custempid", custempid);

我的Jsp:

name="custEmpId" readonly="true" value="<%=request.getAttribute("custempid")%>"

如果字段为空,则显示我的信息: 我的显示器

我的数据库是Oracle 11g,浏览器是FireFox。

您应该避免在JSP中使用scriplet。 请改用JSTL和EL。

您需要在输出null之前测试null字符串。 当您尝试打印一个null的对象引用时,该null引用将转换为"null"字符串。

这是使用EL预测试null

<c:out value="${not empty custempid ? custempid: ''}" />

请注意, not empty将同时检查null和空字符串。

也可以看看:

您可以尝试类似:

<%=request.getAttribute("custempid") == null ? "" : request.getAttribute("custempid") %>

你可以这样

String x=request.getAttribute("custempid");
if(x.equals("null"))
x=""

name="custEmpId" readonly="true" value="<%=x%>"

请注意使用jstl / el而不是使用scriplets

getAttribute()方法返回Object

包含属性值的Object;如果属性不存在,则为null。

当您尝试将其直接转换为String时,它将调用

String.valueOf(Object obj)

如果参数为null,则字符串等于“ null”; 否则,返回obj.toString()的值。

因此,添加一个空检查/空字符串检查。 或现在没有人使用scriplets并像Rohit推荐的那样用电影来表达语言,这使生活变得轻松

因为字段值本身为NULL,所以它打印为null。 如果查询返回一个空结果集,那么它将打印出空白。如果您要强制执行其他行为,请添加一个自定义条件,例如

if(custempid==null)
 custempid="";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM