基於 JSP + Servlet 的使用者登入驗證
阿新 • • 發佈:2018-11-03
綜合案例——基於 JSP + Servlet 的使用者登入驗證
【例6-1】 實現一個簡單的使用者登入驗證程式,如果使用者名稱是 abc ,密碼是 123,則顯示歡迎使用者的資訊,否則顯示“使用者名稱或密碼不正確”。
【分析】 該案例採用 JSP 頁面只完成提交資訊和驗證結果的顯示,而驗證過程由 Servlet 完成,這些元件通過 request (或 HttpServletRequest)物件實現資料共享。由提交頁面將資料傳遞給 Servlet,而 Servlet 獲取資料並實現驗證,根據驗證結果,轉向顯示驗證結果的頁面。
【設計】 根據分析,該系統需要設計3個元件以及修改 web.xml 檔案。
(1)登入表單頁面: login.jsp。
(2)處理登入請求並實現驗證的 Servlet:LoginCheckServlet.java。
(3)顯示提示的頁面: Info.jsp。
(4)修改 web.xml,配置 Servlet的資訊。
假設,元件之間共享資料的引數為 username 和 userpwd。
【實現】
(1)登入表單頁面login.jsp:
<%@ page contentType="text/html;charset=gb2312"%> <html> <head> <title>登入頁面</title> </head> <body> <form action="CheckServlet" method="post"> <table> <tr align="center"> <td>請輸入使用者名稱:<input type="text" name="username" size="20"> </td> </tr> <tr align="center"> <td>請輸入密碼: <input type="password" name="userpwd" size="20"> </td> </tr align="center"> <td><input type="submit" value="登入" /> <input type="reset" /></td> </tr> </table> </form> </body> </html>
(2)處理登入的 Servlet:LoginCheckServlet.java。
package servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginCheckServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("username"); String userPwd = request.getParameter("userpwd"); String info = ""; if(("abc".equals(userName))&&"123".equals(userPwd)){ info = "歡迎你"+userName+"!"; }else{ info = "使用者名稱或密碼不正確!"; } request.setAttribute("outputMessage", info); request.getRequestDispatcher("/Info.jsp").forward(request,response); } }
(3)顯示提示的頁面 Info.jsp:
<%@ page pageEncoding="UTF-8"%>
<html>
<head><title>顯示結果頁面</title></head>
<body>
<%=request.getAttribute("outputMessage") %>
</body>
</html>
(4)修改配置檔案,在 web.xml 中,新增LoginCheckServlet 的配置資訊:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>LoginCheckServlet</servlet-name>
<servlet-class>servlets.LoginCheckServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginCheckServlet</servlet-name>
<url-pattern>/CheckServlet</url-pattern>
</servlet-mapping>
</web-app>
(5)執行結果: