【发布时间】:2022-02-13 02:58:56
【问题描述】:
我正在学习使用 servlet 的会话,我在书中读到要创建一个我们需要调用的会话,如下所示。
HttpSession session = request.getSession()
这会导致 Web 容器创建一个会话 ID 并将其发送回客户端,以便客户端可以将其附加到服务器的每个后续请求中。当我在网络选项卡中的请求标头下打开 chrome 中的开发人员工具时,我确实看到了一个 cookie 标头。
Cookie: JSESSIONID=F92
以下是我在登录 servlet 中所做的操作
package shop;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class LoginServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String uid = request.getParameter("uid");
String password = request.getParameter("pwd");
if(uid.equals("admin") && password.equals("admin"))
{
HttpSession session = request.getSession();
System.out.println(session.getId());
response.sendRedirect("shopping");
}
else
response.getWriter().println("Invalid Credentials");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
this.doGet(request, response);
}
}
索引.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>shopping application</title>
</head>
<body style="background-color:cyan">
<div style="text-align:center">
<h3>Welcome to Mart</h3>
<form action="login" method="post" name="loginform">
<div style="padding:2px;">
<label for="uid">Username:</label>
<input type="text" id="uid" name="uid">
</div>
<div style="padding:2px;">
<label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd">
</div>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
我的问题是,即使我删除了getSession() 调用,我仍然会在网络选项卡中看到 cookie。是否有与 tomcat 的每个请求关联的默认会话?
【问题讨论】:
-
您是否启用了身份验证?
-
我是新手,我该如何检查?我正在使用 eclipse 中的 tomcat 来运行我的项目
-
启用身份验证后,您需要在访问页面时提供用户名和密码。
-
我确实将用户名和密码作为 index.jsp 的输入
标签: java tomcat servlets jakarta-ee