using jsp to check username and password -
hello i'm learning bit jsp , have problem code below. create 1 index.jsp file , try run eclipse or directly tomcat 6.0. error line "if (name.equals("user") && password.equals("1234"))". error java.lang.nullpointerexception. glad advise.
<?xml version="1.0" encoding="iso-8859-1"?> <!doctype html public "-//w3c//dtd xhtml 1.1//en" "http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de"> <head> <title>practice</title> </head> <body> <h2>practice</h2> <h3>please enter name , password.</h3> <form method="post" action=""> <table> <tr><td style="text-align:center">name</td> <td><input type="text" name="name" size="80" /></td> </tr> <tr><td style="text-align:center">password</td> <td><input type="text" name="password" size="80" /></td> </tr> <tr><td><input type="submit" value="send" /></td> <td><input type="reset" value="reset" /></td> </tr> </table> </form> <%-- testing name , password. --%> <% string name = request.getparameter("name"); string password = request.getparameter("password"); if (name.equals("user") && password.equals("1234")) { %> <p>your input correct!</p> <% } else if (!name.equals("")) { %> <p>please enter name!</p> <% } else if (!password.equals("")) { %> <p>please enter password!</p> <% } else if (!name.equals("") && !password.equals("")) { %> <p>please enter name , password!</p> <% } else { %> <p>your input not correct!</p> <% } %> </body> </html>
this wrong approach.
the jsp scriptlet code (the code in <% %>
things) executed whenever page been requested, regardless of if it's been requested normal request (link, bookmark, etc) or post form submit.
on initial request should display empty form, code executed , in attempt grab request parameters, gets null
. since cannot invoke methods on null
, nullpointerexception
.
the easiest workaround let execute on form submit check if request method post.
<% if (request.getmethod().equalsignorecase("post")) { // form been submitted. put code here. } %>
normally, when form submitted, input fields not filled in end empty strings, not null
. however, make code more robust, it's recommended check null
anyway.
the correct solution prevent nullpointerexception
check if reference not null
before attempting access it.
if (name != null && !name.equals("user")) { // ... }
alternatively, can wrap references since "user"
guaranteed not null
.
if (!"user".equals(name)) { // ... }
however, scriptlets (raw java code inside jsp files) bad practice. normal practice let form submit servlet
. can override dopost()
method , write code there. can learn servlets in [servlets]
tag info page here.
Comments
Post a Comment