Java Cookies:Cookiesを使用してJavaサーブレットセッション管理を行う方法
公開: 2020-08-19
Webページには記憶がありません。 ページ間を移動するユーザーは、Webサイトによって完全に新しい訪問者として扱われます。 セッションCookieを使用すると、アクセスしているWebサイトでページからページへの移動を追跡できるため、サイトに既に提供しているのと同じ情報を求められることはありません。
Cookieを使用すると、新しい領域にアクセスするたびに認証や再処理を行うことなく、サイトの多くのページをすばやく簡単に移動できます。
ただし、Java Webアプリケーションでは、クライアントが誰であるかを認識し、それに応じて要求を処理する必要がある場合があります。
たとえば、ショッピングカートアプリケーションは、誰がアイテムを追加するリクエストを送信しているか、どのカートにアイテムを追加する必要があるか、または誰がチェックアウトリクエストを送信しているかを認識して、正しいクライアントに金額を請求できるようにする必要があります。
セッションはクライアントとサーバー間の会話状態であり、クライアントとサーバー間の複数の要求と応答で構成できます。 HTTPとWebサーバーはどちらもステートレスであるため、セッションを維持する唯一の方法は、セッションに関するいくつかの一意の情報(セッションID)がすべての要求と応答でサーバーとクライアントの間で渡される場合です。

それでは、Cookieを使用したJavaサーブレットセッション管理について説明するEclipseでシンプルな動的Webプロジェクトを作成しましょう。
手順は次のとおりです。
- 動的Webプロジェクトの作成:
CrunchifySessionManagementByCookie
-
crunchify-login.html
:アプリケーションのウェルカムページを作成します CrunchifyLoginServlet.java
–ログインリクエストを処理しますCrunchifyLogoutServlet.java
–ログアウトリクエストを処理しますweb.xml
–デプロイメント記述子ファイル(web.xmlが表示されない場合は、このチュートリアルに従ってください)-
CrunchifyLoginSuccessful.jsp
–成功リクエストはLoginSuccess.jsp
に転送され、このCookieはセッションを追跡するためにそこで使用されます。 また、Cookieのタイムアウトが60分に設定されていることにも注意してください。

別の人は読む必要があります:
- Spring MVCの例/チュートリアル:Hello World – Spring MVC 3.2.1
- Spring MVCで3秒ごとにSparklineグラフを更新する方法(リアルタイム更新)
1. crunchify-login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
< ! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta http - equiv = "Content-Type" content = "text/html; charset=US-ASCII" > < title > Crunchify Login Form - Session Management by Cookies < / title > <style type ="text/css"> body { background-image : url ( 'https://cdn.crunchify.com/bg.png' ) ; } </style> < / head > < body > < div align = "center" > < br > < br > < form action = "CrunchifyLoginServlet" method = "post" > Enter Your Username : < input type = "text" name = "crunchifyUser" > < br > Enter Your Password : < input type = "password" name = "crunchifyPassword" > < br > < br > < br > < input type = "submit" value = "Login" > < / form > < / div > < / body > < / html > |
2. CrunchifyLoginServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package com . crunchify . tutorials ; import java . io . IOException ; import java . io . PrintWriter ; import javax . servlet . RequestDispatcher ; import javax . servlet . ServletException ; 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 ; /* * Author: Crunchify.com * */ /** * Servlet implementation class LoginServlet */ @WebServlet ( "/CrunchifyLoginServlet" ) public class CrunchifyLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L ; private final String userID = "CrunchifyUser" ; private final String password = "CrunchifyPassword" ; protected void doPost ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { // get request parameters for userID and password String crunchifyUser = request . getParameter ( "crunchifyUser" ) ; String pwd = request . getParameter ( "crunchifyPassword" ) ; if ( userID . equals ( crunchifyUser ) && password.equals(pwd)) { Cookie crunchifyCookie = new Cookie("crunchifyUser", crunchifyUser); // setting cookie to expiry in 60 mins crunchifyCookie . setMaxAge ( 60 * 60 ) ; response . addCookie ( crunchifyCookie ) ; response . sendRedirect ( "CrunchifyLoginSuccess.jsp" ) ; } else { RequestDispatcher rd = getServletContext ( ) . getRequestDispatcher ( "/crunchify-login.html" ) ; PrintWriter out = response . getWriter ( ) ; out . println ( "<font color=red>Please make sure you enter UserID/Pass as \"CrunchifyUser : CrunchifyPassword\".</font>\n" ) ; rd . include ( request , response ) ; } } } |
3. CrunchifyLogoutServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com . crunchify . tutorials ; import java . io . IOException ; import javax . servlet . ServletException ; 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 ; /* * Author: Crunchify.com * */ /** * Servlet implementation class LogoutServlet */ @WebServlet ( "/CrunchifyLogoutServlet" ) public class CrunchifyLogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L ; protected void doPost ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response . setContentType ( "text/html" ) ; Cookie loginCookie = null ; Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies ! = null ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( "crunchifyUser" ) ) { loginCookie = cookie ; break ; } } } if ( loginCookie ! = null ) { loginCookie . setMaxAge ( 0 ) ; response . addCookie ( loginCookie ) ; } response . sendRedirect ( "crunchify-login.html" ) ; } } |
4. web.xml
1 2 3 4 5 6 7 8 9 10 |
<? xml version = "1.0" encoding = "UTF-8" ?> < web - app xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi : schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < display - name > CrunchifySessionManagementByCookie < / display - name > < welcome - file - list > < welcome - file > crunchify - login . html < / welcome - file > < / welcome - file - list > < / web - app > |
5. CrunchifyLoginSuccessful.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<% @ page language = "java" contentType = "text/html; charset=US-ASCII" pageEncoding = "US-ASCII" %> < ! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta http - equiv = "Content-Type" content = "text/html; charset=US-ASCII" > < title > Crunchify - Login Successful - Session management by Cookies < / title > <style type ="text/css"> body { background-image : url ( 'https://cdn.crunchify.com/bg.png' ) ; } </style> < / head > < body > < div align = "center" > < br > < br > <% String userName = null ; Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies ! = null ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( "crunchifyUser" ) ) userName = cookie . getValue ( ) ; } } if ( userName == null ) response . sendRedirect ( "crunchify-login.html" ) ; %> < h3 > Hi <%= userName %> , Login successful . < / h3 > < br > < form action = "CrunchifyLogoutServlet" method = "post" > < input type = "submit" value = "Logout" > < / form > < / div > < / body > < / html > |
次に、この例を実行してみましょう。
-
CrunchifySessionManagementByCookie
プロジェクトをTomcatにデプロイし、Tomcatを実行します。

- ブラウザのURLをhttp:// localhost:8080 / CrunchifySessionManagementByCookie /crunchify-login.htmlにポイントします

- 成功ページ

- ログインページの失敗

次に、Cookieが正しく設定されているかどうかを確認する方法。

Cookie Manager Extension
をダウンロードしてみると、以下のようにブラウザにCookie
が表示されます。

上記のサーブレットCookie管理コードで問題が発生した場合はお知らせください。