servlet验证码

//画验证码

public class ValidateCode extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {  
        BufferedImage img=new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
//      1、获取画笔      
        Graphics g=img.getGraphics();
        Random random=new Random();
        g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
        g.fillRect(0, 0,100, 30);
        //2获取验证码
        String text=getText(5);
        HttpSession session=req.getSession();
        session.setAttribute("code", text);
        g.setColor(new Color(0,0,0));
        g.setFont(new Font(null,Font.BOLD, 24));
        g.drawString(text, 5, 25);
        //绘制干扰线
        for(int i=0;i<8;i++){
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            g.drawLine(random.nextInt(100),random.nextInt(30), random.nextInt(100),random.nextInt(30));
        }
        //绘制到网页
        resp.setContentType("image/jpeg");
        OutputStream output=resp.getOutputStream();
        ImageIO.write(img, "jpeg", output);
        output.close();


    }


    //获取字符随机字符串
    public String getText(int size){
        String str="QWERTYUIOPLKJHGFDSAZXCVBNMmnbvcxzasdfghjklpoiuytrewq0123456789";
        String text="";
        Random r=new Random();
        for(int j=0;j<size;j++){
            text+=str.charAt(r.nextInt(str.length()));
        }
        return text;
    }

}

web.xml设置

 <servlet-name>identify</servlet-name>
  <servlet-class>com.edusak.identity.ValidateCode</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>identify</servlet-name>
  <url-pattern>/code</url-pattern>
  </servlet-mapping>

网页代码

<div >
<label >验证码:</label> 
<input  name="j_captcha" type="text" placeholder="请输入验证码"> <img id="captcha_img"    alt="点击更换" title="点击更换" src="code" class="m img" onclick="this.src='code?'+Math.random();">
</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值