[已解决]Java验证码的生成,以及校验

转载自LonlySnow

https://blog.csdn.net/piaoyinluo2316/article/details/83754145

代码没有写校验,这里补了一下,主要是用到session

封装工具类

package com.ameng.utils;

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

//对图片进行处理的类和方法
public class VerifyCode {
    public static  String drawRandomText(int width, int height, BufferedImage verifyImg) {

        Graphics2D graphics = (Graphics2D)verifyImg.getGraphics();
        graphics.setColor(Color.WHITE);//设置画笔颜色-验证码背景色
        graphics.fillRect(0, 0, width, height);//填充背景
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 30));

        //数字和字母的组合
        String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

        StringBuffer sBuffer = new StringBuffer();
        int x = 10;  //旋转原点的 x 坐标
        String ch = "";
        Random random = new Random();
        for(int i = 0;i < 4;i++){
            graphics.setColor(getRandomColor());
            //设置字体旋转角度
            int degree = random.nextInt() % 10;  //角度小于30度
            int dot = random.nextInt(baseNumLetter.length());
            ch = baseNumLetter.charAt(dot) + "";

            sBuffer.append(ch);
            //正向旋转
            graphics.rotate(degree * Math.PI / 180, x, 45);
            graphics.drawString(ch, x, 45);
            //反向旋转
            graphics.rotate(-degree * Math.PI / 180, x, 45);
            x += 20;
        }

        //画干扰线
        for (int i = 0; i <6; i++) {
            // 设置随机颜色
            graphics.setColor(getRandomColor());
            // 随机画线
            graphics.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }
        //添加噪点
        for(int i=0;i<30;i++){
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            graphics.setColor(getRandomColor());
            graphics.fillRect(x1, y1, 2,2);
        }
        return sBuffer.toString();
    }
    /**
     * 随机取色

     */
    private static Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
        return color;
    }
}

Controller层

package com.ameng.controller;



import com.ameng.utils.Constants;
import com.ameng.utils.VerifyCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
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.OutputStream;


@Controller
public class VerifyCodeController {

    public static String number = "number";

    @RequestMapping("/getVerifyCode")
    @ResponseBody
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request,HttpSession session) throws IOException {
        int width=90;
        int height=60;
        BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //生成对应宽高的初始图片
        String randomText = VerifyCode.drawRandomText(width,height,verifyImg);
        String str = randomText;
        if(randomText != null) {
            session = request.getSession();
            session.setAttribute(Constants.code, randomText);
        }
        //单独的一个类方法,出于代码复用考虑,进行了封装。
        //功能是生成验证码字符并加上噪点,干扰线,返回值为验证码字符
        request.getSession().setAttribute("verifyCode", str);
        response.setContentType("/image/png");//必须设置响应内容类型为图片,否则前台不识别
        OutputStream os = response.getOutputStream(); //获取文件输出流
        ImageIO.write(verifyImg,"png",os);//输出图片流
        os.flush();
        os.close();//关闭流
    }

}

初学SSM,Controller层写的还不是很好,校验

    @RequestMapping("/login")
    @ResponseBody
    public int login(@RequestParam Map<String,Object> map, HttpSession session ,HttpServletRequest request) {
        int i = 0;
        String code = session.getAttribute(Constants.code).toString();
        System.out.println(code);
        String userAccount = map.get("userAccount").toString();
        String password = map.get("password").toString();
        String captcha = map.get("captcha").toString();
        User user = userService.getUserByUserAccount(userAccount);
        /*验证码错误返回0
        * 账号不存在返回1
        * 密码错误返回2
        * 校验成功返回4*/
        if (captcha.equalsIgnoreCase(code)){
            if (user != null){
                //必须用equals
                if (user.getPassword().equals(password)){
                    session.setAttribute(Constants.USER_SESSION,user);
                    i = 4;
                }else {
                    i = 2;
                }
            }else {
                i = 1;
            }
        }
        return i;
    }

前端界面这里就不提供了,如果配置了SpringMVC拦截器,记得释放这个请求

posted @ 2021-05-10 00:00  阿蒙么么哒  阅读(172)  评论(0)    收藏  举报