🐕
【JavaServlet・JSP】【セッション】データ削除の例(remove・invalidate)
remove
MainServletのdoGetメソッドに以下を記述
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.setAttribute("name1", "abc");
session.setAttribute("name2", 100);
request.getRequestDispatcher("WEB-INF/jsp/session.jsp").forward(request, response);
}
SessionRemoveServletのdoGetメソッドに以下を記述
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute("name2");
RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/session.jsp");
dispatcher.forward(request, response);
}
}
WEB-INF/jspフォルダ内にsession.jspを作成し、以下を記述
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>セッションの値</h1>
name1→${name1 }
<br>
name2→${name2 }
</body>
</html>
1.MainServletを実行、ブラウザは開いたままにする
2.SessionRemoveServletを実行
name2の値が表示されていない
invalidate
SessionInvalidateServletを作成
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
//セッションがあったら
if (session != null) {
//セッションを破棄
session.invalidate();
//jspフォルダのsession.jspにフォワード(表示)
RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/session.jsp");
dispatcher.forward(request, response);
}
}
1.MainServletを実行、ブラウザは開いたままにする
2.SessionInvalidateServletを実行
name1とname2の値が表示されていない
Udemyで講座を公開中!
X(旧Twitter)
Zenn 本
Youtube
Discussion