java使用servlet画出最简单的验证码二(带干扰因素之线条)

在上一篇实现验证码的基础之上,本篇加上干扰因素线条,基本上原理都不变

1、在login.jsp页面中加入样式代码

<form action="<%=request.getContextPath()%>/action" method="post">
       <div>
           <label class="fl w_20">验证码:</label>
           <span class="fr w_80 verify">
                  <input type="text" class="text_txt code" name="userCode">
                  <img id="num" src="checkCode"  />
                  <a href="javascript:;" 
                           onclick="document.getElementById('num').src='checkCode?'+(new Date()).getTime()">
                                        换一张</a>    
           </span>
           <span class="msg"  style="color:red">
                    <%
                       String codeMsg=(String)request.getAttribute("code_msg");
                     %>
                     <%=codeMsg==null?"":codeMsg %>
           </span>
       </div>
       <div>
           <span class="fr w_80">
                 <input type="submit" style="height: 50px;" value="登录">
           </span>
       </div>
</form>

2、在src下建CheckCodeServlet类用来“画”验证码

package com.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
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;
import javax.servlet.http.HttpSession;
/*
 * 生成验证码
 */
public class CheckCodeServlet extends HttpServlet {

    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        OutputStream os=response.getOutputStream();
        
        response.setContentType("image/jpeg");
        //System.out.println("service...");
        //创建图片映射区(画板)
        BufferedImage image=new BufferedImage(80, 40, BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics g=image.getGraphics();
        Random r=new Random();//获取随机数
        g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
        g.fillRect(0, 0, 80, 40);
        //画字符串
        g.setColor(Color.black);
        g.setFont(new Font(null,Font.BOLD,20));//设置字体,粗体,大小
        
        String num=getNum(5);//调用getNum方法
        //将正确的验证码保存到session中
        HttpSession session=request.getSession();
        session.setAttribute("rightCode", num);
        g.drawString(num, 5, 30);
        
        //画线   可以延缓登录时间,减缓程序
        for(int i=0;i<6;i++){
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.drawLine(r.nextInt(80), r.nextInt(40), r.nextInt(80), r.nextInt(40));
        }
        
        //压缩图片
        ImageIO.write(image, "jpeg", os);
        os.close();
    }
    
    //返回正确的验证码
    public String getNum(int length){
        StringBuffer sf=new StringBuffer();
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        Random r=new Random();
        for(int i=0;i<length;i++){
            int index=r.nextInt(str.length());
            char c=str.charAt(index);
            sf.append(c);
        }
        return sf.toString();
    }

}

3、在src下建ActionServlet类用来处理用户输入的信息与验证码图片的信息匹配问题

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Asdf extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8"); // 输出中文
        PrintWriter out = response.getWriter();
        // 创建session对象
        HttpSession session = request.getSession();
        String userCode = request.getParameter("userCode");// 验证码
        String rightCode = (String) session.getAttribute("rightCode");
        if (!userCode.equalsIgnoreCase(rightCode)) {// 成立则失败
            // 回到登录界面
            request.setAttribute("code_msg", "验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else {
            out.println("验证码输入正确");
        }
        out.flush();
        out.close();
    }
}

4、最后在web.xml中去配置两个servlet请求

<servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>com.servlet.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>/action</url-pattern>
</servlet-mapping>
  
<servlet>
    <servlet-name>CheckCodeServlet</servlet-name>
    <servlet-class>com.servlet.CheckCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CheckCodeServlet</servlet-name>
    <url-pattern>/checkCode</url-pattern>
</servlet-mapping>

到这里就完成了,接下来看效果图吧,这个是加了修饰样式的,与提供的代码有所差异哈,但问题不大。

小弟学浅,有照顾不周的地方请见谅哈

posted @ 2018-09-21 11:51  不是一个世界的人  阅读(408)  评论(0编辑  收藏  举报