简体   繁体   English

Else 语句在 Servlet 中不起作用

[英]Else statement not working in Servlet

Can anyone tell me why the else statement in below code not working.谁能告诉我为什么下面代码中的 else 语句不起作用。 I am beginner in java.我是java初学者。

     try (PrintWriter out = response.getWriter()) {
        request.getRequestDispatcher("link.html").include(request, response);
        String u = null;
        Cookie cookies[] = request.getCookies();

        for (Cookie cookie : cookies) {
            if ((cookie.getName()).equals("special")) {
                String name = cookie.getValue();
                if (!name.equals(u)) {
                    out.print("<b>Welcome to Profile</b>");
                    out.print("<br>Welcome, " + name);
                } else {
                    out.print(" LogIn First ");
                    request.getRequestDispatcher("login.html").include(request, response);
                }

            }

        }

    }

Your else is not sufficient because there are two else cases.你的 else 是不够的,因为有两个 else 情况。 First, the else to if the cookie name is equal to "special" and then Second, the else to if the value of the cookie named "special" is not null.第一,else to if the cookie name is equal to "special" 然后第二,else to if the cookie name is not null. Rather than clog the code with two repetitious elses, here it would be best to set a boolean, something like as follows:与其用两个重复的 else 阻塞代码,不如在这里设置一个布尔值,如下所示:

try (PrintWriter out = response.getWriter()) 
{
    request.getRequestDispatcher("link.html").include(request, response);
    String u = null;
    Cookie cookies[] = request.getCookies();
    Boolean blnFoundSpecialCookieWithValue = false; //initialize to false
    for (Cookie cookie : cookies) 
    {
        if ((cookie.getName()).equals("special")) 
        {
            String name = cookie.getValue();
            if (!name.equals(u)) 
            {
                blnFoundSpecialCookieWithValue = true; //set boolean
                out.print("<b>Welcome to Profile</b>");
                out.print("<br>Welcome, " + name);
            }
        }
    }
    //use boolean here to minimize number of else blocks needed
    //and not have to repeat the out.print()s
    if(!blnFoundSpecialCookieWithValue)
    {
        out.print(" LogIn First ");
        request.getRequestDispatcher("login.html").include(request, response);
    }
}

在您的代码中, u等于null ,然后您获得String名称并且它等于某物,在if语句中,您检查name是否不等于u ,它将始终为 true 并且 else 不会被执行。

那是因为 u 的值为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM