本帖最后由 yting_xmei1129 于 2013-9-21 20:05 编辑
下面就是源代码,拿出来跟大家分享一下、、、这里只是客户端生成出认证码并存放到session中去,如果要实现校验功能的话还需要用户输入校验码,并在服务端上进行校验、、、有兴趣的朋友可以把整个工程都考给你们、、、- package yting.day06.web.randompic;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import java.util.Random;
- import javax.imageio.ImageIO;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ServletRandomPicture extends HttpServlet {
- private static final long serialVersionUID = 3096336305189372825L;
- private static final int WIDTH = 120;
- private static final int HEIGHT = 25;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
- Graphics g = image.getGraphics();
-
- //1.设置背景色
- setBackGround(g);
-
- //2.设置边框
- setBorder(g);
-
- //3.画干扰线
- drawRandomLine(g);
-
- //4.写随机数
- String cilentCheckCode = drawRandowNum((Graphics2D) g);
- //将cilentCheckCode存到session中去,用来校验用
- request.getSession().setAttribute("checkcode", cilentCheckCode);
-
- //5.图形写给浏览器,通知浏览器以图片的方式打开,并且告诉浏览器不要缓存
- response.setHeader("content-type", "image/jpeg");
- response.setDateHeader("expries", -1);
- response.setHeader("Cache-Control", "no-cache");
- response.setHeader("Pragma", "no-cache");
-
- ImageIO.write(image, "jpeg", response.getOutputStream());
- }
- private void setBackGround(Graphics g) {
- g.setColor(Color.WHITE);
- g.fillRect(0, 0, WIDTH, HEIGHT);
- }
-
- private void setBorder(Graphics g) {
- g.setColor(Color.BLACK);
- g.drawRect(0, 0, WIDTH-1, HEIGHT-1);
- }
-
- private void drawRandomLine(Graphics g) {
- g.setColor(Color.GREEN);
- for(int i=0; i<5; i++){
- int x1 = 0;
- int y1 = new Random().nextInt(HEIGHT);
- int x2 = WIDTH-1;
- int y2 = new Random().nextInt(HEIGHT);
- g.drawLine(x1, y1, x2, y2);
- }
- }
-
- private String drawRandowNum(Graphics2D g) {
- String str = "最后饿留着眼泪看他抱着你的背我的想念你看不见另一个世界多美最后哭着说再见其实心里不情愿伤心绝对痛彻心扉离开以后饿不会再醉";
- StringBuffer sb = new StringBuffer();
- g.setColor(Color.RED);
- g.setFont(new Font("楷体", Font.BOLD, 25));
- int x=5;
- for(int i=0;i<4;i++){
- int degree = new Random().nextInt()%30; //设置旋转弧度,在-30~30之间
- String ch = str.charAt(new Random().nextInt(str.length()))+"";
- sb.append(ch);
- g.rotate(degree*Math.PI/180, x+14, 11); //开始旋转
- g.drawString(ch, x, 22);
- g.rotate(-degree*Math.PI/180, x+14, 11); //将旋转的弧度转回去,写下一个字
- x+=28;
- }
- return sb.toString();
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
复制代码 |