使用技术 jQuery druid MySQL Jackson AJAX JSON

话不多说直接上代码

–JSP页面

<%--
  Created by IntelliJ IDEA.
  User: QiLin
  Date: 2020/7/28
  Time: 13:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>管理员登录</title>

    <!-- 1. 导入CSS的全局样式 -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <script src="js/jquery.min.js"></script>
    <!-- 3. 导入bootstrap的js文件 -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
    </script>
</head>
<body>
<div class="container" style="width: 400px;">
    <h3 style="text-align: center;">管理员登录</h3>
    <form action="Login" method="post">
        <div class="form-group">
            <label for="user">用户名:</label>
            <input type="text" name="user" class="form-control" id="user"   placeholder="请输入用户名"/>
        </div>

        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" name="password" class="form-control" id="password"   placeholder="请输入密码"/>
        </div>

        <div class="form-inline">
            <label for="vcode">验证码:</label>
            <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
            <a href="javascript:refreshCode()"><img src="Check_card" title="看不清点击刷新" id="vcode"/></a>
        </div>
        <hr/>
        <div class="form-group" style="text-align: center;">
            <c:if test="${not empty sessionScope.jzmmm}">
            记住密码  <input type="radio" name="cookie" checked value="true"><br>
            </c:if>
            <c:if test="${empty sessionScope.jzmmm}">
                记住密码  <input type="radio" name="cookie"  value="true"><br>
            </c:if>

            <input  class="btn btn btn-primary" type="submit" value="登录">
        </div>
    </form>
    <span id="a"></span>
    <span id="b"></span>

    <!-- 出错显示的信息框 -->
    <c:if test="${not empty sessionScope.msg1 || not empty sessionScope.msg2}">
    <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" >
            <span style="color:red;">${sessionScope.msg1}</span>
            <span style="color:crimson;">${sessionScope.msg2}</span>
        </button>
        <strong>登录失败!</strong>
    </div>
    </c:if>
</div>
</body>
</html>
<script>
    $(function () {
    //密码重置为空
        $("#user").keydown(function () {
            $("#password").val("");
        });
        //刷新验证码
        $("#vcode").click(function () {
            var s= new Date().getTime();
            this.src = "Check_card?time="+s;
        });
        //填充密码
        $("#user").blur(function () {
            $.post("GetCookie",{uname:$(this).val()},function (data) {
                    $("#password").val(JSON.parse(data));
                }
            );
        });
    });
</script>

Servlet—登录

package web;

import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author: QiLin
 * @date: 2020/8/1 14:32
 * @version: 1.0
 */
@WebServlet( "/Login")
public class Login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String user = request.getParameter("user");
        String pwd = request.getParameter("password");
        String code = request.getParameter("verifycode");
        String jzmm = request.getParameter("cookie");
        String check_card = (String) request.getSession().getAttribute("check_card");
        HttpSession session = request.getSession();
        if (code.equalsIgnoreCase(check_card)) {
            UserService userService = new UserServiceImpl();
            int login = userService.login(user, pwd);
            if (login == 1) {
                if ( jzmm !=null && jzmm.equals("true") ) {
                    String username = URLEncoder.encode(user,"UTF-8");
                    String userpwd = URLEncoder.encode(user+"pwd","UTF-8");
                    Cookie name = new Cookie(username,username);
                    Cookie pwdpwd = new Cookie(userpwd,pwd);
                    Cookie jzmmm = new Cookie("jzmm",jzmm);
                    name.setMaxAge(1*60*60);
                    pwdpwd.setMaxAge(1*60*60);
                    jzmmm.setMaxAge(1*60*60);
                    session.setAttribute("username", user);
                    session.setAttribute("password", pwd);
                    response.addCookie(name);
                    response.addCookie(pwdpwd);
                    response.addCookie(jzmmm);
                    request.setAttribute("user",user);
                    request.getRequestDispatcher("index.jsp").forward(request,response);
                } else {
                    request.setAttribute("user",user);
                    request.getRequestDispatcher("index.jsp").forward(request,response);
                }
            } else {
                session.removeAttribute("msg1");
                session.setAttribute("msg2","用户名或密码错误");
                response.sendRedirect("login.jsp");
            }
        } else {
            session.removeAttribute("msg2");
            session.setAttribute("msg1","验证码错误");
            response.sendRedirect("login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Servlet—获取密码

package web;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author: QiLin
 * @date: 2020/8/2 14:09
 * @version: 1.0
 */
@WebServlet( "/GetCookie")
public class GetCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String user = request.getParameter("uname");
        String password = "";
        ObjectMapper mapper = new ObjectMapper();
        // 获取cookie
        Cookie[] cookies = request.getCookies();
        // 如果为空,则停留在该页面
         if(cookies !=null || cookies.length >0) {
            String username = URLEncoder.encode(user,"UTF-8");
            String userpwd = URLEncoder.encode(user+"pwd","UTF-8");
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(username)) {
                    user = URLDecoder.decode(cookies[i].getValue(),"UTF-8");
                }
                if (cookies[i].getName().equals(userpwd)) {
                    password = cookies[i].getValue();
                }
            }
            request.setAttribute("pwd",password);
            String pwd = mapper.writeValueAsString(request.getAttribute("pwd"));
            response.getWriter().write(pwd);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Servlet—验证码

package web;

import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author: QiLin
 * @date: 2020/8/1 13:52
 * @version: 1.0
 */
@WebServlet( "/Check_card")
public class Check_card extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置宽高
        int width = 100;
        int height = 50;
        //创建对象,在内存验证码图
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        //美化图片
        Graphics graphics = image.getGraphics();
        //画边框
        graphics.setColor(Color.magenta);
        graphics.drawRect(0,0,width-1,height-1);
        //填充背景颜色
        graphics.setColor(Color.cyan);//画笔颜色
        graphics.drawRect(0,0,width,height);
        //定义随机抽取池
        String str = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuioplkjhgfdsazxcvbnm0123456789";
        //生成随机角标
        Random ran = new Random();
        //接收验证码
        StringBuffer sb = new StringBuffer();
        //写入验证码
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取随机字符
            char c = str.charAt(index);
            sb.append(c);
//            //生成随机x轴
//            int x = ran.nextInt(width-10) % (width-10-10+1)+10;
//            //生成随机y轴
//            int y = ran.nextInt(height-5) % (width-5-5+1)+5;
            graphics.setFont(new Font("Tahoma", Font.BOLD, 18));
            graphics.drawString(c+"",width/5*i,height/2);
        }
        //存入session
        String session_check = sb.toString();
        request.getSession().setAttribute("check_card",session_check);
        //画干扰线
        graphics.setColor(Color.green);
        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }
        //将图片画到页面
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

第一次写文章,略有不足请多多包涵。下面写下思路。
1.开始登录。
先判断用户验证码是否正确,不正确直接返回。
验证码正确后进行用户名和密码的判断,正确走下一步,不正确直接返回。
用户名密码正确后,判断是否记住密码,否就直接进入首页。
用户选择记住密码后,创建cookie并传值。cookie直接存中文容易出乱码,这里我选择将其转编码存值。创建完毕后进入首页。
2.用户第二次进入。
如记住密码,打入用户名自动获取cookie。
获取cookie的思路在代码中,这里我不再重写。
最后使用Jackson将其转JSON格式是因为我采用的是AJAX技术。
3.填充使用js技术则好
PS.
如果你现在不会AJAX或JSON 可以直接将获取的密码传回JSP而无需使用JSON。JS删除 $.post方法。
dao层并无特殊写法,我这里使用的是Druid连接池

@Override
    public int login(String name, String pwd) {
        String sql = "select count(*) from user where name =? and qq=?";
        int list = jdbcTemplate.queryForObject(sql, Integer.class, name, pwd);
        return list;
    }

采用接口方式写的,你可以取消接口直接写实现类。

感谢你观看到最后,希望有帮到你的地方。
如有不理解,可以在此回复,我会尽力解答。