如何检查文本字段的空值并将其放入 if else 语句中以将其重定向到错误页面?
在下面的代码中,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);
}
}
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?
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我喜欢使用方法 StringUtils.isBlank(String) (http://commons.apache.org/lang) 用于此类检查。它检查字符串是否为 null、空或者是否仅包含空格。
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.
我认为只有当表单根本不发送参数时,参数才会变成null。
假设您的表单如下所示:
那么您在
request.getParameter
中使用的参数不存在,因此它为 null。I think the parameters become null only if the form does not send them at all.
Suppose your form is like this:
then the parameter you are using in
request.getParameter
is not present so it is null.也许这些值是(非空)空字符串?尝试:
Perhaps the values are (non-null) empty strings? Try:
这些字段可能以空字符串而不是空值的形式出现,但在没有看到更多代码的情况下我们无法确定这一点。
在调试器中运行它或添加调试打印将会澄清。
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.