码迷,mamicode.com
首页 > 编程语言 > 详细

java验证码生成

时间:2019-01-15 22:03:27      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:out   png   技术   pack   pac   ***   tin   line   font   

第一种方式:纯代码

先写jsp:

技术分享图片

在编写CaptServlet:

 1 package cn.itcast.web.controller;
 2 
 3 import java.awt.Color;
 4 import java.awt.Font;
 5 import java.awt.Graphics;
 6 import java.awt.image.BufferedImage;
 7 /**
 8  * 用户登陆
 9  */
10 import java.io.IOException;
11 import java.util.Random;
12 
13 import javax.imageio.ImageIO;
14 import javax.servlet.ServletException;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18 
19 public class CaptServlet extends HttpServlet {
20     private static final long serialVersionUID = 1L;
21 
22     protected void doGet(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         int width = 120;
25         int height = 25;
26         //验证码
27         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
28         //画笔
29         Graphics g = image.getGraphics();
30             //设置颜色,设置一个边线
31             g.setColor(Color.green);
32             g.drawRect(0, 0, width, height);
33             //设置填充色
34             g.setColor(Color.yellow);
35             g.fillRect(1, 1, width-2, height-2);
36             //干扰线
37             g.setColor(Color.gray);
38             Random r = new Random();
39             g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
40             //随机验证码
41             g.setColor(Color.black);
42             g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 20));
43             int x = 20;
44             for(int i=0;i<4;i++) {
45             String num = r.nextInt(10)+"";
46             g.drawString(num, x, 20);
47             x+=20;
48             }
49         //输出到页面
50             ImageIO.write(image, "jpg", response.getOutputStream());
51     }
52

53     protected void doPost(HttpServletRequest request, HttpServletResponse response)
54             throws ServletException, IOException {
55         // TODO Auto-generated method stub
56         doGet(request, response);
57     }
58 
59 }

页面效果:

技术分享图片

//**********************推荐(validatecode 的jar包网上能搜到)

 技术分享图片

行轻松搞定。**********************************************************************************************

技术分享图片

 

java验证码生成

标签:out   png   技术   pack   pac   ***   tin   line   font   

原文地址:https://www.cnblogs.com/csh520mjy/p/10274438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!