初學jsp首先要練習登入功能,今天學習了使用servlet完成登入檢查。
效果:
在登入頁面反複輸入錯誤密碼,頁面不會重新整理。而是将表單内容通過js中的ajax送出到servlet中進行檢查,根據其傳回值确定使用者是否登入成功。
準備:
我使用的IDE是 Intellij IDEA,下面的方法在myeclipse中應該是可以的吧。
原生js寫ajax挺繁瑣的,糾結若幹秒以後,選擇用jquery架構寫。(ps:jquery架構其實就是js代碼封裝一下,用起來友善而已)
首先下載下傳jquery:https://code.jquery.com/jquery-3.3.1.min.js
将下載下傳後的檔案(字尾應該是.min.js)拷貝到自己的項目的web目錄下(我是放在了"web/template/js"目錄下)
在項目下,建立檔案 loginPage.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登入</title>
<style type="text/css">
input{
width:300px;
height:30px;
}
.bigContainer tr{
height:35px;
}
#btnLogin{
width:300px;
height: 30px;
}
</style>
</head>
<body>
<div class="bigContainer">
<div id="login-page">
<center>
<h1>歡迎登陸<%=homeName%></h1>
<form id="login" method="post">
<table>
<tr>
<td>使用者名:</td>
<td><input id="userName" type="text" name="userName" size="16"/></td>
</tr>
<tr>
<td>密碼:</td>
<td><input id="password" type="password" name="password" size="16"/></td>
</tr>
<tr>
<td></td>
<td>
<button id="btnLogin" type="button">登入</button>
<a href="#" target="_blank" rel="external nofollow" style="color: #3d444c">忘記密碼?</a>
</td>
</tr>
</table>
</form>
</center>
</div>
</div>
<script src="/template/js/jquery-3.3.1.min.js"></script>
<script language="JavaScript">
//監聽登入按鈕,執行登入
$('#btnLogin').click(function () {
check();
});
//監聽回車,執行登入按鈕
$("body").keydown(function() {
if (event.keyCode == "13") {// keyCode=13是Enter鍵
$('#btnLogin').click();
}
});
//執行登入檢查
function check() {
var userName=$("input[name='userName']").val(); //擷取input裡的值
var password=$("input[name='password']").val();
$.ajax({
type:"POST",
url:"/ServletLogin",
data:$('#login').serialize(), //直接傳表單裡的資料
// data:{
// userName:userName,
// password:password
// },
success:function (result) {
if("Yes"==result){
alert("登入成功!");
}else{
alert("使用者名或密碼錯誤");
$("#password").val(""); //将密碼input清空
$("#password").focus(); //将光标定位到密碼input
}
},
error:function (err) {
alert("系統錯誤-loginPage.jsp-ajax");
}
});
};
</script>
</body>
</html>
注意:
第37行,button标簽的type不可以是submit,應該為button!否則你每次點選登入,form表單都會送出一次,導緻頁面重新整理一次
第47行,記得引入jquery檔案
第50行,監聽按鈕,執行check函數,去驗證登入資訊
關注check函數中的$.ajax,其标點符号一定看清楚。check函數的功能就是通過ajax将表單資訊送到/ServletLogin去驗證,如果執行成功,ajax會跳到success執行,後面的函數根據Servlet的傳回值确定登入狀态。
在工程的src檔案夾下建立ServletLogin.java(在IDEA中,右擊src檔案夾,選擇new,再選擇Servlet即可)
package Servlet;
import Beans.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ServletLogin",urlPatterns = {"/ServletLogin"})
public class ServletLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
work(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.write("No get");
out.flush();
out.close();
}
private void work(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String enPassword = password; //User.encode(password); //md5加密!
String ret="No "+userName;
if(User.isLegal(userName,enPassword)){
request.getSession().setAttribute("user", new User(userName));
request.getSession().setMaxInactiveInterval(60*30);
ret="Yes"; //登入成功
}
PrintWriter out=response.getWriter();
out.write(ret);
out.flush();
out.close();
}
}
注意:
第11行,urlPatterns屬性一定要寫上,想寫什麼就寫什麼,但開頭必須是“/”,例如我的是"/ServletLogin",那麼我用ajax通路他的時候就直接通路這個屬性值(可以看看我在loginPage.jsp的第65行 url屬性),這樣寫了之後就不用配置web.xml啦(網上大部分文章使用Servlet還是配置web.xml)
第71行,User.isLegal函數是我在User.java中寫的驗證使用者名和密碼的靜态方法,當使用者合法時傳回true
DoGet和DoPost方法是自動生成的,get和post的差別這裡不細講了,執行ajax時,type屬性是哪個,調用ServletLogin時就自動進入哪個,我這裡直接把DoGet給忽略掉了,隻有DoPost才通過驗證。
測試:
寫好兩個檔案後,運作loginPage.jsp,就可以測試登陸了!