4

I want to check if a Integer value is empty. The value for Integer is completed in a form. Here is my code.

Here the value is introduced:

<input name="varsta" placeHolder="Varsta:" type="text" data-constraints='@NotEmpty @Required @AlphaSpecial'> <br/><br/>

Now I want to check if there are data introduced or not.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    Integer varsta = Integer.parseInt(request.getParameter("varsta"));
    request.getSession().setAttribute("varsta", varsta);

    try {
        DBConnection connection = new DBConnection();
        Connection con = connection.Connect();

        PreparedStatement ps = con.prepareStatement(
            "insert into user(Nume,Prenume,E_mail,Parola,Varsta,Sex,Greutate,Inaltime,Nivel_activitate,Calcul_calorii)" + 
            "values ('"+nume+"','"+prenume+"','"+email1+"','"+parola+"','"+varsta+"','"+sex+"','"+greutate+"','"+inaltime+"','"+activitate+"','"+calorii+"')"
        );

        if (varsta == null && "".equals(varsta)) {
            String message = "Va rugam completati cu atentie TOATE campurile!";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/inregistrare.jsp").forward(request, response);           
        } else {
           int i = ps.executeUpdate();

           if (i > 0) {
              request.getRequestDispatcher("/preferinte.jsp").forward(request, response);
           }
        }
        ps.close();
        con.close();         
    } catch(Exception se) {
        se.printStackTrace();
    }
}       

is not working.

Could anyone help me?

4
  • There are some errors and misconceptions in your code. What does System.out.println(request.getParameter("varsta")) prints? Some of the errors: You defined you variable as varsta and you are checking Varsta this is just the first problem. Being varsta an Integer you can't check it against "" (empty) it is an Integer. Commented Jul 17, 2016 at 16:16
  • Did you mean varsta reference instead of Varsta in you if-condition? If you did, this if-statement will never return true, since you're comparing different types of objects: Integer against String Commented Jul 17, 2016 at 16:16
  • What is request? Commented Jul 17, 2016 at 16:17
  • Was a mistake when I wrote "Varsta", is it 'varsta'. I know that is an integer and I check for String....That is the question! Commented Jul 17, 2016 at 16:20

2 Answers 2

8

Class Integer is just an wrapper on top of primitive int type. So it can either be null or store a valid integer value. There is no obvious "empty" definition for it.

If you just compare Integer against empty String, you''ll get false as a result. Always. See Integer.equals(Object o) implementation:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

First of all, you can get a NumberFormatException during parsing integer in the line:

Integer varsta = Integer.parseInt(request.getParameter("varsta"));

And you are getting it, since For input string: "" looks like a NumberFormatExpection message.

In your example you should either check whether the "varsta" attribute value is a number (assume it's a string) and then parse it, or parse it as is and catch NumberFormatException that Integer.parseInt() throws on incorrect argument.

First solution:

Integer varsta = null;
String varstaStr = request.getParameter("varsta"); // read string 'varsta' field
if (varstaStr != null && varstaStr.matches("\\d+")) { // null-check and regex check to make sure the string contains only digits
     varsta = Integer.parseInt(varstaStr);
}

Second solution:

Integer varsta = null;
String varstaStr = request.getParameter("varsta"); // read string 'varsta' field
try {
    varsta = Integer.parseInt(varsta);
} catch (NumberFormatException e) {
    // handle error
}

After this, you have one more problem in the line:

if(varsta == null && "".equals(varsta)){

The varsta reference has type Integer here, so "".equals(varsta) will always return false:

(varsta == null && "".equals(varsta)) = [assume varsta is null] =
((null) == null && "".equals(null)) = (true && false) = false

Replace

if(varsta == null && "".equals(varsta)){

with

if(varsta == null){

This should help you.

P.S. If you use Java of version 7 or higher, consider use try-with-resources to manage Connection and PreparedStatement.

Sign up to request clarification or add additional context in comments.

10 Comments

I want only to check if in the field that represent value is empty/null or not. If Yes returns me a message If no returns me another message. The problem is that 'varsta' in int but i check it as a string. I don't know how to check it like integer
@Bogdan if you need to check whether a String instance is null or empty, you can just use str != null && !"".equals(str) condition. You can also use String.isNotEmpty(String str) from Apache commong-lang3 or String.isNotBlank(String str) if you wanna exclude blank strings as well
using: if (varsta == null && "".equals(varsta) ) seems not to work. HTTP Status 500 - For input string: ""
@Bogdan what type does request.getParameter("varsta") return? Does it return String, Integer, Object or anything else? it it returns String, see my comment above. If it returns Integer, just use simple null-check: varsta != null. If it returns other object, let us know what is the type of it
@Bogdan if varsta == null holds, then "".equals(varsta) will always return false, so you statement won't be executed if varsta is null.
|
3

If you want to check if your field is empty or not than you can use that:

if (!request.getParameter("varsta").equals("")) {
    System.out.println("not empty");
} else {
    System.out.println("Empty");
}

But if you want to get the value so you should to be carful:

try {
    if (!request.getParameter("varsta").equals("")) {
        System.out.println("not empty");
        Integer varsta = new Integer(request.getParameter("varsta"));
    } else {
        System.out.println("Exmpty");
    }
} catch (NumberFormatException e) {
    System.out.println("Number is not correct");
}

what if request.getParameter("varsta") = "4558ez"? this can make a problem.

2 Comments

Catching Exception like that is rather... nasty. Better not do it even in some example code. Just catch the relevant exceptions, so NumberFormatException, and whatever request.getParameter may throw (if you really need to catch anything at all, instead of just letting exceptions to propagate higher).
using request.getParameter("varsta").equals("") not working. Error: HTTP Status 500 - For input string: ""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.