我的servlet中有以下代码段。在这里,出于某种原因,我无法在创建一个会话后为同一个用户保持会话。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String userName = request.getParameter("userName");
HttpSession session = request.getSession();
if (userName != "" && userName != null) {
session.setAttribute("savedUserName", userName);
}
writer.println("Request parameter has user name as : " + userName + "<br />");
writer.println("Request session has user name as : " + (String) session.getAttribute("savedUserName") + "<br />");
}
答案 0 :(得分:1)
你在什么基础上暗示会话不起作用?可能不起作用的唯一方案是,当您没有提供userName
时,它将是null
并且永远不会创建会话,因为您的下面的代码正在以错误的顺序测试条件并且相等检查应使用equals()而不是!=
if (userName != "" && userName != null) {
session.setAttribute("savedUserName", userName);
}
应该改为
if (userName != null && !userName.equals("")) {
session.setAttribute("savedUserName", userName);
}