2019独角兽企业重金招聘Python工程师标准>>>

生成验证码的方式有很多,个人认为较为灵活方便的是Kaptcha ,他是基于SimpleCaptcha的开源项目。使用Kaptcha 生成验证码十分简单并且参数可以进行自定义。只需添加jar包配置下就可以使用。kaptcha所有配置都可以通过web.xml来完成,如果项目使用了Spring MVC,那么实现方式会略有不同。

一、Servlet项目

1、添加jar包依赖

maven项目,在pom.xml中添加dependency

<!-- kaptcha -->
<dependency>  <groupId>com.google.code.kaptcha</groupId>  <artifactId>kaptcha</artifactId>  <version>2.3.2</version>
</dependency>

非maven项目,在官网下载kaptcha的jar包,然后添加到项目lib库中。

下载地址:http://code.google.com/p/kaptcha/downloads/list

2、配置web.xml

<servlet>  <servlet-name>Kaptcha</servlet-name>  <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>  <servlet-name>Kaptcha</servlet-name>  <url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>

注:url-pattern 自定义

kaptcha的参数都有默认值,如果要配置kaptcha,在init-param增加响应的参数即可

<servlet>  <servlet-name>Kaptcha</servlet-name>  <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>  <init-param>  <param-name>kaptcha.image.width</param-name>  <param-value>200</param-value>  <description>Width in pixels of the kaptcha image.</description>  </init-param>  <init-param>  <param-name>kaptcha.image.height</param-name>  <param-value>50</param-value>  <description>Height in pixels of the kaptcha image.</description>  </init-param>  <init-param>  <param-name>kaptcha.textproducer.char.length</param-name>  <param-value>4</param-value>  <description>The number of characters to display.</description>  </init-param>  <init-param>  <param-name>kaptcha.noise.impl</param-name>  <param-value>com.google.code.kaptcha.impl.NoNoise</param-value>  <description>The noise producer.</description>  </init-param>
</servlet>

3、jsp代码

<script type="text/javascript">
$(function(){  //生成验证码         $('#kaptchaImage').click(function () {  $(this).hide().attr('src', '/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); });
});   window.onbeforeunload = function(){  //关闭窗口时自动退出  if(event.clientX>360&&event.clientY<0||event.altKey){     alert(parent.document.location);  }
};  function changeCode() {  //刷新$('#kaptchaImage').hide().attr('src', '/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn();  event.cancelBubble=true;
}
</script> <div class="form-group">  <label>验证码 </label> <input name="j_code" type="text" id="kaptcha" maxlength="4" class="form-control" /><br/> <img src="/code/captcha-image" id="kaptchaImage"  style="margin-bottom: -3px"/>       <a href="#" onclick="changeCode()">看不清?换一张</a>
</div>

二、Spring mvc 中使用kaptcha

1、spring 配置文件 applicationContext.xml

<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  <property name="config">  <bean class="com.google.code.kaptcha.util.Config">  <constructor-arg>  <props>  <prop key="kaptcha.border">yes</prop>  <prop key="kaptcha.border.color">105,179,90</prop>  <prop key="kaptcha.textproducer.font.color">blue</prop>  <prop key="kaptcha.image.width">125</prop>  <prop key="kaptcha.image.height">45</prop>  <prop key="kaptcha.textproducer.font.size">45</prop>  <prop key="kaptcha.session.key">code</prop>  <prop key="kaptcha.textproducer.char.length">4</prop>  <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  </props>  </constructor-arg>  </bean>  </property>  </bean>

2、Controller的实现

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;  @Controller
@RequestMapping("/code")
public class CaptchaController {  @Autowired  private Producer captchaProducer = null;  @RequestMapping(value = "captcha-image")  public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {  HttpSession session = request.getSession();  String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);  System.out.println("验证码: " + code );  response.setDateHeader("Expires", 0);  response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  response.addHeader("Cache-Control", "post-check=0, pre-check=0");  response.setHeader("Pragma", "no-cache");  response.setContentType("image/jpeg");  String capText = captchaProducer.createText();  session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  BufferedImage bi = captchaProducer.createImage(capText);  ServletOutputStream out = response.getOutputStream();  ImageIO.write(bi, "jpg", out);  try {  out.flush();  } finally {  out.close();  }  return null;  }
}

3、kaptcha可配置项

kaptcha.border  是否有边框  默认为true  我们可以自己设置yes,no
kaptcha.border.color   边框颜色   默认为Color.BLACK
kaptcha.border.thickness  边框粗细度  默认为1
kaptcha.producer.impl   验证码生成器  默认为DefaultKaptcha
kaptcha.textproducer.impl   验证码文本生成器  默认为DefaultTextCreator
kaptcha.textproducer.char.string   验证码文本字符内容范围  默认为abcde2345678gfynmnpwx
kaptcha.textproducer.char.length   验证码文本字符长度  默认为5
kaptcha.textproducer.font.names    验证码文本字体样式  默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
kaptcha.textproducer.font.size   验证码文本字符大小  默认为40
kaptcha.textproducer.font.color  验证码文本字符颜色  默认为Color.BLACK
kaptcha.textproducer.char.space  验证码文本字符间距  默认为2
kaptcha.noise.impl    验证码噪点生成对象  默认为DefaultNoise
kaptcha.noise.color   验证码噪点颜色   默认为Color.BLACK
kaptcha.obscurificator.impl   验证码样式引擎  默认为WaterRipple
kaptcha.word.impl   验证码文本字符渲染   默认为DefaultWordRenderer
kaptcha.background.impl   验证码背景生成器   默认为DefaultBackground
kaptcha.background.clear.from   验证码背景颜色渐进   默认为Color.LIGHT_GRAY
kaptcha.background.clear.to   验证码背景颜色渐进   默认为Color.WHITE
kaptcha.image.width   验证码图片宽度  默认为200
kaptcha.image.height  验证码图片高度  默认为50

转载于:https://my.oschina.net/ydsakyclguozi/blog/533180

Spring mvc 中使用 kaptcha 验证码相关推荐

  1. 彻底解决Spring mvc中时间的转换和序列化等问题

    彻底解决Spring mvc中时间的转换和序列化等问题 参考文章: (1)彻底解决Spring mvc中时间的转换和序列化等问题 (2)https://www.cnblogs.com/childkin ...

  2. spring mvc中的@propertysource

    在spring mvc中,在配置文件中的东西,可以在java代码中通过注解进行读取了: @PropertySource  在spring 3.1中开始引入 比如有配置文件 config.propert ...

  3. spring_在Spring MVC中使用多个属性文件

    spring 每个人都听说过将单个Web应用程序组合成一个大型Web应用程序的门户. 门户软件的工作原理类似于mashup -来自多个来源的内容是在单个服务中获取的,大部分都显示在单个网页中. 门户软 ...

  4. Spring MVC中处理Request和Response的策略

    前沿技术早知道,弯道超车有希望 积累超车资本,从关注DD开始 作者:码农小胖哥, 图文编辑:xj 来源:https://mp.weixin.qq.com/s/3eFygsiVl8dC2nRy8_8n5 ...

  5. Spring MVC 中的 forward 和 redirect

    Spring MVC 中,我们在返回逻辑视图时,框架会通过 viewResolver 来解析得到具体的 View,然后向浏览器渲染.假设逻辑视图名为 hello,通过配置,我们配置某个 ViewRes ...

  6. Spring MVC中获取当前项目的路径

    Spring MVC中获取当前项目的路径 在web.xml中加入以下内容 <!--获取项目路径--><context-param><param-name>webAp ...

  7. Spring 2.5:Spring MVC中的新特性

    转载说明:infoQ就是牛人多,看人家去年就把Spring2.5注视驱动的MVC写出来了,还是这么详细,我真是自叹不如,今天偶尔看到这篇文章非常认真的拜读了2遍,简直是茅厕顿开啊....\(^o^)/ ...

  8. Spring MVC中的二三事

    HandlerMapping和HandlerAdapter 这个两个组件应该算是spring mvc中最重要的几个组件之一了,当一个请求到达DispatcherSerlvet后,spring mvc就 ...

  9. 在Spring MVC中使用Apache Shiro安全框架

    我们在这里将对一个集成了Spring MVC+Hibernate+Apache Shiro的项目进行了一个简单说明.这个项目将展示如何在Spring MVC 中使用Apache Shiro来构建我们的 ...

最新文章

  1. 暗渡陈仓:用低消耗设备进行破解和渗透测试1.2.2 渗透测试工具集
  2. androidstuido_schooltest_4_phone
  3. stateflow中向量与矩阵
  4. Fiori launchpad里Enter Group name这个tile是怎么配置出来的
  5. 与JSP的初次邂逅……
  6. 【Github】怎么在README.md中添加图片?
  7. 南大用“推荐算法”分宿舍666,新生配好舍友美滋滋
  8. C语言 指针与字符串
  9. Effective Modern C++ 第二章 auto的使用
  10. ThinkPHP扩展,实现Redis的CURD操作。
  11. win10怎么安装ie11
  12. 如何把图片裁剪为圆形
  13. VRay Next for SketchUp 赋予材质常见问题
  14. VMware上传超过4GB文件失败
  15. 本地连接测试mysql失败,提示 flush hosts;
  16. zerg发出了第一个报文,纪念一下!!!
  17. Axure--使用阿里云搭建自己的原型发布站点
  18. 【Python脚本进阶】2.3、利用FTP与Web批量抓“ 肉机”(终)
  19. 从潞晨到世界名校,实习生火热招聘中
  20. [RK3568 Android11] 教程之USB OTG模式切换

热门文章

  1. 如何快速更改电脑ip地址【图文教程】?
  2. 【Security】操作系统安全
  3. 微信群发软件哪个好?好用的群发软件选择
  4. Linux的入门学习
  5. 人在旅途——》张家界之旅:20190420
  6. 编辑视频贴纸软件_视频贴纸软件介绍
  7. html js不触发_「万字整理 」这里有一份Node.js入门指南和实践,请注意查收 ??
  8. 重入锁:ReentrantLock
  9. 杰里之104X之输出 3 路 PMW【篇】
  10. 至联云讲解《关于IPFS我们应该知道哪些真相?》