简体   繁体   中英

What is the difference between null and “”

I am currently trying to understand the jsp codes of another guy but I am having trouble with the following codes:

    if( request.getParameter("username")!=null &&
        !request.getParameter("username").equals(""))

The username is the field a user fills on an HTML form. The codes after these codes saves the data the user fills in into strings which will be later used for other purposes.

My question is what is the purpose of the !request.getParameter("username").equals("") code part in the above?

Has request.getParameter("username")!=null part of the code not already tested whether the user enters information into the input field of the HTML form or not?

Regards

If you reveive a request like

http://.../yourservlet

then the parameter value will be null, since no parameter named username is passed at all.

If you reveive a request like

http://.../yourservlet?username=

then the parameter value will be the empty string, since the parameter is passed, but its value is the empty string.

What you'll receive depends on the HTML, and on what the user actually does (he could type the URL manually in the address bar, for example). The code makes sure both cases are handled in the same way. Let's imagine some JavaScript in the page disabled the input field or removes it from the DOM when some checkbox is checked. In that case, the parameter won't be sent at all.

Has request.getParameter("username")!=null part of the code not already tested whether the user enters information into the input field of the HTML form or not?

No. A text input in a HTML form will always send a value. If nothing has been typed into it, then that value will be "" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM