Java–验证码登录

导读:本篇文章讲解 Java–验证码登录,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

步骤:1、封装VerificationCode类;2、实例化;3、调用getText()方法获取验证码并保存到session;4、调用getImage()方法获得Image对象并输出到浏览器。

Verification类

package com.qfedu.demo.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class VerificationCode {

    private int width = 100;// 生成验证码图片的宽度
    private int height = 30;// 生成验证码图片的高度
    //生成的验证码的字体,每次生成的时候从四个字体中随机选择一个
    private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
    private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
    private Random random = new Random();
    //验证码的原文字
    private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private String text;// 记录随机字符串

    /**
     * 获取一个随意颜色
     *
     * @return
     */
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 获取一个随机字体
     *
     * @return
     */
    private Font randomFont() {
        //获取一个随机的字体
        String name = fontNames[random.nextInt(fontNames.length)];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(name, style, size);
    }

    /**
     * 获取一个随机字符
     *
     * @return
     */
    private char randomChar() {
        return codes.charAt(random.nextInt(codes.length()));
    }

    /**
     * 创建一个空白的BufferedImage对象
     *
     * @return
     */
    private BufferedImage createImage() {
        //创建图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取一个画笔
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        //设置画笔的颜色
        g2.setColor(bgColor);// 设置验证码图片的背景颜色
        //填充图片的背景
        g2.fillRect(0, 0, width, height);
        return image;
    }

    /**
     * 绘制图片的方法
     * @return
     */
    public BufferedImage getImage() {
        //创建一个图片对象
        BufferedImage image = createImage();
        //继续获取画笔
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        //保存随机生成的字符串
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";
            sb.append(s);
            g2.setColor(randomColor());
            g2.setFont(randomFont());
            float x = i * width * 1.0f / 4;
            g2.drawString(s, x, height - 8);
        }
        this.text = sb.toString();
        drawLine(image);
        return image;
    }

    /**
     * 绘制干扰线
     *
     * @param image
     */
    private void drawLine(BufferedImage image) {
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        int num = 5;
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2.setColor(randomColor());
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    public String getText() {
        return text;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}

servlet登录接口

package com.qfedu.demo.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.demo.model.RespBean;
import com.qfedu.demo.service.UserService;
import com.qfedu.demo.utils.CommonsUtils;
import com.qfedu.demo.utils.VerificationCode;

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;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    UserService userService=new UserService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("vcode".equals(action)){
            //获取验证码
            VerificationCode verificationCode=new VerificationCode();
            BufferedImage image = verificationCode.getImage();
            String text = verificationCode.getText();
            System.out.println("vcode = " + text);
            //保存到session,方便以后使用
            HttpSession session = request.getSession();
            session.setAttribute("vcode",text);
            //输出到浏览器
            VerificationCode.output(image,response.getOutputStream());
        }else {
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Integer result = userService.login(username, password,request);
        RespBean respBean = null;
        if (result == CommonsUtils.VCODE_ERROR){
            respBean = RespBean.error("验证码错误,登录失败");
        } else if (result == CommonsUtils.ACCOUNT_DISABLED) {
            respBean=RespBean.error("账户被禁用,登录失败");
        }else if (result == CommonsUtils.USERNAME_NOT_OR_PASSWORD_ERROR) {
            respBean = RespBean.error("用户名或者密码输入错误,登录失败");
        } else if (result == CommonsUtils.LOGIN_SUCCESS) {
            respBean = RespBean.ok("登录成功");
        } else {
            respBean = RespBean.error("登录失败");
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        ObjectMapper om = new ObjectMapper();
        out.write(om.writeValueAsString(respBean));
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14618.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!