JSP+Servlet实现图片验证码

187 篇文章 0 订阅
97 篇文章 0 订阅

转自:https://blog.csdn.net/kkorkk/article/details/54292427

 

 

我们在登录或者注册的过程中,常常会发现有验证码的存在,今天我们自己动手来实现一个图片验证码。

 

首先,我们的验证码图片是在JSP页面中展示的,所以先从JSP页面着手。直接上代码。

login.jsp

 

[html] view plain copy

  1. <code class="language-html"> <body>  
  2.         <h2>欢迎登陆</h2><br>  
  3.         <form action="<%= request.getContextPath() %>/servlet/LoginServlet" method="get">  
  4.             <input type="text" name="validateCode">  
  5.             <img alt="点击更换验证码" src="<%= request.getContextPath() %>/servlet/Functio<span>          </span>nServlet" id="img" οnclick="reloadImg()">  
  6.             <input type="submit" value="提交" >  
  7.         </form>  
  8.           
  9.   </body>  
  10.   <script type="text/javascript">  
  11.     function reloadImg(){  
  12.         var time = new Date().getTime();  
  13.         document.getElementById("img").src="<%= request.getContextPath()%>/servlet/FunctionServlet?d="+time;  
  14.     }  
  15.   </script>  
  16. </code>  


其中,LoignServlet是一个验证用户输入的验证码的Servlet,用户输入的表单信息将提交到这个Servlet。img的src由FunctionServlet提供,点击验证码将会更换一张新的验证码,实际上这是由JavaScript实现的,很简单。
再来看主角--FunctionServlet--具体生成验证码的Servlet。先上代码。

 

FunctionServlet.java

 

 
  1. //定义随机字母库

  2. static final char[] CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

  3.  
  4. //得到一个4位的随机字符数组

  5. public static Random random = new Random();

  6. static String getRandomString(){

  7. StringBuffer randomString = new StringBuffer();

  8. for(int i=0;i<4;i++){

  9. randomString.append(CHARS[random.nextInt(CHARS.length)]);

  10. }

  11. return randomString.toString();

  12. }

  13. //获得随机颜色

  14. static Color getRandomColor(){

  15. return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));

  16. }

  17.  
  18. public void doGet(HttpServletRequest request, HttpServletResponse response)

  19. throws ServletException, IOException {

  20. response.setContentType("image/jpeg"); //设置类型

  21. String randomString = this.getRandomString(); //得到一个4位的验证码

  22. request.getSession().setAttribute("randomString", randomString); //将验证字符串保存到会话中

  23. int width=80,height=25; //设置验证码的宽高

  24. Color c = this.getRandomColor(); //得到一种随机颜色

  25. BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

  26. Graphics2D g = bi.createGraphics();

  27. g.fillRect(0, 0, width, height); //此行缺少,图片背景变为黑色

  28. g.setColor(c);

  29. g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));

  30. g.drawString(randomString, 20, 20);

  31. //设置图片噪点

  32. for(int i=0;i<20;i++){

  33. int x = random.nextInt(width);

  34. int y = random.nextInt(height);

  35. bi.setRGB(x, y,(int)(Math.random()*255));

  36. }

  37. //设置图片干扰线

  38. for (int i = 0; i < 6; i++) {

  39. //随机获取干扰线的起点和终点

  40. int xstart = (int)(Math.random() * 80);

  41. int ystart = (int)(Math.random() * 25);

  42. int xend = (int)(Math.random() * 80);

  43. int yend = (int)(Math.random() * 25);

  44. g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

  45. g.drawLine(xstart, ystart, xend, yend);

  46. }

  47. //输出验证码图片

  48. ImageIO.write(bi, "JPG", response.getOutputStream());

  49. }

具体思路并不复杂,先生成一个BufferImage对象,然后由BufferImage生成一个Graphics2D对象,接着往BufferImage对象中设置字符,之后再在Graphics2D对象中设置随机噪点和随机线条;最后输出整张图片。

 

再看LoginServlet,先上代码。

LoginServlet.java

 

 
  1. public void doGet(HttpServletRequest request, HttpServletResponse response)

  2. throws ServletException, IOException {

  3.  
  4. response.setContentType("text/html;charset=utf-8"); //少了此行文字乱码

  5. String imageCode = (String) request.getSession().getAttribute("randomString");

  6. String validateCode = (String) request.getParameter("validateCode");

  7. //验证用户输入的验证码--不分大小写

  8. if(imageCode.equalsIgnoreCase(validateCode)){

  9. response.getWriter().print("登陆成功!");

  10. }else{

  11. response.getWriter().print("登陆失败!");

  12. }

  13. }

这个比较简单,思路就是从login.jsp中获取用户输入的验证码,与session中保存的字符相比较,再输出比较结果。

 

最后,别忘了配置web.xml,如果是使用MyEclipse,软件会自动帮你配置好。

上结果图。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值