JSPでセッションを使ったログイン(2007/07/15(日) 17:13:36)

最近JSPをいじっているので、JSPメモ。

JSPの基礎と、セッション管理のサンプル。
1つのJSPファイルでログイン、ログアウト、ホーム画面を表示できる。
各画面は「sc」というパラメータで制御される。

sc 画面
なし ホーム、ログイン
login ログイン処理
logout ログアウト処理

またJSPでのセッションは、PHPと少し違っていて、session_start();などをやらなくても、勝手にセッションが生成される。なので、セッションにIDというAttribute値が存在するかどうかで、ログイン常態かを判断する。

ソース

<%@ page
  trimDirectiveWhitespaces="true"
  contentType="text/html; charset=Shift_JIS"
  import="java.util.HashMap"
%>

<%
  String sc = request.getParameter("sc");
  String id = (String)session.getAttribute("ID");

  if(sc != null){
    if(sc.equals("login")){
      HashMap<String, String> idpswd = new HashMap<String, String>();
      idpswd.put("admin", "password");
      idpswd.put("user1", "pswd1");
      idpswd.put("guest", "guest");

      String id0 = request.getParameter("id");
      String pswd0 = request.getParameter("pswd");
      if(id0 != null && pswd0 != null &&
        idpswd.get(id0) != null && idpswd.get(id0).equals(pswd0)){
        session.setAttribute("ID", id0);
      }
    }else if(sc.equals("logout")){
      session.invalidate();
    }
  }
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
  <head>
    <title>セッションログインテスト</title>
    <meta http-equiv="content-type" content="text/html;charset=shift_jis">
    <meta http-equiv="content-script-type" content="text/javascript">
    <meta http-equiv="content-style-type" content="text/css">
<%  if(sc != null){ %>
    <meta http-equiv="refresh" content="0;url=sessiontest.jsp">
<%  } %>
  </head>
  <body>
<%  if(id == null){ %>
    <h1>ログイン</h1>
    <form method="POST" action="sessiontest.jsp?sc=login">
      <table>
        <tr><td>ログインID:</td><td><input type="text" name="id"></td></tr>
        <tr><td>パスワード:</td><td><input type="password" name="pswd"></td></tr>
      </table>
      <input type="submit" value="ログイン">
    </form>
<%  }else{ %>
    <h1>ようこそ [<%= id %>]さん</h1>
    <a href="sessiontest.jsp?sc=logout">ログアウト</a>
<%  } %>
  </body>
</html>