我正在尝试调用存储为会话范围变量的变量。如果我运行第一个if
语句,则作用域变量调用有效。当我运行else
语句并且只输入名称而没有地址(但是先前输入的名称带有存储的地址)时,不会返回与此名称匹配的地址。任何帮助将不胜感激,因为我有点迷失了。谢谢
@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();
}
}
答案 0 :(得分:0)
我认为你应该使用equals而不是==
if ((name.equals("username")) && (address.equals(""))) {
out.println("The username " + name + " is already saved. The address of this user is " + (String) session.getAttribute("username"));
}