检查请求参数是否等于 Java 中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4636381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:19:27  来源:igfitidea点击:

Check if the request parameter equals a string in Java

javarequestquery-string

提问by steve

I want to do this in java

我想在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?

对于 Java 新手,为什么上面的代码不起作用,上面我想做的最好的方法是什么?

回答by BalusC

Since Stringis 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.

由于String是一个对象,而不是一个原始对象,==因此只能通过引用来比较它们,而不是通过对象的内部表示。你需要比较它们equals()

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 NullPointerExceptionon for example request.getParameter("page").equals("page1")when the parameter returns null)

(注意,这种风格是为了防止潜在NullPointerException的,例如request.getParameter("page").equals("page1")当参数返回时null

Related questions:

相关问题:



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

与问题无关,JSP 不是这项工作的最佳场所。考虑一个Servlet

回答by 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.

== 比较对象引用以查看它们是否相等,而 .equals 检查这些对象引用的值是否相等。