`

验证码使用总结

    博客分类:
  • Java
阅读更多
Servlet生成验证码
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = -5051097528828603895L;
    private int width = 100;
    private int height = 30;
    private int codeCount = 4;
    private int fontHeight;
    private int codeX;
    private int codeY;

    char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
        'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    public void init() throws ServletException {

        String strWidth = this.getInitParameter("width");
        String strHeight = this.getInitParameter("height");
        String strCodeCount = this.getInitParameter("codeCount");

        try {
            if (strWidth != null && strWidth.length() != 0) {
                width = Integer.parseInt(strWidth);
            }
            if (strHeight != null && strHeight.length() != 0) {
                height = Integer.parseInt(strHeight);
            }
            if (strCodeCount != null && strCodeCount.length() != 0) {
                codeCount = Integer.parseInt(strCodeCount);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        codeX = (width - 4) / (codeCount + 1);
        fontHeight = height - 10;
        codeY = height - 7;
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gd = buffImg.createGraphics();
        Random random = new Random();
        gd.setColor(Color.LIGHT_GRAY);
        gd.fillRect(0, 0, width, height);
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        gd.setFont(font);
        gd.setColor(Color.BLACK);
        gd.drawRect(0, 0, width - 1, height - 1);
        gd.setColor(Color.gray);
        for (int i = 0; i < 16; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            gd.drawLine(x, y, x + xl, y + yl);
        }
        StringBuffer randomCode = new StringBuffer();
        int red = 0;
        int green = 0;
        int blue = 0;
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            gd.setColor(new Color(red, green, blue));
            gd.drawString(strRand, (i + 1) * codeX, codeY);
            randomCode.append(strRand);
        }
        HttpSession session = request.getSession();
        session.setAttribute("captcha", randomCode.toString());
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
    }
}


Web.xml中的配置
<servlet>
        <servlet-name>CaptchaServlet</servlet-name>
        <servlet-class>com.quidsi.emm.track.util.CaptchaServlet</servlet-class>
        <init-param>
            <param-name>width</param-name>
            <param-value>120</param-value>
        </init-param>
        <init-param>
            <param-name>height</param-name>
            <param-value>32</param-value>
        </init-param>
        <init-param>
            <param-name>codeCount</param-name>
            <param-value>4</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>CaptchaServlet</servlet-name>
        <url-pattern>/CaptchaServlet</url-pattern>
    </servlet-mapping>


页面中的使用:
 <div>
	Captcha:<input id="inputCode" name="inputCode" />
	<img src="CaptchaServlet" align="middle" title="Look not clear, please click me"  onclick="javascript:refresh(this);" onmouseover="mouseover(this)"/>
</div>


相关问题
1、浏览器后退,可以不断重复提交。js禁用后退:<script language="JavaScript">javascript:window.history.forward(1);</script>
2、前端页面验证码输入验证时,从后台取到的验证码与页面显示的验证码慢一拍。
   解决方案:(1)、在提交的时候通过ajax请求取得最新的验证码。
             (2)、直接后台验证一次,验证失败回写前台
3、跨域请求,改用相对路径
4、javax.imageio.IIOException: Can't create output stream!
   原因:ImageIO依赖于Tomcat的temp目录,如temp目录遗失就会报上述错误
   解决方案:(1)、(不推荐)在tomcat目录下加上temp目录
             (2)、(不推荐)把ImageIO.write(image, "jpeg", response.getOutputStream());修改为
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(image);
(3)、禁用缓存ImageIO.setUseCache(false);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics