网页登入验证码的实现(java&html)

时间:2022-01-04 21:10:28

前端界面实现(由于验证码是动态获取所以用jsp格式)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<base href="/Mvcpro/"/>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
    <body>
     <span>${msg}</span>
       <form action="emp/login" method="POST">
       <fieldset>
       <legend>请登录!</legend>
                   用户名:<input type="text" name="username" placehodler="输入用户名"><br><br>&nbsp;&nbsp;&nbsp;码: <input type="password" name="pwd" placehodler="输入密码"><br><br>
       <img alt="图片不存在" src="imgCode" height="40px"><a href="javascript:void">&nbsp;&nbsp;&nbsp;看不清,换一张!</a><br><br>
       验证码:<input type="text" name="code">
       <br><br>
       <input type="submit" value="提交">
       <input type="reset" value="重置">
        </fieldset>
       </form>
       <script type="text/javascript">
       $(function(){
       $("form a").click(function(){//为a标签绑定了一个单机事件
           $("form img").attr("src","imgCode?ran="+new Date().getTime());
       })
       })
       </script>
    </body>
</html>

用于验证码图片所编写的工具类

package com.sxt.mvcpro.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
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;
@WebServlet("/imgCode")
public class RandomCode extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static int WIDTH = 102;//定义验证图片的宽度
    private static int HEIGHT = 50;//定义验证图片的高度
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        response.setContentType("image/jpeg");
        ServletOutputStream sos = response.getOutputStream();
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        char[] rands = generateCheckCode();
        drawBackground(g);
        drawRands(g, rands);
        g.dispose();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", bos);
        byte[] buf = bos.toByteArray();
        response.setContentLength(buf.length);
        sos.write(buf);  //锟斤拷锟斤拷锟缴碉拷锟斤拷证锟斤拷图片写锟斤拷页锟斤拷
        bos.close();
        sos.close();
        //锟斤拷锟斤拷锟缴碉拷锟斤拷证锟诫保锟芥到session
        session.setAttribute("rand", new String(rands));
    }
    private void drawBackground(Graphics g) {
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        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);
        }
    }

    private void drawRands(Graphics g, char[] rands) {
        // g.setColor(Color.BLUE);
        Random random = new Random();
        int red = random.nextInt(110);
        int green = random.nextInt(50);
        int blue = random.nextInt(50);
        g.setColor(new Color(red, green, blue));
        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 30));
        g.drawString("" + rands[0], 5, 35);
        g.drawString("" + rands[1], 25, 34);
        g.drawString("" + rands[2], 45, 36);
        g.drawString("" + rands[3], 65, 33);
    }

    private char[] generateCheckCode() {
        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);
        }
        return rands;
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

servlet层代码编写

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username=req.getParameter("username");
    String pwd=req.getParameter("pwd");
    String ranCode=req.getParameter("code");
    //先判断验证码是否正确
    if (ranCode.equalsIgnoreCase((String)req.getSession().getAttribute("rand"))) {
        if ("smith".equals(username)&&"1234".equals(pwd)) {
            req.getSession().setAttribute("name", username);
            //跳转到首页
            resp.sendRedirect("/Mvcpro/pages/welcome.jsp");
        }else {
            req.setAttribute("msg", "用户名密码不正确!");
            req.getRequestDispatcher("/pages/login.jsp").forward(req, resp);
        }
    }
}
@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

总的来说借助所编写的工具类控制层的代码相对变得比较简洁,可塑性强,在工具类花的时间会较多,可以直接调用,后期与其他页面相结合也较为方便。