登入界面添加验证码

这篇博客展示了如何运用Ajax技术实现图形验证码的生成和登录验证过程。在Servlet中,CheckCode.java生成验证码并存储在session中,logcheck.java负责接收用户输入并验证用户名、密码和验证码的正确性。登录界面login.jsp通过Ajax异步更新验证码图像,并在用户提交时发送数据到服务器进行验证。文章内容包括Servlet和JSP的详细代码示例。
摘要由CSDN通过智能技术生成

目录

一、效果展示:

二、代码实现

1、servlet

CheckCode .java

 logcheck.java

2、jsp

login.jsp

一、效果展示:

二、代码实现

运用了Ajax的编程技术,实现浏览器和服务器异步交互的的技术,对用户请求的响应不需要刷新整个页面,只需要刷新局部页面即可。

1、servlet

CheckCode .java

主要是生成验证码,并把验证码的正确答案用session存储,在logcheck 中与客户端传来的数据进行匹配。

package servelt;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@WebServlet("/checkcode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/jpeg");
        HttpSession session =req.getSession();
        int width=60;
        int height=20;
        //设置浏览器不要缓存此图片
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","no-cache");
        resp.setDateHeader("Expires",0);
        // 创建内存图像并获得其图形上下文
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // 产生随机验证码
        // 定义验证码的字符表
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[4];
        for (int i = 0; i < 4; i++) {
            int rand = (int) (Math.random() * 36);
            rands[i] = chars.charAt(rand);
        }
        // 产生图像
        // 画背景
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // 随机产生120个干扰点
        for (int i = 0; i < 120; i++) {
            int x = (int) (Math.random() * width);
            int y = (int) (Math.random() * height);
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            g.setColor(new Color(red, green, blue));
            g.drawOval(x, y, 1, 0);
        }
        g.setColor(Color.BLACK);
        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));
        // 在不同的高度上输出验证码的不同字符
        g.drawString("" + rands[0], 1, 17);
        g.drawString("" + rands[1], 16, 15);
        g.drawString("" + rands[2], 31, 18);
        g.drawString("" + rands[3], 46, 16);
        g.dispose();
        // 将图像输出到客户端
        ServletOutputStream sos = resp.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        byte[] buffer = baos.toByteArray();
        resp.setContentLength(buffer.length);
        sos.write(buffer);
        baos.close();
        sos.close();
        // 将验证码放到 session 中
        session.setAttribute("checkCode", new String(rands));
    }
}

 logcheck.java

用来接收login.jsp传来和CheckCode .java的数据,判断用户名和密码以及验证码是否正确。(未调用数据库,只是一组固定的数据,用户名:张三,密码:123)

package servelt;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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;

@WebServlet("/logcheck")

public class logcheck extends HttpServlet {

    public logcheck() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userid = request.getParameter("userid");
        String userpwd = request.getParameter("userpwd");
        String usercheckcode = request.getParameter("checkcode");
        String info = "";
        HttpSession session = request.getSession();
        String servercheckcode = (String) session.getAttribute("checkCode");
        if (!servercheckcode.equalsIgnoreCase(usercheckcode)) {
            info = "验证码不正确,请重新输入";
        } else if ("张三".equals(userid) && "123".equals(userpwd)) {
            info = "登录成功";
        } else {
            info = "用户名或密码不正确";
        }

        request.setAttribute("info", info);
        RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
        rd.forward(request, response);
    }


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


    public void init() throws ServletException {
        // Put your code here
    }

}

2、jsp

login.jsp

<%@ page pageEncoding="UTF-8"%>
<html>
<head>
    <title>带图形验证码的登录</title>
</head>
<script>
    function refresh(){
        document.getElementById("img1").src="checkcode?a="+Math.random();
    }
</script>
<body>
<form method="post" name="form1">
    用户名
    <input type="text" name="userid" onclick="mes.innerHTML=''"
           value="${param.userid }" />
    <br />
    密码
    <input type="password" name="userpwd" value="${param.userpwd }" />
    <br />
    验证码
    <input type="text" name="checkcode" />
    <img border="0" src="checkcode" />
    <input type="submit" value="换一张"
           onclick="refresh()" />
    <br />
    <input type="submit" value="登录" onclick="form1.action='logcheck'" />
    <input type="reset" value="重置" />
    <div id="mes">
        ${info}
    </div>
</form>
</body>
</html>

 

以下是一个简单的 HTML 登录界面,包含验证码功能: ```html <!DOCTYPE html> <html> <head> <title>Login Page</title> <style> body { background-color: #f2f2f2; font-family: Arial, sans-serif; } form { background-color: #fff; padding: 20px; border-radius: 5px; box-shadow: 0px 0px 10px 0px #ccc; width: 400px; margin: 50px auto; } h2 { margin-top: 0; text-align: center; color: #333; } label { display: block; margin-bottom: 10px; color: #666; } input[type="text"], input[type="password"] { padding: 10px; border-radius: 5px; border: 1px solid #ccc; margin-bottom: 20px; width: 100%; font-size: 16px; } input[type="submit"] { background-color: #4CAF50; color: #fff; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; margin-bottom: 10px; } .code-box { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; } .code { background-color: #fff; padding: 10px; border-radius: 5px; border: 1px solid #ccc; font-size: 16px; width: 60%; } .code-img { height: 30px; cursor: pointer; } </style> </head> <body> <form> <h2>Login</h2> <label for="username">Username:</label> <input type="text" id="username" name="username"> <label for="password">Password:</label> <input type="password" id="password" name="password"> <div class="code-box"> <label for="code">Code:</label> <input type="text" id="code" name="code" class="code"> <img src="#" alt="code" class="code-img"> </div> <input type="submit" value="Login"> </form> <script> // 生成随机验证码 function generateCode() { var code = ""; var codeLength = 6; var charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < codeLength; i++) { var randomChar = Math.floor(Math.random() * charSet.length); code += charSet.charAt(randomChar); } return code; } // 更新验证码图片 function updateCode() { var code = generateCode(); var codeImg = document.querySelector(".code-img"); var codeInput = document.querySelector(".code"); codeImg.src = "https://via.placeholder.com/150x30.png?text=" + code; codeInput.value = ""; } // 初始化 updateCode(); // 点击验证码图片更新验证码 document.querySelector(".code-img").addEventListener("click", function() { updateCode(); }); </script> </body> </html> ``` 该登录界面使用了简单的 HTML 和 CSS 样式,包含用户名、密码和验证码输入框,并且通过 JavaScript 动态生成随机验证码并显示在图片上。当用户点击验证码图片时,会生成新的验证码并更新到图片上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值