How to compare String to String received in a . jsp?

Asked

Viewed 953 times

0

I have an html page and it sends a form with POST method, I take the data like this:

String email =  request.getParameter("user");

When I compare the email string to another string containing the same text it turns me false. Because it happens ? how can I solve ?

I’m making the normal comparison

if(email == "[email protected]"){
    out.println("executou aqui");
}

In the "[email protected]" case it would be the same value as the String I picked up in the post method.

  • How are you comparing?

  • How are you making the comparison?

  • if(email == "[email protected]"){ out.println("executed here"); } This text is the same as I am sending from another page via POST

1 answer

1


When you use ==, you test if two objects are identical, look at the example:

String texto1 = "Mundo genial";
String texto2 = "Mundo genial";

In the above case if you compare with == you will receive the desired value, but as you are bringing this information, it is the same as doing this:

String s1 = new String("Mundo genial");
String s2 = new String("Mundo genial");

In this case you are comparing content and the comparison has to be done with equals,

boolean comparar = s1.equals(s2); // resultado = true
boolean comparar = s1 == s2; // resultado = false

If you want to continue with == you would have to somehow point to the same object, something like this:

String s1 = new String("Mundo genial");
String s2 = s1;

In the above case if you do the S1 == s2 comparison, the value would be true because they are pointing to the same object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.