Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the request parameter equals a string in 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?

like image 480
steve Avatar asked Sep 02 '26 07:09

steve


1 Answers

Since 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() instead.

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)

Related questions:

  • What is the difference between == and equals()?

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

like image 77
BalusC Avatar answered Sep 03 '26 22:09

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!