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

0

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

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

When I compare the email string with another string containing the same text it makes me false. Why does this happen? how can I solve it?

I'm doing the normal comparison

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

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

    
asked by anonymous 12.03.2018 / 21:18

1 answer

1

When you use ==, you test whether 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 get the desired value, but since 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 make the comparison s1 == s2, the value would be true because they are pointing to the same object.

    
12.03.2018 / 22:35