java HTTP 请求中缺少元素 - Null 还是 Empty?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15028349/
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-31 18:16:37  来源:igfitidea点击:

Missing Elements in HTTP Request - Null or Empty?

javaservletsjax-rs

提问by Walls

I have a HTTP Request javax.servlet.http.HttpServletRequestthat is passing in a value to be used in some code being handled in a Java web service using JAX-RS. The POST function in Java is consuming application/json. There are two possible values to be passed into the request, call one Xand the other Y, assume both are Strings. The request requires at leastone of the two possible values to be considered 'valid'.

我有一个 HTTP 请求javax.servlet.http.HttpServletRequest,它传入一个值,用于使用 JAX-RS 在 Java Web 服务中处理的某些代码。Java 中的 POST 函数正在消耗application/json. 有两个可能的值要传递到请求中,调用一个X和另一个Y,假设两者都是字符串。该请求至少需要将两个可能值中的一个视为“有效”。

When the request comes in, if Xis provided and Yis left out of the request entirely, what is the proper way to check to see if Yis there? Would you check to see if Y.isEmpty()or Y == null? Providing Xdoesn't guarantee Yis present, and vice versa.

当请求进来时,如果X提供并且Y完全不在请求中,那么检查是否Y存在的正确方法是什么?你会检查看看是否Y.isEmpty()Y == null?提供X并不保证Y存在,反之亦然。

回答by BalusC

If a parameter is not specified at all like so,

如果一个参数根本没有像这样指定,

http://example.com/context/servlet?x=foo

then it will return null:

然后它将返回null

String x = request.getParameter("x"); // "foo"
String y = request.getParameter("y"); // null

If a parameter is specified, but does not have a value like so,

如果指定了一个参数,但没有这样的值,

http://example.com/context/servlet?x=foo&y

then it will return an empty string:

然后它将返回一个空字符串:

String x = request.getParameter("x"); // "foo"
String y = request.getParameter("y"); // ""

Makes sense, right?

有道理吧?

回答by mightyrick

Tests if a parameter is present in the request

测试请求中是否存在参数

httpServletRequest.getParameter( "Y" ) == null

The following code tests the value of the parameter if it is present

下面的代码测试参数的值是否存在

if ( httpServletRequest.getParameter( "Y" ) != null )
{
    String value = httpServletRequest.getParameter( "Y" );

    // Put your test code here.  Include a empty value check
}