I am new to JSP and am having trouble comparing string with the value in a form field submitted.

The following is the code that I am executing through Tomcat and is not giving me the desired result:

<%
String myvar = request.getParameter("var1");
boolean first = false;
if (myvar == null) {  
        first = true;
} else {
        if (myvar == "compareme") out.println("string matches"); else out.println("string MISMATCH");                  
}
%>
<html>
<head><title>String compare with Form Input</title></head>
<body>
<h2>If you enter input as "compareme", I should say "MATCH", 
else "MISMATCH"</h2>
<% if (! first) { %>
Input was <%= myvar %> <br>
<% }  %>
<hr>
<form>Please enter a string <input name=var1>
 and <input type=submit></form>
</body>
</html>

You will notice that even though the correct string "compareme" is submitted in the form, the string comparison still fails. I have tried appending .toString() and .trim() to myvar but that has not helped either.

I am obviously missing something very basic in JSP. Please help.

You are missing something basic in Java which is why you should leave JSP and practice more:

if (myvar.equals("compareme")) 
   out.println("string matches"); 
else 
   out.println("string MISMATCH");

Quite a snobby reply - people that ask this type of question are obviously new...
..thanks.

Quite a snobby reply - people that ask this type of question are obviously new...
..thanks.

If they are new then jsp pages are rather complex for them and they shouldn't even try them, especially if they don't know that equals is used for comparing Strings. Such understating is the essence of the OOP because it distinguish Object to primitive types.
Learning the basics is more important, than just giving an answer that will solve one line of error

Would you lend your 20,000$ Harley to someone that doesn't know that a bicycle has 2 wheels?

This article has been dead for over six months. Start a new discussion instead.