1. 程式人生 > >基於JSP+Servlet的使用者登入驗證

基於JSP+Servlet的使用者登入驗證

        要求:實現一個簡單的使用者登驗證程式.如果使用者名稱和密碼都正確,顯示歡迎資訊.  否則顯示“登入失敗”

       分析:採用jsp頁面完成提交資訊和驗證結果的顯示,而驗證過程由Servlet來完成,由於沒涉及到資料庫技術,所以使用者名稱和密碼都是事先確定好的,這些元件通過request物件實現物件共享.

       設計

1.登入表單頁面 login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
   <head><title>登入頁面</title></head>
   <body>
       <form action="loginCheck" method="post">
            請輸入使用者名稱:<input type="text" name="username"/><br/>
            請輸入密碼:<input type="password" name="userpassword"/><br/>
           <input type="submit" name="登入">
       </form>
   </body>
</html>

 2.處理驗證過程的Servlet   LoginCheckServlet.java

package my;
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 {

		response.setContentType("text/html");
		
		String userName=request.getParameter("username");
		String userPassword=request.getParameter("userpassword");
		String info="";
		if(("wcz".equals(userName))&& "1234".equals(userPassword))
		{
			info="歡迎你"+userName+"!";
			request.setAttribute("info1", info);
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/fail.jsp").forward(request, response);
		}
		
		
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">
</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">3.登入成功的頁面 </span><span style="font-family: Calibri; background-color: rgb(255, 255, 255);">success.jsp</span>
<span style="font-family: Calibri; background-color: rgb(255, 255, 255);">
</span>
<span style="font-family: Calibri; background-color: rgb(255, 255, 255);"></span><pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
    <head><title>登入成功頁面</title></head>
    <body>
        <p align="center">登入成功<%=request.getAttribute("info1") %>
        </p>
    </body>
</html>

 4.登入失敗的頁面 faile.jsp
<span style="font-family: Calibri; background-color: rgb(255, 255, 255);"></span><pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
    <head><title>登入失敗頁面</title></head>
    <body>
        <p align="center">登入失敗.<a href= "login.jsp">請重新登入</a>
            
        </p>
    </body>
</html>


5.web.xml檔案的配置

<servlet-mapping>
    <servlet-name>LoginCheckServlet</servlet-name>
    <url-pattern>/loginCheck</url-pattern>   此處要換成<span style="font-family: Calibri;">/loginCheck  與login.jsp中相對應.</span>
  </servlet-mapping>	

下面是對部分結果的截圖: