java验证码生成

第一种方式:纯代码

先写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包网上能搜到)

 

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

 

posted @ 2019-01-15 21:39  土木转行的人才  阅读(187)  评论(0编辑  收藏  举报