歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 運用Struts2.0實現頁面中的驗證碼

運用Struts2.0實現頁面中的驗證碼

日期:2017/3/1 10:14:46   编辑:Linux編程

<1>畫驗證碼核心類ValidateCodeAction

  1. package com.tarena.common.action;
  2. import java.awt.*;
  3. import java.awt.image.BufferedImage;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import javax.imageio.stream.ImageOutputStream;
  9. import com.opensymphony.xwork2.ActionContext;
  10. /**
  11. * 網頁中驗證碼的實現
  12. * @author JimmyZhang
  13. * @since 2012.5.10
  14. *
  15. */
  16. public class ValidateCodeAction {
  17. private ByteArrayInputStream inputStream;
  18. //默認的執行方法
  19. public String execute() throws Exception{
  20. Random r = new Random();
  21. //BufferedImage相當與緩存在內存中的圖像
  22. BufferedImage image =
  23. new BufferedImage(60,//繪圖區域的長度
  24. 20,//繪圖區域的高度
  25. BufferedImage.TYPE_INT_RGB);
  26. //獲取繪圖工具Graphiscs
  27. Graphics g = image.getGraphics();
  28. //設置繪圖顏色
  29. g.setColor(new Color(r.nextInt(255),
  30. r.nextInt(255),
  31. r.nextInt(255)));
  32. //從原點(0,0)填充繪圖區域
  33. g.fillRect(0, 0, 60, 20);
  34. //生成一個隨機的字符串(5位數字)
  35. String number = String.valueOf(r.nextInt(99999));
  36. //將number繪制在image中
  37. g.setColor(new Color(0,0,0));
  38. g.drawString(number, 5, 15);
  39. //將number保存在Session中
  40. ActionContext ac = ActionContext.getContext();
  41. ac.getSession().put("vcode", number);
  42. //畫干擾線
  43. for(int i=0; i<3;i++){
  44. drawLine(g,r);
  45. }
  46. //寫入到字節輸出流中
  47. ByteArrayOutputStream output = new ByteArrayOutputStream();
  48. ImageOutputStream imageOutput =
  49. ImageIO.createImageOutputStream(output);
  50. //將圖像image寫入到imageOutput中
  51. ImageIO.write(image, "jpeg", imageOutput);
  52. //根據output構建inputStream
  53. inputStream = new ByteArrayInputStream(
  54. output.toByteArray());
  55. //對象之間的轉換--image-->ByteArrayOutStream-->ByteArrayInputStream
  56. return "success";
  57. }
  58. //輔助方法,用於繪制一條干擾線
  59. private void drawLine(Graphics g,Random r){
  60. g.setColor(new Color(r.nextInt(255),
  61. r.nextInt(255),
  62. r.nextInt(255)));
  63. //drawLine(x1,y1,x2,y2)
  64. g.drawLine(
  65. r.nextInt(60), r.nextInt(20),
  66. r.nextInt(60), r.nextInt(20));
  67. }
  68. public ByteArrayInputStream getInputStream() {
  69. return inputStream;
  70. }
  71. public void setInputStream(ByteArrayInputStream inputStream) {
  72. this.inputStream = inputStream;
  73. }
  74. }
Copyright © Linux教程網 All Rights Reserved