【Servlet】【JSP】Servlet + JSP でログイン機能を実装する

動作仕様

 * ビジネスロジックServlet)とUI(JSP)の分離
 * ログオン状態をセッションで保持する
 * エラーがあった際は、Login画面に戻り、エラー内容を表示する

サンプル

Vews

LoginView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:useBean id="loginModel" class="com.sample.models.LoginModel" scope="session" />
<!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=windows-31j">
<title>Login</title>
</head>
<body>
<table border="0">
<form action="<%=request.getContextPath() %>/LoginController" method="post">
<tr><th>User Name:</th><td><input type="text" id="userName" name="userName"></td></tr>
<tr><th>Password:</th><td><input type="password" id="password" name="password"></td></tr>
<tr><th></th><td><input type="submit" value="Login"></td></tr>
<%
if(loginModel != null && loginModel.isValidUser() == false && loginModel.getMessage() != null) {
%>
<tr><th>Error</th><td><%=loginModel.getMessage() %></td></tr>
<%
}
%>
</form>
</table>
</body>
</html>

WelcomeView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:useBean id="loginModel" class="com.sample.models.LoginModel" scope="session" />
<!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=ISO-8859-1">
<title>Welcome page</title>
</head>
<body>
<h1>Welcome, Mr/Ms. <%=loginModel.getUserName() %>!!</h1>
</body>
</html>

Models

 * セッションに登録するObjectはSerializableであること
http://konnichiwa-dou.cocolog-nifty.com/blog/2006/06/objectserializa_dd5d.html
http://magor.air-nifty.com/never_know/2005/12/serializable_6cff.html
http://www.wakhok.ac.jp/~tomoharu/web2004/text/index_c4.html

LoginModel.java

import java.io.Serializable;

public class LoginModel implements Serializable {
   private boolean isValidUser;
   private String userName;
   private String message;

   public LoginModel() {
      this.isValidUser = false;
      this.userName = null;
      this.setMessage(null);
   }

   public boolean isValidUser() {
      return this.isValidUser;
   }

   public void setValidUser(boolean isValidUser) {
      this.isValidUser = isValidUser;
   }

   public String getUserName() {
      return this.userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }
}

LoginController

LoginController.java

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sample.models.LoginModel;

/**
 * Servlet implementation class LoginController
 */
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginController() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");

		// セッション取得
		HttpSession session = request.getSession(true);
		// 既存セッション破棄
		session.invalidate();
		// 新規セッションを開始
		HttpSession newSession = request.getSession(true);
		
		if ("admin".equals(userName) && "admin".equals(password)) {
			LoginModel loginModel = new LoginModel();
			loginModel.setValidUser(true);
			loginModel.setUserName(userName);
			
			newSession.setAttribute("loginModel", loginModel);
			
			response.sendRedirect(request.getContextPath() + "/Views/Logon/WelcomeView.jsp");
		} else {
			LoginModel loginModel = new LoginModel();
			loginModel.setValidUser(false);
			loginModel.setMessage("Login Fail...");
			
			newSession.setAttribute("loginModel", loginModel);
			
			response.sendRedirect(request.getContextPath() + "/Views/LoginView.jsp");
		}		
	}
}


関連記事

 * 実はこの実装だけではまだ不十分。続きは以下の関連記事を参照。

フィルタ機能 ~ Filter ~

http://blogs.yahoo.co.jp/dk521123/33573064.html

ページ遷移およびパラメータの受け取り ~クエリ文字列編~

http://blogs.yahoo.co.jp/dk521123/32776759.html

ページ遷移およびパラメータの受け取り ~セッション編~

http://blogs.yahoo.co.jp/dk521123/33118263.html

Servlet/JSP/useBeanタグ を使って、MVCモデル

http://blogs.yahoo.co.jp/dk521123/33118025.html

Servlet + JSP でログイン機能を実装する

http://blogs.yahoo.co.jp/dk521123/33567439.html

Servlet + JSP でログアウト機能を実装する

http://blogs.yahoo.co.jp/dk521123/33704010.html

JWebUnitServlet / JSP のためのテストツール ~

 * 今回のサンプルの単体試験を作成している
http://blogs.yahoo.co.jp/dk521123/33775213.html