基於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>

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








注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com