使用IDEA产生随机验证码

语句的作用注释在代码块中
运行结果:
随机生成宽250,长150的验证码图片:
在这里插入图片描述
生成一张250X150的图片:

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //生成图片
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(generatePic(250,150),"JPEG" ,sos);
        sos.flush();
        sos.close();
    }

先建立一张图片:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();

width是图片宽度,height是图片长度,最后一个参数是图片类型。
新建一个类randString,能够获取随机字符:

public static String randString(int count){
        String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//字符串仓库
        Random rand = new Random();
        String res = "";
        for(int i = 0;i<count;i++){
            res +=text.charAt(rand.nextInt(text.length()));
        }//通过循环语句,生成随机字符
        return res;
    }

然后在图片类中添加语句:

String text = CaptcheController.randString(4);//生成4个随机字符
        for (int i = 0; i < text.length(); i++) {
            Random rand = new Random();
            g.setFont(new Font("宋体", Font.BOLD, randint((int) (width * 0.2), (int) (height * 0.6))));//设置字体,字号随着图片大小而改变
            g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));//设置字体颜色,在0~255之间随机
            AffineTransform aff = g.getTransform();
            double radis = Math.toRadians(rand.nextInt(140));//设置字体的旋转角度,在0~140度之间随机
            int x = (int) (width * 0.4); //字体的X坐标
            int y = (int) (height * 0.5);//字体的Y坐标
            g.rotate(radis, 125, 75);//旋转图片
            g.drawString(text.charAt(i) + "", x, y);
        }

新建一个类randint,用来固定字符串的位置:

public static int randint(int a,int b){
    Random r = new Random();
    int res = r.nextInt(b-a);
    res += a ;
    return res;
}

使用drawOval方法生成噪点,使用循环+随机坐标来生成:

for (int i = 0; i < 20; i++) {
            Random r = new Random();
            int x = r.nextInt(width);
            int y = r.nextInt(height);
            g.drawOval(x, y, 5, 5);
        }

新建类getRandColor,设置线条:

private static Color getRandColor(int fc, int bc) {
    Random random = new Random();
    if (fc > 255) {
        fc = 255;
    }
    if (bc > 255) {
        bc = 255;
    }
    int r = fc + random.nextInt(bc - fc);
    int g = fc + random.nextInt(bc - fc);
    int b = fc + random.nextInt(bc - fc);
    return new Color(r, g, b);
}

在图片类中添加设置线条语句:

 Random r2 = new Random();
 g.setColor(getRandColor(160,200));//设置线条颜色
 for (int i=0;i<20;i++){
 int x = r2.nextInt(width-20);//设置线条的宽度
 int y = r2.nextInt(height-10);//设置线条高度
 int xl = r2.nextInt(12);
 nt yl = r2.nextInt(20);
 g.drawLine(x,y,x+xl+30,y+yl+20);
        }
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现验证码登录页面,需要在之前的示例代码中添加一个验证码输入框和一个生成验证码的逻辑。 下面是一个使用 Java 和 Spring Boot 框架实现验证码登录页面的示例: 1. 在 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 2. 创建一个 `LoginController` 类,该类包含以下方法: ```java @GetMapping("/login") public String login() { return "login"; } @PostMapping("/doLogin") public String doLogin(@RequestParam String username, @RequestParam String password, @RequestParam String verifyCode, HttpSession session) { String kaptchaCode = (String) session.getAttribute("kaptchaCode"); if (!verifyCode.equalsIgnoreCase(kaptchaCode)) { return "redirect:/login?error=验证码错误"; } // 验证用户名和密码,如果验证通过,则跳转到主页 return "redirect:/index"; } @GetMapping("/verifyCode") public void verifyCode(HttpServletResponse response, HttpSession session) throws Exception { // 生成验证码图片,并将验证码文本存入 session response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String verifyCode = new Kaptcha().createText(); session.setAttribute("kaptchaCode", verifyCode); BufferedImage image = new Kaptcha().createImage(verifyCode); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); out.close(); } ``` 3. 创建一个 `login.html` 页面,包含以下代码: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>验证码登录</title> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6"> <div class="card"> <div class="card-header">验证码登录</div> <div class="card-body"> <form action="/doLogin" method="post"> <div class="form-group"> <label for="username">用户名</label> <input type="text" class="form-control" id="username" name="username" required autofocus> </div> <div class="form-group"> <label for="password">密码</label> <input type="password" class="form-control" id="password" name="password" required> </div> <div class="form-group"> <label for="verifyCode">验证码</label> <div class="input-group"> <input type="text" class="form-control" id="verifyCode" name="verifyCode" required> <img src="/verifyCode" onclick="this.src='/verifyCode?t='+Math.random()" style="cursor: pointer;"> </div> </div> <button type="submit" class="btn btn-primary btn-block">登录</button> </form> </div> </div> </div> </div> </div> </body> </html> ``` 在这个页面中,我们创建了一个包含用户名、密码和验证码输入框的表单,并使用 Bootstrap 样式美化页面。验证码输入框旁边还有一个图像,点击图像可以刷新验证码。 这样,就实现了一个简单的验证码登录页面。当用户提交表单时,控制器会验证验证码是否正确,如果验证码正确,则继续验证用户名和密码,如果验证通过,则跳转到主页。否则,将出现错误消息并重定向到登录页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值