Hello i’m learning a bit JSP and i have a problem with the code below. I create one index.jsp file and try to run it with eclipse or directly with Tomcat 6.0. I always get a error for the line “if (name.equals(“user”) && password.equals(“1234”))“. The error is
java.lang.NullPointerException. I would be glad for any 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 your name and the 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 and password. --%>
<% String name = request.getParameter("name");
String password = request.getParameter("password");
if (name.equals("user") && password.equals("1234"))
{
%>
<p>Your Input is correct!</p>
<% }
else if (!name.equals(""))
{
%>
<p>Please enter your name!</p>
<% }
else if (!password.equals(""))
{
%>
<p>Please enter your password!</p>
<% }
else if (!name.equals("") && !password.equals(""))
{
%>
<p>Please enter your name and your password!</p>
<% }
else
{
%>
<p>Your input is not correct!</p>
<% }
%>
</body>
</html>
This is the wrong approach.
The JSP scriptlet code (the code in
<% %>things) will always be executed immediately whenever the page is been requested, regardless of if it’s been requested by a normal GET request (link, bookmark, etc) or a POST form submit.On the initial request which should display the empty form, the code get executed as well and in an attempt to grab the request parameters, all it gets is
null. Since you cannot invoke any methods onnull, you will get aNullPointerException.The easiest workaround to let it execute only on a form submit is to check if the request method is POST.
Normally, when the form is submitted, the input fields which are not filled in will end up as empty strings, not as
null. However, to make the code more robust, it’s recommended to check fornullanyway.The correct solution to prevent
NullPointerExceptionis to check if the reference is notnullbefore attempting to access it.Alternatively, you can also wrap the references since
"user"is guaranteed notnull.However, scriptlets (raw Java code inside JSP files) are a bad practice. The normal practice is to let the form submit to a
Servlet. You can then just override thedoPost()method and write code there. You can learn anything about servlets in the[servlets]tag info page here.