我读到为了在 servlet 中持久化会话,cookie 会以 JSESSIONID 的名称保存在客户端。
我也检查了它,我找到了localhost的 cookie,名称为JSESSIONID,带有一些随机字符串值。
因此,我尝试通过在 servlet 中创建 JSESSIONID cookie 来手动创建会话,但是当我尝试获取会话时,它无法正常工作。
这里发生了什么?
除了 cookie(JSESSIONID) 之外,还有其他东西可以存储在某个地方用于创建会话吗?
如果不是,为什么我无法参加会议?
请帮忙。
我用来创建 cookie 和获取会话的代码
package sessionHandling;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/sessionhandling")
public class SessionHandling extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
out.print("Hello Mr.! How are you?");
HttpSession session = request.getSession(false);
if(session != null){
out.println("You are logged in.");
out.println("session found with "+session.getId());
out.println("session found with "+session.getLastAccessedTime());
}else{
//session = request.getSession(true);
Cookie JSESSIONID = new Cookie("JSESSIONID", "12345");
JSESSIONID.setMaxAge(-1);
response.addCookie(JSESSIONID);
System.out.println("Cookie Created");
out.print("You are not logged in");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
您不负责创建或跟踪 cookie。servlet 容器会为您处理这些。
一旦你调用:
HttpSession session = request.getSession(true);
或者
HttpSession session = request.getSession();
然后 servlet 容器将开始为您维护会话(并根据需要生成 cookie)。
该HttpSession
对象在请求之间维护在服务器内存中,通常由会话 id 查找。如果您自己创建 cookie,服务器将不知道任何关于它或任何关联的 HttpSession。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句