先上登录界面(html代码和css代码在我的另一篇作品)
这是我数据库里面的数据
然后在登陆界面随便输入一个账号密码:如果账号密码在数据库里面存在,则登陆成功
如果账号密码不存在于数据库中,则登陆失败
jQuery代码
<script>
$(function(){
$(".btn").on("click",function(){
$.ajax({
url:"login",
type:"get",
data:{
account:$("#account").val(),
password:$("#password").val()
},
success:function(data){
alert(data.msg)
location.href="./manage.html"
}
})
})
})
</script>
servlet代码:
package zyf;
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 db.MysqlUtil;
/**
* Servlet implementation class login
*/
@WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("json/text");
//获取数据
String account = request.getParameter("account");
String password = request.getParameter("password");
//往数据库中添加
String sql = "select count(*) from user where account= \""+account+"\" and password =\""+password+"\"";
int res = MysqlUtil.getCount(sql);
//定义反馈数据
String json = "";
if(res!=0) {
json = "{\"code\":\"1\",\"msg\":\"亲爱的用户,恭喜您登录成功\"}";
}else {
json = "{\"code\":\"0\",\"msg\":\"登录失败呢,重新检查下信息试试\"}";
}
//给前端响应数据
response.getWriter().write(json);
}
/**
* @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);
}
}
数据库中查询数量的代码:
/*查询数量*/
public static int getCount(String sql) {
int sum = 0;
DBConnection db = new DBConnection();
try {
Statement stmt = (Statement) db.conn.createStatement();
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
while (rs.next()) {
sum += rs.getInt(1);
}
rs.close();
db.close();
} catch (Exception e) {
// TODO: handle exception
}
return sum;
}