首先先创建一个登录页面(login.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script src="js/jquery.cookie.min.js"></script>
<script src="js/login.js" defer></script>
</head>
<body>
<div>
账号:<input type='text' class='account'><br>
密码:<input type='text' class='password'><br>
<input type='button' value='登录' class='btn'>
</div>
</body>
</html>
并且在相对应的位置上创建js文件
$(".btn").on("click",function(){
var account = $(".account").val().trim()
var password = $(".password").val().trim()
$.ajax({
url:"Studentlogin",
type:"get",
data:{
account,
password,
/*captcha*/
},
success:function(value){
alert(value)
if(value=="登录成功"){
location.href="student.html"
}
}
})
})
if(value=="登录成功"){
location.href="student.html"
}判断登录成功之后跳转的页面
在创建一个相应的servlet文件(Studentlogin.java)
package qcby.servlet;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import qcby.db.MysqlUtil;
/**
* Servlet implementation class Login
*/
@WebServlet("/Studentlogin")
public class Studentlogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Studentlogin() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String account = request.getParameter("account");
String password = request.getParameter("password");
String captcha = request.getParameter("captcha");
HttpSession session = request.getSession();
String captchaVal = (String)session.getAttribute("captchaVal");
String res = "验证码错误";
if(captcha.equals(captchaVal)) {
String sql = "select count(*) from admin where account=\""+account+"\" and password=\""+password+"\"";
int num = MysqlUtil.getCount(sql);
res = "登录失败";
if(num>0) {
res = "登录成功";
//设置登录状态
session.setAttribute("account", account);
}
}
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.getWriter().write(res);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
这样就能够利用session进行登录判断了