网站登录界面的随机验证码,记住密码,验证密码等模块(手机网站)利用Ajax ,Json,Session ,Cookie,Jquery ,Servlet

8 篇文章 0 订阅
3 篇文章 0 订阅

首先是设计网页的登录界面,

按照手机网站的大小做的,

如果想查看效果,运行在浏览器上之后按F12进入开发者模式,然后选择左上角的切换按钮,切换到手机状态

这里写图片描述

先上图该登录界面实现了记住密码的功能
这里写图片描述

这是初始的界面

输入密码两次错误之后弹出验证码区域,需要验证码才能提交数据

这里写图片描述

首先是html的代码

如果要使用需要把js css jquery 都是自定义的,你们要是导入需要改一下路径

link是css代码,剩下的是js代码,路径需要改成自己电脑上的

<link rel="stylesheet" type="text/css" href="../css_data/mobile/mobilelogin.css">
    <script src="../js/jquery-3.3.1.min.js"></script>
    <script src="../js/mobile/myCookie.js"></script>
    <script src="../js/mobile/mobileLogin.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link rel="stylesheet" type="text/css" href="../css_data/mobile/mobilelogin.css">
    <script src="../js/jquery-3.3.1.min.js"></script>
    <script src="../js/mobile/myCookie.js"></script>
    <script src="../js/mobile/mobileLogin.js"></script>
</head>
<body>
<div class="title_div">
    <div>
        <a class="back" href="mobileIndex.html"><</a>
        <p>帮帮堂登录</p>
    </div>
</div>
<div class="line"></div>
<div class="LoginMaxDiv">
    <div class="logo_div">
        <img class="imageLogo" src="../images/logo.png">
    </div>
    <div class="input_div">
        <input class="text" id="name" type="text" placeholder="用户名">
        <input class="text" id="pwd" type="password" placeholder="密码">
        <div class="myBoxDiv">
            <input class="myCheckBox" type="checkbox">
            <a class="check_text">记住密码</a>
        </div>
        <a class="input_wrong" id="input_wrong"></a>
        <div class="identifyCode">
            <input class="text" id="identifyInput" type="text" placeholder="请输入验证码">
            <img class="identifyImage" id="identifyImage" alt="验证码" src="/ImageServlet">
            <a id="cantSee">看不清</a>
        </div>
        <button class="btn">登录</button>
        <div class="label">
            <a class="label" href="mobileForget.html">忘记密码</a>
            <a class="label" href="mobileCreat.html">注册新账号</a>
        </div>
    </div>
</div>
</body>
</html>
以下是css的代码,前端就学了4、5天,做的都是一些基础的样式设计
body {
    width: 100%;
    margin: 0;
    padding: 0;
    background-color: #b5d4f6;
}

.LoginMaxDiv {
    width: 100%;
}

/*标题*/
.title_div {
    width: 100%;
    display: flex;
}

.title_div div {
    width: 100%;
    display: flex;
}

.title_div a {
    width: 10%;
    font-size: 5em;
    color: #9d9d9d;
    padding: 4% 2% 2% 2%;
    text-align: center;
    text-decoration: none;
}

.title_div a:active {
    color: #0f0f0f;
}

.title_div p {
    width: 80%;
    font-size: 3em;
    text-align: center;
    font-family: 楷体, serif;
}

/*横线*/
.line {
    width: 100%;
    height: 1px;
    background-color: #9d9d9d;
}

/*图标*/
.logo_div {
    width: 80%;
    margin: 20% 0 0 10%;
    text-align: center;
}

img.imageLogo {
    width: 100%;
}

/*输入区域*/
.input_div {
    width: 100%;
}

/*输入框*/
.LoginMaxDiv form {
    width: 100%;
    display: block;
}

input.text {
    width: 73%;
    display: block;
    opacity: 0.8;
    font-size: 3em;
    padding: 0.7em;
    color: #000000;
    margin: 2% 0 0 10%;
    border-radius: 10px;
    font-family: 楷体, serif;
    background-color: #bed8df;
}

/*checkbox*/
.myBoxDiv {
    width: 100%;
    font-size: 2.5em;
    font-family: 楷体, serif;
    margin-top: 5%;
}

input.myCheckBox {
    zoom: 400%;
    margin-left: 10%;
}

a.check_text {
    font-size: 1.2em;
}

/*错误警告*/
a.input_wrong {
    font-size: 2em;
    display: none;
    color: #fa2b15;
    margin: 4% 0 0 13%;
}

/*验证码区域*/
.identifyCode{
    width: 100%;
    display: none;
}

.identifyCode input{
    width: 30%;
}
/*图片*/
img.identifyImage{
    width: 22%;
    height: 15%;
    margin: 2em 0 0 2em;
}
/*看不清*/
.identifyCode a{
    font-size: 2.4em;
    margin: 1.7em 0 0 1em;
}
.identifyCode a:active{
    color:#1d9ef5;
}

/*登陆按钮*/
button.btn {
    width: 80%;
    font-size: 3em;
    color: #f8eef6;
    text-align: center;
    padding: 3% 0 3% 0;
    margin: 4% 0 0 10%;
    border-radius: 15px;
    display: block;
    font-family: 楷体, serif;
    background-color: #1d9ef5;
}

button.btn:active {
    background-color: #1bc4f3;
}

/*忘记密码和前往注册*/
div.label {
    width: 80%;
    margin: 5% 0 0 10%;
    display: flex;
    justify-content: space-between;
}

a.label {
    color: #373eab;
    font-size: 2.4em;
    font-family: 楷体, serif;
    text-decoration: none;
}

a.label:active {
    color: #4e56ee;
}
下面是自己定义的操作cookie几个方法,cookie主要是用于记住密码操作的

主要是利用ajax 提交json格式的数据给服务端
利用cookie记住密码

//设置cookie
function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
//获取cookie
function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        var c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!==-1)
        {
            c_start=c_start + c_name.length+1;
            var c_end=document.cookie.indexOf(";",c_start);
            if (c_end===-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
//清除cookie
function clearCookie(name) {
    setCookie(name, "", -1);
}
下面是js的代码,用于一些简单的判断以及和服务端的交互
/**
 * 文档就绪事件,防止在文档加载之前就运行jQuery代码
 * */
$(document).ready(function () {
    //进入先判断有没有记住密码和验证码
    checkRemember();

    function checkRemember() {
        $("#name").val(getCookie("name"));
        $("#pwd").val(getCookie("pwd"));
        if (getCookie("check") === "true") {
            $("input.myCheckBox").attr("checked", true);
        }
        if(getCookie("login")>0){
            $(".identifyCode").css("display", "flex");
        }

    }

//判断登陆是否成功

    $("button.btn").click(function () {
        var name = $("#name").val();
        var pwd = $("#pwd").val();
        var identifyInput = $("#identifyInput").val();
        var input_wrong = $("#input_wrong");
        if (name == null || name === "") {
            input_wrong.html("用户名不能为空");//错误警告
            input_wrong.css("display", "block");
        } else if (pwd == null || pwd === "") {
            input_wrong.html("密码不能为空");
            input_wrong.css("display", "block");
        } else if(getCookie("login").length>1&&(identifyInput == null || identifyInput === "")){
            input_wrong.html("输入验证码");
            input_wrong.css("display", "block");
        } else{
            input_wrong.css("display", "none");
            var myCheckBox = $("input.myCheckBox");
            if (myCheckBox.is(':checked')) {
                setCookie("name", name, 7);
                setCookie("pwd", pwd, 7);
                setCookie("check", "true", 7);//记录复选框选中
            } else {
                clearCookie("name");
                clearCookie("pwd");
                clearCookie("check");
            }
            alert(document.cookie);
            succeed();//将数据传回服务端
        }
    });


    /**
     * 登录之后将数据发送到服务端
     * */

    function succeed() {
        /* $.post("/LoginServlet", function (data, status) {
             alert(data + "状态:\n" + status);
         });*/
        var inputName = $("#name").val();
        var inputPwd = $("#pwd").val();
        var identifyInput = $("#identifyInput").val();//验证码
        var personInfo = {"name": inputName, "pwd": inputPwd, "identify": identifyInput};
        var loginNum = 0;
        //提交json数据
        $.ajax({
            type: "POST",
            url: "/LoginServlet",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(personInfo),
            dataType: "json",
            success: function (message) {
                if (message.status === "error") {
                    var input_wrong = $("#input_wrong");
                    input_wrong.html("用户名或密码错误!");
                    input_wrong.css("display", "block");
                    loginNum = getCookie("login") + 1;
                    setCookie("login", loginNum);
                    if (loginNum.length > 1) {
                        $(".identifyCode").css("display", "flex");
                    } else {
                        $(".identifyCode").css("display", "none");
                    }
                } else {
                    $("#input_wrong").css("display", "none");
                    clearCookie("login");
                    window.location.href = "mobileIndex.html";
                }
            },
            error: function (message) {
                alert("提交失败" + JSON.stringify(message));
            }
        });

    }

    /**
     * 获取验证码
     *
     * 点击看不清再次获取
     * */
    $("#cantSee").click(function () {
        var time = new Date().getTime();
        //后面加一个随机数是为了防止网页从缓存中获取
        document.getElementById("identifyImage").src = "/ImageServlet?d=" + time;
    });
});
接下来就是java后端部分的操作了,

主要定义了两个servlet ,一个LoginServlet 用于登录页面的操作
ImageServlet 用于获取验证码

下面是LoginServlet 两个servlet都需要在xml文件里面配置,配置的路径就是后面ajax提交数据的url

package com.sharetime.servlet;


import com.sharetime.util.MyJsonUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录Servlet
 *
 * @Author: yd
 * @Date: 2018/6/19 11:35
 * @Version 1.0
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyJsonUtil myJsonUtil = new MyJsonUtil(request, response);
        JSONObject clientToService = myJsonUtil.getInfo();
        String name = clientToService.getString("name");//获取name的值
        String pwd = clientToService.getString("pwd");//获取pwd的值
        String getCode = clientToService.getString("identify");//获取到的验证码
        //发送给客户端json对象:serviceToClient
        //创建session
        HttpSession loginSession = request.getSession();
        loginSession.setAttribute("name", name);
        loginSession.setAttribute("pwd", pwd);
        String realCode = loginSession.getAttribute("identify").toString();//真正的验证码
        JSONObject serviceToClient = new JSONObject();
        //如果验证码为空就说明验证码区域未显示可见
        //如果需要输入验证码,前端页面会拦截为空的情况
        if (!(getCode==null||"".equals(getCode))&&!realCode.equalsIgnoreCase(getCode)) {
            serviceToClient.accumulate("status", "error");
            System.out.println(1);
        } else if ("123".equals(name) && "123456".equals(pwd)) {
            serviceToClient.accumulate("status", "success");
            serviceToClient.accumulate("name", name);
            serviceToClient.accumulate("pwd", pwd);
            serviceToClient.accumulate("age", 18);
            serviceToClient.accumulate("sex", "男");

        } else {
            serviceToClient.accumulate("status", "error");
        }
        myJsonUtil.sendInfo(serviceToClient);
    }
}
其中MyJsonUtil是我自己定义的一个对json数据操作的工具类

代码如下

package com.sharetime.util;

import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 获取、发送、处理json数据的工具类
 *
 * @version 1.0
 * @Date 2018-6-18
 */
public class MyJsonUtil {
    private HttpServletRequest request;
    private HttpServletResponse response;

    /**
     * 构造方法,用于给request ,response赋值
     *
     * @param request
     * @param response
     */
    public MyJsonUtil(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    /**
     * 读取客户端传回来得数据
     *
     * @return JSONObject对象
     */
    public JSONObject getInfo() throws IOException {
        request.setCharacterEncoding("UTF-8");
        StringBuffer getjson = new StringBuffer();
        BufferedReader reader = request.getReader();//获取请求中的数据流
        for (String line; (line = reader.readLine()) != null; ) {//用for循环能使line在用完之后就回收
            getjson.append(line);
        }
        /*String show =URLDecoder.decode(myJson.toString(),"UTF-8");//将内容中的汉字有url编码转换*/
        String json = new String(getjson);
        return JSONObject.fromObject(json);
    }

    /**
     * 发送数据给客户端
     *
     * @param serviceToClient
     */
    public void sendInfo(JSONObject serviceToClient) throws IOException {
        response.setContentType("application/json;charset=utf-8");//指定返回的格式为JSON格式
        PrintWriter writerClient = response.getWriter();
        writerClient.print(serviceToClient);
        writerClient.close();
    }

}
然后是ImageServlet
package com.sharetime.servlet;

import com.sharetime.util.IdentityCode;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 图片传输Servlet
 * @Author: yd
 * @Date: 2018/6/19 11:39
 * @Version 1.0
 */
public class ImageServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedImage image;//实例化BufferedImage
        IdentityCode identityCode = new IdentityCode();
        image = identityCode.getImage();
        HttpSession mySession = request.getSession();
        mySession.setAttribute("identify",identityCode.getText());//把图片里的text放入session中
        ImageIO.write(image,"jpg",response.getOutputStream());//向页面输出图像
    }
}
生成随机验证码的工具类
package com.sharetime.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 用于生成随机验证码的工具类
 *
 * @Author: yd
 * @Date: 2018/6/19 11:35
 * @Version 1.0
 */
public class IdentityCode {
    private int w = 80;
    private int h = 25;
    private Random r = new Random();
    // {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
    private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
    // 可选字符
    private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    // 背景色
    private Color bgColor = new Color(255, 255, 255);
    // 验证码上的文本
    private String text;

    /**
     * 生成随机颜色
     */
    private Color randomColor() {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 生成随机的字体
     */
    private Font randomFont() {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];//生成随机的字体名称
        int style = r.nextInt(4);//生成随机的样式, 0(无样式), 1(粗体), 2(斜体), 3(粗体+斜体)
        int size = r.nextInt(5) + 26; //生成随机字号, 24 ~ 28
        return new Font(fontName, style, size);
    }

    /**
     * 画干扰线
     */
    private void drawLine(BufferedImage image) {
        int num = 3;//一共画3条
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {//生成两个点的坐标,即4个值
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.BLUE); //干扰线是蓝色
            g2.drawLine(x1, y1, x2, y2);//画线
        }
    }

    /**
     * 随机生成一个字符
     */

    private char randomChar() {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }

    /**
     * 创建图片
     *
     * @return BufferedImage
     */
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
        return image;
    }

    /**
     * 调用这个方法得到验证码
     *
     * @return BufferedImage
     */
    public BufferedImage getImage() {
        BufferedImage image = createImage();//创建图片缓冲区
        Graphics2D g2 = (Graphics2D) image.getGraphics();//得到绘制环境
        StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本
        // 向图片中画4个字符
        for (int i = 0; i < 4; i++) {//循环四次,每次生成一个字符
            String s = randomChar() + "";//随机生成一个字母
            sb.append(s); //把字母添加到sb中
            float x = i * 1.0F * w / 4; //设置当前字符的x轴坐标
            g2.setFont(randomFont()); //设置随机字体
            g2.setColor(randomColor()); //设置随机颜色
            g2.drawString(s, x, h - 5); //画图
        }
        this.text = sb.toString(); //把生成的字符串赋给了this.text
        drawLine(image); //添加干扰线
        return image;
    }

    /**
     * 返回验证码图片上的文本
     *
     * @return String
     */
    public String getText() {
        return text;
    }

}
配置的xml文件
<!--登录-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.sharetime.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <!--图片验证码-->
    <servlet>
        <servlet-name>ImageServlet</servlet-name>
        <servlet-class>com.sharetime.servlet.ImageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ImageServlet</servlet-name>
        <url-pattern>/ImageServlet</url-pattern>
    </servlet-mapping>

以上就是登陆页面的全部内容,如果有不足的地方可以和我商讨

资源下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值