1. 本章任務
之前的登入,沒有真正的通路資料庫,在上一章節我們已經實作了真實資料庫的操作子產品,是以本章就完整的實作下登入功能。
整體流程是:
使用者通路登入頁面login.jsp
輸入使用者名、密碼後送出表單給LoginServlet
LoginServlet調用LoginService檢查登入資訊是否正确
LoginService調用UserDao通路資料庫,拼裝sql執行
登入成功後跳轉背景頁面index.jsp
2. 使用者通路登入頁面
登入頁面login.jsp顯示輸入使用者名、密碼、送出按鈕即可。
<form id="mainForm" method="post" action="/HomeworkSystem/LoginServlet">
請輸入使用者名:<input type="text" name="userName" />
<br/>
請輸入密碼:<input type="password" name="userPassword"/>
<input type="submit" value="登入"/>
</form>
1
2
3
4
5
6
7
3. LoginServlet調用LoginService驗證登入資訊
LoginServlet擷取表單輸入資訊後,調用LoginService驗證登入資訊
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 處理post請求
// 設定輸入輸出格式、編碼
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 擷取使用者在網頁輸入的使用者名和密碼
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
LoginService lc = new LoginService();
User user = null;
String tipInfo = "";// 提示内容
String page = "";// 跳轉頁面
try {
user = lc.checkLogin(userName, userPassword);
if (user == null) {
// 跳轉到錯誤提示頁面,并提示使用者不存在
tipInfo = "使用者不存在";
page = "tip.jsp";
} else {
// 登入成功,記錄使用者資訊到Session,同時跳轉管理背景頁面
request.getSession().setAttribute("loginUser", user);
page = "index.jsp";
// 設定菜單
String[][] loginMenus = Constants.roleMenuMap.get(user.getUserRole());
request.getSession().setAttribute("loginMenus", loginMenus);
}
// 根據使用者角色顯示不同内容
} catch (Exception e) {
// 跳轉到錯誤提示頁面,并提示相應錯誤資訊
tipInfo = e.getMessage();
page = "tip.jsp";
}
request.setAttribute("tipInfo", tipInfo);// 設定同手資訊
request.getRequestDispatcher("/" + page).forward(request, response);// 跳轉到page頁面
}
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
4. LoginService調用UserDao驗證使用者資訊
首先在UserDao内開發方法,通過使用者名、密碼擷取使用者資訊。
/**
* 通過使用者名、密碼擷取使用者
*/
public List<User> getUser(String name, String password) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<User> users = new ArrayList<User>();
conn = DbUtils.getConnection();
String sql = "select * from user where user_name=? and user_password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next()) {
users.add(makeOneUser(rs));
} catch (SQLException e) {
} finally {
DbUtils.releaseConnection(rs, ps, conn);
return users;
然後在LoginService内完善驗證使用者資訊的方法。
public class LoginService {
public User checkLogin(String userName, String userPassword) throws Exception {
if (userName.equals("") || userPassword.equals("")) {
// 抛出輸入資訊異常
throw new Exception("使用者名和密碼不能為空");
UserDao userDao = new UserDao();
List<User> list = userDao.getUser(userName, userPassword);
if (list.size() == 1) {// 隻有比對出一個使用者時,才是合法登入
user = list.get(0);
// 抛出資料庫異常
throw new Exception("資料庫操作異常:" + e.getMessage());
return user;// 傳回查詢結果
}
5. 測試驗證
在資料内構造幾條測試數:
INSERT INTO `homework`.`user`(`user_id`, `user_role`, `user_name`, `user_password`) VALUES (1, 'master', '趙校長', '123');
INSERT INTO `homework`.`user`(`user_id`, `user_role`, `user_name`, `user_password`) VALUES (2, 'teacher', '錢老師', '123');
INSERT INTO `homework`.`user`(`user_id`, `user_role`, `user_name`, `user_password`) VALUES (3, 'student', '孫學生', '123');
然後啟動項目,以孫學生+123登入即可。
需要注意的是,登入後左側的菜單是根據使用者角色決定的,此處使用者角色為student,是以根據Constants常量類配置,對應菜單為{ "頁面1", "page1.jsp" }, { "頁面2", "page2.jsp" }, { "不存在頁面", "xxxx.jsp" }。
public class Constants {
// 用于儲存角色及對應的菜單資訊
public static HashMap<String, String[][]> roleMenuMap = new HashMap<String, String[][]>();
static { // 使用static代碼塊對roleMenuMap進行初始化
// 注意,二位數組中的每一組表示一個菜單的資訊,又通過map建立了角色名和菜單直接的對應關系
roleMenuMap.put("student", new String[][] { { "頁面1", "page1.jsp" }, { "頁面2", "page2.jsp" }, { "不存在頁面", "xxxx.jsp" } });