2

When I submit a HTML form with blank data it's still going into else block below:

    String n=request.getParameter("uname");
    String e=request.getParameter("mail");
    String p=request.getParameter("pwd");   

    if(n==null || e==null || p==null)
    {
        // ...
    } else
    {
       // ...
    }

How can I make sure that it enters the if block?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
manojrohit
  • 17
  • 1
  • 4

3 Answers3

2

Blank submitted input values do not arrive as null. Instead, they arrive as empty string. The null only means that the input value was not submitted at all (i.e. the input field was totally absent in the form).

If you're not interested in distinguishing the presence of a specific input field in the form, then add a String#isEmpty() check to the if block.

if (n == null || n.isEmpty() || e == null || e.isEmpty() || p == null || p.isEmpty()) {
    // ...
}

You could even bake a custom utility method for this.

public static boolean isEmpty(String string) {
    return (string == null || string.isEmpty());
}
if (isEmpty(n) || isEmpty(e) || isEmpty(p)) {
    // ...
}

You can even go a refactoring step further with help of varargs.

public static boolean isOneEmpty(String... strings) {
    for (String string : strings) {
        if (string == null || string.isEmpty()) {
            return true;
        }
    }

    return false;
}
if (isOneEmpty(n, e, p)) {
    // ...
}

If you would like to cover whitespace as well, then replace string.isEmpty() over all place by string.trim().isEmpty().

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

This is because uname,mail,pwd variables are not null instead these parameters contains empty strings.

i.e. uname=""; mail=""; pwd="";

when you check whether these parameters are null or not , it results into false and your else block executes and persist the record into database.

you can create a method to check empty string(s).

 public static boolean checkEmpty(String value){
    if(!(value==null))
       return value.isEmpty();

    return true;
 }

replace your if condition with this:

if(checkEmpty(n) || checkEmpty(e) || checkEmpty(p)){

}
AsSiDe
  • 1,826
  • 2
  • 15
  • 24
1
String n=request.getParameter("uname");
if (n != null) n = n.trim();
if (n == null) n = "";

String e=request.getParameter("mail");
if(e != null) e = e.trim();
if(e == null) e = "";

String p=request.getParameter("pwd");   
if(p != null) p = p.trim();
if(p == null) p = "";

//
// only process if values for all three exist
//

if((n.length() < 1) || (e.length() < 1) || (p.length() < 1))
{
    // ...
} else
{
   // ...
}
mrflash818
  • 930
  • 13
  • 24