1. 程式人生 > >正確優雅的解決使用者退出問題——JSP和Struts解決方案

正確優雅的解決使用者退出問題——JSP和Struts解決方案

Login action
Brian Pontarelli的經典文章《J2EE Security: Container Versus Custom》討論了不同的J2EE認證途徑。文章同時指出,HTTP協議和基於form的認證並未提供處理使用者退出的機制。因此,解決途徑便是引入自定義的安全實現機制。
自定義的安全認證機制普遍採用的方法是從form中獲得使用者輸入的認證資訊,然後到諸如LDAP (lightweight directory access protocol)或關係資料庫的安全域中進行認證。如果使用者提供的認證資訊是有效的,登陸動作往HttpSession物件中注入某個物件。HttpSession存在著注入的物件則表示使用者已經登陸。為了方便讀者理解,本文所附的示例只往HttpSession中寫入一個使用者名稱以表明使用者已經登陸。清單1是從loginAction.jsp頁面中節選的一段程式碼以此闡述登陸動作:

Listing 1
//...
//initialize RequestDispatcher object; set forward to home page by default
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");

//Prepare connection and statement
rs = stmt.executeQuery("select password from USER where userName = '" + userName + "'");
if
(rs.next()) { //Query only returns 1 record in the result set; only 1
  password per userName which is also the primary key
   if (rs.getString("password").equals(password)) { //If valid password
      session.setAttribute("User", userName); //Saves username string in the session object
   }
   else { //Password does not match, i.e., invalid user password
      request.setAttribute("Error", "Invalid password.");

      rd = request.getRequestDispatcher("login.jsp");
   }
} //No record in the result set, i.e., invalid username
   else
{

      request.setAttribute("Error", "Invalid user name.");
      rd = request.getRequestDispatcher("login.jsp");
   }
}

//As a controller, loginAction.jsp finally either forwards to "login.jsp" or "home.jsp"
rd.forward(request, response);