五種內置的效果圖
網頁中使用
配置web.xml<servlet>
<servlet-name>patchca</servlet-name>
<servlet-class>com.ssh.servlet.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>patchca</servlet-name>
<url-pattern>/patchca.png</url-pattern>
</servlet-mapping>
一:自定義CaptchaService(可靈活配置效果)
public class CaptchaServlet extends HttpServlet {
private static MyCaptchaService cs = null;
@Override
public void init() throws ServletException {
super.init();
//可直接使用ConfigurableCaptchaService,然後修改配置
cs = new MyCaptchaService();
}
@Override
public void destroy() {
cs = null;
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/png");
response.setHeader("cache", "no-cache");
HttpSession session = request.getSession(true);
OutputStream os = response.getOutputStream();
String patchca= EncoderHelper.getChallangeAndWriteImage(cs, "png", os);
session.setAttribute("PATCHCA", patchca);
os.flush();
os.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
private class MyCaptchaService extends AbstractCaptchaService {
public MyCaptchaService() {
//文本內容
wordFactory = new MyWordFactory();
//字型
fontFactory = new RandomFontFactory();
//效果
textRenderer = new BestFitTextRenderer();
//背景
backgroundFactory = new SingleColorBackgroundFactory();
//字型顏色
colorFactory = new SingleColorFactory(new Color(25, 60, 170));
//樣式(曲線波紋加干擾線)
filterFactory = new CurvesRippleFilterFactory(colorFactory);
//圖片長寬
width = 150;
height = 50;
}
}
private class MyWordFactory extends RandomWordFactory {
public MyWordFactory() {
//文本範圍和長度
characters = "absdekmnowx23456789";
minLength = 5;
maxLength = 4;
}
}
}
二:使用包中提供的配置
(1)ConfigurableCaptchaService
默認配置說明:
FontFactory 字型 默認:RandomFontFactory(Verdana,Tahoma,minSize、maxSize=45)
WordFactory 單詞範圍和長度 默認:RandomWordFactory 單詞6-6
ColorFactory 默認:SingleColorFactory 黑色
BackgroundFactory 默認:SingleColorBackgroundFactory 白色
TextRenderer 文本渲染 默認:BestFitTextRenderer
FilterFactory 樣式 默認:CurvesRippleFilterFactory(曲線波紋帶干擾線,干擾線顏色為當前colorFactory)
width/height 圖片長寬(默認160*70)
(2)SimpleCaptchaService 構造時需要自己輸入參數
<table><tr>
<!-- patchca.png和servlet中的<url-pattern>對應 -->
<td><img src="patchca.png" alt="驗證碼"style="cursor:pointer;vertical-align:text-bottom;" onclick="this.src=this.src+'?'+Math.random();"></td>
<td valign="top">
<form method="POST"><br>
驗證碼:<input type="text" name="patchcafield"><br />
<input type="submit" name="submit">
</form></td></tr></table>
<%//"PATCHCA"和servlet中定義的session保存位置對應
String c = (String)session.getAttribute("PATCHCA");
String parm = (String) request.getParameter("patchcafield");
out.println("Parameter: " + parm + " ? Session Key: " + c + " : ");
if (c != null && parm != null) {
if (c.equalsIgnoreCase(parm)) {
out.println("<b>true</b>");
} else {
out.println("<b>false</b>");
}}%>