servlet实现验证码

/**
*servlet类
*/
package servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class YZMServlet extends HttpServlet {
    public static final char[] CHARS={'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S'};
    public static Random random=new Random();
    //获取随机数
    public static String getRandomString(){
        StringBuffer buffer=new StringBuffer();
        for(int i=0;i<6;i++){
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }
    //获取随机颜色
    public static Color getRandomColor(){
        return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
    }
    //反色
    public static Color getReverseColor(Color c){
        return new Color(random.nextInt(255-c.getRed()),random.nextInt(255-c.getGreen()),random.nextInt(255-c.getBlue()));
    }
    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //如果需要在客户端写二进制数据,可以使用HttpServletResponse.getOutputStream()
        resp.setContentType("image/jpeg");//设置输出类型
        String randomString=getRandomString();//随机字符串
        req.getSession(true).setAttribute("randomString", randomString);//放到session中
        int width=100;
        int height=30;
        Color color=getRandomColor();
        Color reverse=getReverseColor(color);
        //设置一个彩色图片
        BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取画图对象
        Graphics2D g=bi.createGraphics();
        g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));//设置字体
        g.setColor(color);//设置颜色
        g.fillRect(0, 0, width, height);//设置背景
        g.setColor(reverse);
        g.drawString(randomString, 18, 20);//绘制随机字符,18是x坐标,20是y坐标
        for(int i=0,n=random.nextInt(100);i<n;i++){
            //绘制噪音点,增加识别难度
            g.drawRect(random.nextInt(width), random.nextInt(height),1,1);
        }
        ServletOutputStream out=resp.getOutputStream();//转成JPEG格式
        JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);//编码器
        encoder.encode(bi);//对图片进行编码
        out.flush();//输出到客户端
    }


}

/**
*web.xml
*/

 <servlet>
    <servlet-name>yzmServlet</servlet-name>
    <servlet-class>servlet.YZMServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>yzmServlet</servlet-name>
    <url-pattern>/YZMServlet</url-pattern>
  </servlet-mapping>

/*JSP页面/

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
    function reloadImage(){
        document.getElementById('btn').disabled=true;
        document.getElementById('yzm').src='YZMServlet?ts='+new Date().getTime();
    }
</script>
</head>
<body>
    <img src="YZMServlet" id="yzm" onload="btn.disabled=false;">
    <input type="button" value="换个图片" onclick="reloadImage()" id="btn">
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值