先添加点击事件
<input type="button" id="submitt" value="立即登录" />
展示信息
<div id="showMsg" style="text-align: center"></div>
发送JSON格式数据给servlet,并接收回传信息
<script> submitt.onclick=function () { //alert(12212); $.post("/shop/login", { "username":$("#username").val(), "password":password.value }, function (data) { if (data.code==111){ $("#showMsg").html("对不起,你输入的账号或者密码错误").css("color","red"); }else{ window.location.href="/shop/home"; } }); }
验证登陆,并将结果回传给jsp
@WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*获取请求参数telephone,password*/ String telephone = req.getParameter("username"); String password = req.getParameter("password"); //System.out.println(telephone+"-----"+password); /*调用dao,验证是否匹配*/ ILoginDAO dao=new LoginDAOImpl(); Map<String ,Object> user = dao.isLogin(telephone,password); resp.setContentType("text/json;charset=UTF-8"); PrintWriter out = resp.getWriter(); Map<Object, Object> map = new HashMap<>(); if (user==null){ /**如果不正确提示电话或者密码不正确*/ map.put("code","111"); map.put("error","对不起,你输入的账号或者密码错误"); //req.setAttribute("error","对不起,你输入的账号或者密码错误"); //req.getRequestDispatcher("/views/login.jsp").forward(req,resp); }else{ /**如果正确,跳转到主页*/ /*为什么用session,从共享数据开始到关闭浏览器,共享数据都可以获取,不受请求转发和重定向的影响*/ HttpSession session = req.getSession();//获取session对象 session.setAttribute("user",user); resp.sendRedirect("/shop/home"); } String s = JSON.toJSONString(map); out.write(s); out.close(); } }