Compruebe si el parámetro de solicitud es igual a una cadena en Java

I want to do this in java

if(request.getParameter("page") == "page1")
// page1
else if(request.getParameter("page") == "page2")
// page2

For someone new to java, why doesn't the above code work, and what is the best way to do what I want to do above?

preguntado el 08 de enero de 11 a las 21:01

2 Respuestas

Como String is an object, not a primitive, the == would only compare them by reference, not by the object's internal representation. You need to compare them by equals() en vez.

if("page1".equals(request.getParameter("page")))
// do something
else if("page2".equals(request.getParameter("page")))
// do something else

(note, this style is done so to prevent potential NullPointerException on for example request.getParameter("page").equals("page1") when the parameter returns null)

Preguntas relacionadas:


Unrelated to the problem, the JSP is not the best place for this job. Consider a Servlet.

Respondido el 20 de junio de 20 a las 12:06

Good point on the difference between the 2 styles. I never thought about it like that. - jmort253

You are using the wrong equals. Try this:

  if(request.getParameter("page") != null) {
    if(request.getParameter("page").equals("page1")) {
         // do stuff
    } else if(request.getParameter("page").equals("page2")) {
         // do other stuff
    }
  }

== compares the object references to see if they are equal, whereas .equals checks to see if the values of those object references are equal.

Respondido el 09 de enero de 11 a las 01:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.