WEB项目总结(二)开源验证码patcha引入
来源:互联网 发布:手机gif修改软件 编辑:程序博客网 时间:2024/06/01 16:03
通常来说一个B/S项目基本都会用到验证码,用于用户登录或注册,以此提高项目的安全性,而目前仍存在一些网站的应用环境比较特殊,使用人群分部较广,所以需要考虑ie浏浏览器的兼容性,众所周知,ie一代比一代坑,9以下和9以上差异非常大,第三方验证码都很少有兼容ie9以下的。然而由于国情的特殊,仍然有一大部分人在使用ie8甚至更低版本的浏览器。所以我用了patcha,这是一款兼容ie7以上所有版本 (7以下没做测试)的验证码jar包,接入非常方便,效果也不错。
首先,servlet中的代码
package org.captcha.servlet;import java.awt.Color;import java.io.IOException;import java.io.OutputStream;import java.util.Properties;import java.util.Random;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.patchca.color.ColorFactory;import org.patchca.color.SingleColorFactory;import org.patchca.filter.predefined.CurvesRippleFilterFactory;import org.patchca.filter.predefined.DiffuseRippleFilterFactory;import org.patchca.filter.predefined.DoubleRippleFilterFactory;import org.patchca.filter.predefined.MarbleRippleFilterFactory;import org.patchca.filter.predefined.WobbleRippleFilterFactory;import org.patchca.service.ConfigurableCaptchaService;import org.patchca.utils.encoder.EncoderHelper;import org.patchca.word.RandomWordFactory;public class CaptchaServlet extends HttpServlet {private static final long serialVersionUID = 4968328161261528097L;private static ConfigurableCaptchaService cs = null;private static ColorFactory cf = null;private static RandomWordFactory wf = null;private static Random r = new Random();private static CurvesRippleFilterFactory crff = null;private static MarbleRippleFilterFactory mrff = null;private static DoubleRippleFilterFactory drff = null;private static WobbleRippleFilterFactory wrff = null;private static DiffuseRippleFilterFactory dirff = null;/**验证码字符串长度,默认4*/private static Integer randomCodeLength=4;/**验证码图片宽度,默认120*/private static Integer randomCodeWidth=120;/**验证码图片高度,默认50*/private static Integer randomCodeHight=50;/**验证码样式 * 1 弯曲状 * 2 摇摆装 * 3 摇晃 * 4 散开 * 5 大理石 * 6 随机(默认) * */private static Integer randomCodeType=6;/**验证码session中Attribute的Name*/private static String randomCodeSessionAttributeName="PATCHCA";@Overridepublic void init() throws ServletException { super.init(); cs = new ConfigurableCaptchaService(); cf = new SingleColorFactory(new Color(25, 60, 170)); wf = new RandomWordFactory(); crff = new CurvesRippleFilterFactory(cs.getColorFactory()); drff = new DoubleRippleFilterFactory(); wrff = new WobbleRippleFilterFactory(); dirff = new DiffuseRippleFilterFactory(); mrff = new MarbleRippleFilterFactory(); cs.setWordFactory(wf); cs.setColorFactory(cf); cs.setWidth(randomCodeWidth); cs.setHeight(randomCodeHight); randomCodeLength=Integer.valueOf(null==this.getInitParameter("randomCodeLength")?"4":this.getInitParameter("randomCodeLength")); randomCodeWidth=Integer.valueOf(null==this.getInitParameter("randomCodeWidth")?"120":this.getInitParameter("randomCodeWidth")); randomCodeHight=Integer.valueOf(null==this.getInitParameter("randomCodeHight")?"50":this.getInitParameter("randomCodeHight")); randomCodeType=Integer.valueOf(null==this.getInitParameter("randomCodeType")?"6":this.getInitParameter("randomCodeType")); randomCodeSessionAttributeName=null==this.getInitParameter("randomCodeSessionAttributeName")?"PATCHCA":this.getInitParameter("randomCodeSessionAttributeName");}@Overridepublic void destroy() { wf = null; cf = null; cs = null; super.destroy();}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/png"); response.setHeader("cache", "no-cache"); wf.setMaxLength(randomCodeLength); wf.setMinLength(randomCodeLength); HttpSession session = request.getSession(true); OutputStream os = response.getOutputStream(); int typeCode=randomCodeType; if(typeCode==6) { typeCode=r.nextInt(5); } //随机产生5种效果(filter) switch (typeCode) { case 1: cs.setFilterFactory(crff); break; case 2: cs.setFilterFactory(mrff); break; case 3: cs.setFilterFactory(drff); break; case 4: cs.setFilterFactory(wrff); break; case 5: cs.setFilterFactory(dirff); break; default: cs.setFilterFactory(crff); break; } //这里可以生成彩色验证码/* final Random random = new Random(); cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170))); cs.setColorFactory(new ColorFactory() { @Override public Color getColor(int x) { int[] c = new int[3]; int i = random.nextInt(c.length); for (int fi = 0; fi < c.length; fi++) { if (fi == i) { c[fi] = random.nextInt(71); } else { c[fi] = random.nextInt(256); } } return new Color(c[0], c[1], c[2]); } });*/ String patchca= EncoderHelper.getChallangeAndWriteImage(cs, "png", os); session.setAttribute(randomCodeSessionAttributeName, patchca); os.flush(); os.close(); }}
web.xml中的配置
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>patchattest</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>patchca</servlet-name> <servlet-class>org.captcha.servlet.CaptchaServlet</servlet-class> <init-param><param-name>randomCodeType</param-name><param-value>3</param-value></init-param> </servlet> <servlet-mapping> <servlet-name>patchca</servlet-name> <url-pattern>/patchca.png</url-pattern></servlet-mapping></web-app>
jsp中的代码,注意点击事件后面跟的随机数,用于改变图片url防止浏览器缓存不清,点击时重点内容图片不变动。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my JSP page. <br> <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> <br /><br /><br /><br /> </body></html>
效果
上面这种方式原生serlvlet的写法应该没人用了,现在都是用框架,这更加简单,不需要任何配置,这边用struts
action中的代码,action返回的结果是一个图片流,页面上直接用img标签可以接收到。
import java.awt.Color;import java.io.IOException;import java.io.OutputStream;import java.io.PrintWriter;import java.util.Random;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.Namespace;import org.apache.struts2.convention.annotation.ParentPackage;import org.patchca.color.ColorFactory;import org.patchca.color.SingleColorFactory;import org.patchca.filter.predefined.CurvesRippleFilterFactory;import org.patchca.filter.predefined.DiffuseRippleFilterFactory;import org.patchca.filter.predefined.DoubleRippleFilterFactory;import org.patchca.filter.predefined.MarbleRippleFilterFactory;import org.patchca.filter.predefined.WobbleRippleFilterFactory;import org.patchca.service.ConfigurableCaptchaService;import org.patchca.utils.encoder.EncoderHelper;import org.patchca.word.RandomWordFactory;import com.jshop.action.backstage.base.BaseTAction;import com.opensymphony.xwork2.ActionContext;@Namespace("/frontstage/buyers")@ParentPackage("jshop")public class CaptchaAction extends BaseTAction{ /** *patchca验证码 *@author tang */ private static final long serialVersionUID = 1L; private static ConfigurableCaptchaService cs = null; private static ColorFactory cf = null; private static RandomWordFactory wf = null; private static Random r = new Random(); private static CurvesRippleFilterFactory crff = null; private static MarbleRippleFilterFactory mrff = null; private static DoubleRippleFilterFactory drff = null; private static WobbleRippleFilterFactory wrff = null; private static DiffuseRippleFilterFactory dirff = null; /**验证码字符串长度,默认4*/ private static Integer randomCodeLength=4; /**验证码图片宽度,默认120*/ private static Integer randomCodeWidth=120; /**验证码图片高度,默认50*/ private static Integer randomCodeHight=50; /**验证码样式 * 1 弯曲状 * 2 摇摆装 * 3 摇晃 * 4 散开 * 5 大理石 * 6 随机(默认) * */ private static Integer randomCodeType=6; /**验证码session中Attribute的Name*/ private static String randomCodeSessionAttributeName="PATCHCA"; /** * 生成验证码 * @author tang * @throws IOException */ @Action("/getCaptcha") public void getCaptcha(){ cs = new ConfigurableCaptchaService(); cf = new SingleColorFactory(new Color(25, 60, 170)); wf = new RandomWordFactory(); crff = new CurvesRippleFilterFactory(cs.getColorFactory()); drff = new DoubleRippleFilterFactory(); wrff = new WobbleRippleFilterFactory(); dirff = new DiffuseRippleFilterFactory(); mrff = new MarbleRippleFilterFactory(); cs.setWordFactory(wf); cs.setColorFactory(cf); cs.setWidth(randomCodeWidth); cs.setHeight(randomCodeHight); randomCodeLength=Integer.valueOf(randomCodeLength); randomCodeWidth=Integer.valueOf(randomCodeWidth); randomCodeHight=Integer.valueOf(randomCodeHight); randomCodeType=Integer.valueOf(randomCodeType); randomCodeSessionAttributeName=null==randomCodeSessionAttributeName?"PATCHCA":randomCodeSessionAttributeName; HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("image/png"); response.setHeader("cache", "no-cache"); wf.setMaxLength(randomCodeLength); wf.setMinLength(randomCodeLength); OutputStream os; try { os = response.getOutputStream(); int typeCode=randomCodeType; if(typeCode==6) { typeCode=r.nextInt(5); } //随机产生5种效果(filter) switch (typeCode) { case 1: cs.setFilterFactory(crff); break; case 2: cs.setFilterFactory(mrff); break; case 3: cs.setFilterFactory(drff); break; case 4: cs.setFilterFactory(wrff); break; case 5: cs.setFilterFactory(dirff); break; default: cs.setFilterFactory(crff); break; } final Random random = new Random(); cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170))); cs.setColorFactory(new ColorFactory() { @Override public Color getColor(int x) { int[] c = new int[3]; int i = random.nextInt(c.length); for (int fi = 0; fi < c.length; fi++) { if (fi == i) { c[fi] = random.nextInt(71); } else { c[fi] = random.nextInt(256); } } return new Color(c[0], c[1], c[2]); } }); String patchca= EncoderHelper.getChallangeAndWriteImage(cs, "png", os); System.out.println(patchca); if(os!=null){ os.close(); } ActionContext.getContext().getSession().put(randomCodeSessionAttributeName, patchca); }catch(Exception e){ System.err.println("远程主机关闭了一个现有的链接"); } }}
html代码
<img id="patchca" src="getCaptcha.action" alt="验证码" style="cursor:pointer;vertical-align:text-bottom;"onclick="this.src=this.src+'?random='+Math.random();"/>
大小,颜色,样式都可以根据自己需要调整,用的都是awt下的Color类(好冷门的GUI的东西)
总结一下patcha的优点:全浏览器兼容、低依赖整合方便、安全性足够,响应速度很快。
用到的jar包,也是唯一的一个jar包
http://download.csdn.net/detail/qq_36289377/9887404
阅读全文
0 0
- WEB项目总结(二)开源验证码patcha引入
- 网站安全之为Web项目添加验证码功能(二)
- SpringMVC_v02中的总结(web项目、java项目中引入Config.properties,加载hibernate映射文件的配置的区别)
- Web项目中引入Spring
- web项目中引入logback
- 【ExtJS】Web项目引入ExtJS
- web开发(二)之jsp文件的引入
- 如何在项目中引入oscache(二)
- Vue项目实战(二)- 引入JQuery等第三方库
- c#调试web service http头验证项目总结
- Android的开源项目总结( 二 )
- Android新浪微博-项目整理总结 二[使用WebView获取OAuth验证码]
- web项目登陆页面添加验证码
- Java WEB项目如何实现验证码
- web项目动态生成验证码
- 数据库项目无法引入system.web???
- 在web项目下引入hibernate配置文件
- IntelliJ IDEA (idea)引入eclipse web项目
- 带进度条的WKWebView
- oracle更改自动收集统计信息时间
- PHP简明教程-面向对象基础 2
- 【视觉-结构光三维重建-理论篇】结构光 三维重建----论文调研3
- [Leetcode] 254. Factor Combinations 解题报告
- WEB项目总结(二)开源验证码patcha引入
- python编写爬虫获取区域代码-递归获取所有子页面
- php5.6+Redis+Windows7安装 (phpstudy)
- ubuntu系统服务器下调用python中matplotlib问题
- ajax跨域访问--. No 'Access-Control-Allow-Origin
- android studio 引入so使用
- 文章标题
- 多线程(2)
- 类的特殊成员方法