JSPのセッションの管理

 JSPでセッションを使った簡単な例です。

<%@ page language="java" contentType="text/html;charset=EUC_JP" %>
<%@ page import="java.util.*" %>
<html>
<head><title>ログイン</title></head>
<body bgcolor="white">

<%
String customerID = request.getParameter("cust_id");
if(customerID == null){
%>
<h1>ログイン</h1>
<form action="session-login.jsp" method="post">
お客様番号:<input type="text" name="cust_id"><br>
パスワード:<input type="password" name="password"><br>
<br>
<input type="submit" value="ログイン"><br>
</form>
<%
}
else{
    if(customerID.trim().equals("")){
%>
        <h1>おおっと</h1>
        お客様番号を入力して下さい。<br>
        <a href="<%= response.encodeURL("session-login.jsp") %>">戻る</a>
<%
    }
    else{
        /* パスワードのチェックはしていません。*/
%>
        <h1>ログインしました。</h1>
        いらっしゃいませ、<%= customerID %>さん。<br>
        <br>
        <a href="<%= response.encodeURL("session-main.jsp") %>">
        メインメニュー</a>
<%
        RRRHttpSession s = request.getSession(true);
        s.setAttribute("cust_id", customerID);RRR
    }
}
%>
</body>
</html>

<%@ page language="java" contentType="text/html;charset=EUC_JP" %>
<html>
<head><title>ログイン</title></head>
<body bgcolor="white">

<%
// session-login.jspで記憶されたはずのセッション属性値
// (お客様番号)を取得
HttpSession s = request.getSession(true);
String customerID = (String) s.getAttribute("cust_id");

if(customerID == null){
    // 値がセットされていない→ログインせずに直接このページのURL
    // を打って来たのだろう?
%>
    <h1>おおっと</h1>
    ログインしていません。
    <a href="<%= response.encodeURL("session-login.jsp") %>">こちら</a>
    で初めにログインを行って下さい。
<%
}
else{
%>
    <h1>ようこそ</h1>
    <%= customerID %>さんにご利用頂けるサービスは次の通りです。<br>
	 ... (ここに書く。)
<%
}
%>
</body></html>

 あるページでセッションに情報を記憶させるには、次のように書きます。

HttpSession s = request.getSession(true);
s.setAttribute("cust_id", customerID);

セッションはHttpSessionオブジェクトが保持しています。 HttpServletRequest.getSession()の引数のtrueというのは、 セッションオブジェクトがまだ存在していなかったら新しく作るように、 という指令です。falseにすると、存在していない場合、 セッションオブジェクトを作らずにnullを返してきます。
HttpSession.setAttribute()は2つの引数をとります。 1番目は属性の名前、2番目は属性値となるオブジェクトです。

 別のページに行ってから、それらを取り出すには、次のように書きます。

HttpSession s = request.getSession(true);
String customerID = (String) s.getAttribute("cust_id");

HttpSession.getAttribute()は属性値をjava.lang.Objectで返すので、 明示的なキャストが必要です。

※ JSPにはsessionという暗黙オブジェクトもあるので、 明示的にrequest.getSessionする必要はないことも多いです。

Server Side Java Index Top

(first uploaded 2001/12/24 last updated 2003/05/03, URANO398)

楽天モバイル[UNLIMITが今なら1円] ECナビでポインと Yahoo 楽天 LINEがデータ消費ゼロで月額500円〜!


無料ホームページ 無料のクレジットカード 海外格安航空券 解約手数料0円【あしたでんき】 海外旅行保険が無料! 海外ホテル