简体   繁体   中英

Scoped variables in Java. How to link two variables within one scope?

I am trying to call a variable that is stored as a session scoped variable. If I run the first if statement the scoped variable call works. When I run the else statement and only enter a name and no address (but a previously entered name with a stored address), the address matching this name isn't returned. Any help would be appreciated because I'm a bit lost with this. Thanks

@WebServlet("/Test2") // tells server under which URL to offer this servlet 
public class UserRegistration extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // set content-type header before accessing the Writer 
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        // then write the response 
        out.println("<html>" + "<head><title>Online Shopping Directory</title></head>");
        //Get the identifier of the book to display 

        out.println("<body bgcolor=\"#ffffff\">"
                + "<h2>Please enter your name:</h2>" + "<form method=\"get\">"
                + "<input type=\"text\" name=\"username\" size=\"25\">"
                + "<p></p>"
                + "<h2>Please enter your address:</h2>" + "<form method=\"get\">"
                + "<input type=\"text\" name=\"useraddress\" size=\"25\">"
                + "<p></p>"
                + "<input type=\"submit\" value=\"Submit\">"
                + "<input type=\"reset\" value=\"Reset\">"
                + "</form>");

        String name = request.getParameter("username");
        String address = request.getParameter("useraddress");
        HttpSession session = request.getSession();
        session.setAttribute("username", address);

        if ((name != null) && (name.length() > 0) && (address != null) && (address.length() > 0)) {

            out.println("The username " + name + " has been saved for "
                    + "this session. The address of this user is "
                    + (String) session.getAttribute("username"));
        } else if ((name == "username") && (address == null)) {
            out.println("The username " + name + " is already saved. The address of this user is " + (String) session.getAttribute("username"));
        }
        out.println("</body></html>");
        out.close();
    }
}

i think you should use equals rather ==

 if ((name.equals("username")) && (address.equals(""))) {
        out.println("The username " + name + " is already saved. The address of this user is " + (String) session.getAttribute("username"));
    }

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