1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

String compare with Form field

Discussion in 'JSP' started by ninadg, Mar 11, 2009.

  1. ninadg

    ninadg New Member

    Joined:
    Mar 11, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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:


    Code: java
    Code:
    <%
    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
     
  2. ninadg

    ninadg New Member

    Joined:
    Mar 11, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Ok, posting the code once again for increased legibility:

    Code: java
    Code:
    <%
    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>
    
    
     
    Last edited by a moderator: Mar 11, 2009

Share This Page