简体   繁体   中英

Else statement not working in Servlet

Can anyone tell me why the else statement in below code not working. I am beginner in 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. 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. Rather than clog the code with two repetitious elses, here it would be best to set a boolean, something like as follows:

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 的值为空。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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