簡體   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