§封Ja葬va§

自定义图形验证码标签

JSP页面上引入:
<%@ taglib uri="/htdz-tag" prefix="htdz-tag"%>
使用自定义图形验证码标签自动生成验证码:
<htdz-tag:CheckCodeTag />

以下为详细定义过程:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
 version="2.0">
    <description>htdz tag</description>
    <display-name>htdz tag</display-name>
    <tlib-version>1.0</tlib-version>
    <short-name>htdz-tag</short-name>
    <uri>/htdz-tag</uri>

    <tag>

    <!--   
    验证码控件
    使用说明:
    jsp中使用范例:
    1.无参数:<htdz-tag:CheckCodeTag/>
    2.全部参数:<htdz-tag:CheckCodeTag id="checkCodeImg" height="18" width="58"/>
   
    如果用户未设置参数,则默认值分别为:height="18" width="58"
    -->
    <description>验证码控件</description>
    <name>CheckCodeTag</name>
    <tag-class>com.htdz.util.tag.CheckCodeTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>id</description>
        <name>id</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>高</description>
        <name>height</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>宽</description>
        <name>width</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>

    </tag>
<taglib/>

CheckCodeTag.java:

public class CheckCodeTag extends TagSupport {
    private String id;
    private String height;
    private String width;

    public CheckCodeTag() {
    }

    @SuppressWarnings( { "unchecked", "static-access" })
    public int doStartTag() throws JspException {
        StringBuffer html = new StringBuffer();
        if (height == null || height.length() == 0)
            height = "18";
        if (width == null || width.length() == 0)
            width = "60";
        html.append("<img alt=\"重新获取验证码\"");
        if (id != null && id.length() > 0) {
            html.append(" id=\"");
            html.append(id);
            html.append("\"");
        }
        html.append(" height=\"");
        html.append(height);
        html.append("\" width=\"");
        html.append(width);
        html.append("\" src=\"/checkCodeImg\" onclick=\"this.src='/checkCodeImg?now='+new Date();\" style=\"cursor: pointer\" />");
        try {
            pageContext.getOut().println(html.toString());
        } catch (Exception e) {
            throw new JspException(e.getMessage());
        }
        return this.SKIP_BODY;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public void setWidth(String width) {
        this.width = width;
    }
}



web.xml:
    <servlet>
        <servlet-name>img</servlet-name>
        <servlet-class>com.htdz.util.CheckCodeImg</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>img</servlet-name>
        <url-pattern>/checkCodeImg</url-pattern>
    </servlet-mapping>


CheckCodeImg.java:

public class CheckCodeImg extends HttpServlet {
    private Font mFont = new Font("Arial black", Font.PLAIN, 16);

    public void init() throws ServletException {
        super.init();
    }

    Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");

        int width = 60, height = 18;
        BufferedImage image = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(1, 1, width - 1, height - 1);
        g.setColor(new Color(102, 102, 102));
        g.drawRect(0, 0, width - 1, height - 1);
        g.setFont(mFont);

        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g.drawLine(x, y, x + xl, y + yl);
        }
        for (int i = 0; i < 70; i++) {
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int xl = random.nextInt(12) + 1;
            int yl = random.nextInt(6) + 1;
            g.drawLine(x, y, x - xl, y - yl);
        }

        char[] codes = { // 'a','b','c','d','e','f','h','k','m','n','r','s','t','x','y',//15个
                                     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
                                 // 'A','B','C','D','E','F','G','H','K','N','S','T','X','Y'//14
        };
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            int j = random.nextInt(10);
            String tmp = String.valueOf(codes[j]);
            sRand += tmp;
            g.setColor(new Color(20 + random.nextInt(110), 20 + random
            .nextInt(110), 20 + random.nextInt(110)));
            g.drawString(tmp, 15 * i + 2, 15);
        }

        HttpSession session = request.getSession(true);
        session.setAttribute(MyConstant.SESSION_CHECKCODE, sRand);
        g.dispose();
        ImageIO.write(image, "PNG", response.getOutputStream());
   }
}

posted on 2009-04-04 00:52 §朱家二少§ 阅读(408) 评论(1)  编辑  收藏 所属分类: J2SE

Feedback

# re: 自定义图形验证码标签 2011-05-23 13:24 tandong

你这个标签有什么意义呢 Servlet还得开发人员自己写  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: