I am working on a JSP file(don't want to use a servlet), I have a simple form, 2 labels, 2 inputs and 2 buttons, and I want to print out the submitted string on the same jsp page , the problem is that the last values submitted remain printed on the screen as I try new ones, that is why I thought of a test to check whether the button submit was clicked before we move to the display, I tried this code :
<body>
<form method='post'>
<pre>
<label>Username</label> <input type="text" name="user" required/>
<label>Password</label> <input type="password" name="pwd" required />
<br>
<input type="submit" value="confirm" name ="submit" />
<input type="reset" value="clear" />
</pre>
</form>
<br>
// test if the submit button was clicked (check if value of submit is confirm)
<% String x=request.getParameter("submit")%>
<% if (x.equals("confirm")){ %>
<% if (request.getParameter("user")!="" && request.getParameter("pwd")!=""){ %>
<center>
<h4> user is : <% out.write(request.getParameter("user")); %> </h4>
<br>
<h4> password is : <% out.write(request.getParameter("pwd")); %> </h4>
</center>
<% } else { %>
<h4> inputs r empty !! </h4>
<% } %>
<% } %>
</body>
I get an error at line :
<% if (x.equals("confirm")){ %>
any idea why ?
First of all, stop opening and closing JSP tags unnecessarily. Its sloppy and unreadable. Secondly, you're missing a semi-colon. Third, you need to check for the possibility that the parameter is null. When the form was not submitted, the parameter is null.
This is bad:
<% String x=request.getParameter("submit")%>
<% if (x.equals("confirm")){ %>
Do it like this:
<%
String x = request.getParameter("submit");
if(x!=null && x.equals("confirm"))
{
...
You could also reverse the string comparison. If you use a dot operator on a variable that is null, you get a null pointer exception. So you could use the dot operator on the string literal, and thus avoid explicitly checking for null:
<%
String x = request.getParameter("submit");
if("confirm".equals(x))
{
...
Also once you fix this, you will run into a problem with if (request.getParameter("user")!=""
. You need to use .equals()
because in Java for String ==
, !=
do not compare string contents, but compare pointer (i.e. memory address) equivalence.