java 如何检查文本字段的空值并将其放入 if else 语句以将其重定向到错误页面?

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

How to check null values of text fields and put it in if else statements to redirect it to error page?

javanullif-statement

提问by a k

In following code there is a problem in If Else statement. Only Else part of Request dispatcher is executing even if I don't enter anything in Text Fields. Also, how to check null values of text fields inside Java?

在以下代码中,If Else 语句中存在问题。即使我没有在文本字段中输入任何内容,也只有请求调度程序的其他部分正在执行。另外,如何检查 Java 中文本字段的空值?

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
                                           throws ServletException, IOException {

String Email    = request.getParameter("email");
String Password = request.getParameter("password");

    if (Email == null || Password == null){             

        RequestDispatcher rd = request.getRequestDispatcher("JSP Address");
        rd.forward(request, response);

    } else {

        RequestDispatcher rd = request.getRequestDispatcher("JSP Address");
        rd.forward(request, response);

    }

}

回答by Ravi Wallau

I like to use the method StringUtils.isBlank(String)in the commons-lang (http://commons.apache.org/lang) for this type of checking. It checks if the string is null, empty, or if it contains only whitespaces.

我喜欢在 commons-lang ( http://commons.apache.org/lang) 中使用StringUtils.isBlank(String)方法进行此类检查。它检查字符串是否为空、空或是否仅包含空格。

回答by Viswanadh Kumar Reddy Vuggumud

I think the parameters become nullonly if the formdoes not send them at all.

我认为只有当表单根本不发送参数时,参数才会变为

Suppose your form is like this:

假设你的表格是这样的:

input type=text name="pass" (not password)

then the parameter you are using in request.getParameteris not present so it is null.

那么你使用的参数request.getParameter不存在所以它是null

回答by Tommi

Perhaps the values are (non-null) empty strings? Try:

也许这些值是(非空)空字符串?尝试:

   if (Email == null || Password == null || Email.equals("") || Password.equals("")){

回答by Don Roby

Likely the fields are coming in as empty strings rather than nulls, but we can't tell that for sure without seeing more code.

很可能这些字段是作为空字符串而不是空值出现的,但如果没有看到更多代码,我们就无法确定。

Running it in a debugger or adding debug prints would clarify.

在调试器中运行它或添加调试打印会澄清。