初学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="#" 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是回车键
$('#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,就可以测试登陆了!