2

I am reading a String value from database and printing it onto a jsp page through a servlet. The Problem is that on the Jsp the String 'null' is getting printed in case the field in the database is null. I need to have a blank editbox instead if the value in the database is null.

My database Access Object:

 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;
    }

My Servlet:

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

My Jsp:

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

My Display if the field is null: My Display

My database is Oracle 11g and Browser is FireFox.

Stanley Mungai
  • 4,044
  • 30
  • 100
  • 168

5 Answers5

5

You should avoid using scriplets in JSP. Use JSTL and EL instead.

You need to test for null string before printing your value. When you try to print an object reference which is null, the null reference is converted to "null" string.

This is how you pre-test for null using EL:

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

Note that not empty will check for both null and empty string.

See also:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

You would try something like:

<%=request.getAttribute("custempid") == null ? "" : request.getAttribute("custempid") %>
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0

you can do this way

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

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

note use jstl/el instead of using scriplets

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

The getAttribute() method returns Object

an Object containing the value of the attribute, or null if the attribute does not exist.

And when you try to convert it to String directly it invokes

String.valueOf(Object obj)

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So add a null check/empty string check. or now a days no one using scriplets and as Rohit suggested movie to Expression language,which makes life easy

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

It is printing null because the field value itself is NULL. If the query were returning an empty resultset then it would've printed a blank.If you want to enforce a different behaviour, add a custom condition like

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