Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request.getParameter don't have null values when they are expected

I found this issue so perplexing (but also interesting) that I'd like to ask people here for insights.

I've been teaching myself JSP and associated technologies. What I'm tring to do is to retrieve parameters from a JSP to a servlet, then use them with If( ). Here is part my coding.

if ((request.getParameter("ID_A") != null || request.getParameter("Password_A") != null) &&
    (request.getParameter("ID_B") != null || request.getParameter("Password_B") != null)) {

        errorMessage = "Information is detected for the both side";
        request.setAttribute("errorMessage", errorMessage);
        request.getRequestDispatcher("4_enter_personal_info.jsp").forward(request, response);
    } // Other conditions...

Here is part of a JSP(The previous step)

<form action="PersonalInfor_to_confirmation_servlet" method="POST">
    <h2>For an existing customer</h2>
        <p>Customer ID</p>
        <input type="text" name="ID_A" value="" />
        <p>Password</p>
        <input type="text" name="Password_A" value="" />
        <br>
    <h2>For a new customer</h2>
        <p>Set your customer ID</p>
        <input type="text" name="ID_B" value="" />
        <p>Set your password</p>
        <input type="text" name="Password_B" value="" />
    //There are other lines
</form>

I'm tring to ensure that, when a client entered information on the both sides (For an existing customer/For a new customer), there will appear the above message "Information is detected for the both side" on a JSP.

However, even if all the text boxes are blank, the error message appears. So all the request.getParameter( ) methods above don't contain null values even if I make them empty.

Even if I can come up with other algorithms, I'd like to know the reason this phenomenon happens.

Any advice will be appreciated.

like image 296
Hiroki Avatar asked Feb 12 '23 04:02

Hiroki


1 Answers

The reason why the statements in the if block runs is that because the field exists. If you don't want to run it when the textboxes are empty what you should do is include in your condition a check if the parameter contains an empty string, something like:

request.getParameter("ID_A") != null && !request.getParameter("ID_A").isEmpty()
|| request.getParameter("Password_A") && !request.getParameter("Password_A").isEmpty()
...

So all the request.getParameter( ) methods above don't contain null values even if I make them empty.

Yes. When getParamater() returns a null value, it means that it can't find a field in the form with that name. Use another method: isEmpty() to check whether a field is empty or not. Such as:

request.getParameter("noSuchField")==null //true
request.getParameter("ID_A")==null //false
request.getParameter("ID_A").isEmpty() //true
like image 69
lxcky Avatar answered May 14 '23 11:05

lxcky