我正在學習 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 的每個請求關聯的默認會話?
uj5u.com熱心網友回復:
在 Tomcat 上,會話是在需要時懶惰地建立的。基本上有幾種情況會創建會話:
- 如果您打電話
request.getSession()或request.getSession(true)總是建立會話, - 如果您根據 Tomcat 的用戶資料庫對用戶進行身份驗證,則可能會根據身份驗證方法創建會話。最值得注意的是,如果您使用表單身份驗證(請參閱本教程),則始終會建立會話,
- 除非您添加
<%page session="false"%>指令,否則 JSP 頁面會創建會話(請參閱為什么要設定 JSP 頁面 session="false" 指令?)。
瀏覽器會記住 cookie,因此存在 aJSESSIONID并不表示存在會話(它可能來自之前的測驗)。要測驗是否存在會話,請使用request.getSession(false). 例如:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final boolean establishSession = req.getParameter("withSession") != null;
try (final PrintWriter writer = resp.getWriter()) {
final String requestedSessionId = req.getRequestedSessionId();
final HttpSession possibleSession = req.getSession(establishSession);
writer.append("I requested a session with id: ")//
.append(requestedSessionId)
.append("\nI have a session with id: ")
.append(possibleSession != null ? possibleSession.getId() : null)
.println();
}
}
編輯:我添加了 JSP 頁面創建會話的情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426563.html
下一篇:由于最近的log4j漏洞,Grails3.3.2對tomcat-embed-logging-log4j-8.5.2.jar的依賴是否存在問題?
