利用Apache的一个 开源项目Image Tag Library(http://jakarta.apache.org/taglibs/sandbox/doc/image-doc/intro.html)
下载必要文件
1)下载Jakarta-Taglibs:
http://people.apache.org/builds/jakarta-taglibs-sandbox/nightly/
解压后取出taglibs-image.jar放于/WEB-INF/lib下
将taglibs-image.tld拷到/WEB-INF/下
2)下载Poor Man's Imaging Wrapper:Image Tag 用到了这个包
http://www.mullassery.com/downloads/ 填写一些必要信息后就可以免费下载了
解压后将pmiw.jar拷到/WEB-INF/lib下
在web.xml中配置ImageServlet
<context-param>
<param-name>ImageServletMapping</param-name>
<param-value>/gen-image</param-value>
</context-param>
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>org.apache.taglibs.image.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/gen-image/*</url-pattern>
</servlet-mapping>
在jsp页面中加入实现代码(部分内容参考了http://technology.a.lunqun.com/read.php?tid=149894&page=e&fpage=1)
1)在页首加入<%@ taglib uri="/WEB-INF/taglibs-image.tld" prefix="img" %>
2)在页面顶端加入
<%
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
%>
3)在想加上验证码的地方加上如下代码:
<%
int num = (int) java.lang.Math.round(java.lang.Math.random() * 8999);
String sRand = "" + (1000 +num);
session.setAttribute("userInfo.authcode",sRand);
%>
<img:image src="/graphics/auth.jpg" refresh="true">
<img:text text="<%=sRand.substring(0,1)%>" x="7" y="-1" font="Times New Roman" bold="false" size="22" color="0x993399" italic="true" />
<img:text text="<%=sRand.substring(1,2)%>" x="17" y="-1" font="Times New Roman" bold="false" size="22" color="0x660033" italic="false" />
<img:text text="<%=sRand.substring(2,3)%>" x="27" y="-1" font="Times New Roman" bold="true" size="18" color="0xcc3366" italic="true" />
<img:text text="<%=sRand.substring(3,4)%>" x="37" y="-1" font="Times New Roman" bold="false" size="22" color="0x990099" italic="false" />
<%if(num<4500){%>
<img:grayscale brightness="90" />
<%}%>
</img:image>