struts2的配置 和代码
1.生成图片流
类名:VerifyCodeUtils
1 /** 2 * 生成图片流 3 * @author Administrator 4 * 5 */ 6 import java.awt.Color; 7 import java.awt.Font; 8 import java.awt.Graphics; 9 import java.awt.Graphics2D; 10 import java.awt.RenderingHints; 11 import java.awt.geom.AffineTransform; 12 import java.awt.image.BufferedImage; 13 import java.io.File; 14 import java.io.FileOutputStream; 15 import java.io.IOException; 16 import java.io.OutputStream; 17 import java.util.Arrays; 18 import java.util.Random; 19 20 import javax.imageio.ImageIO; 21 22 public class VerifyCodeUtils{ 23 24 //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符 25 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; 26 private static Random random = new Random(); 27 28 29 /** 30 * 使用系统默认字符源生成验证码 31 * @param verifySize 验证码长度 32 * @return 33 */ 34 public static String generateVerifyCode(int verifySize){ 35 return generateVerifyCode(verifySize, VERIFY_CODES); 36 } 37 /** 38 * 使用指定源生成验证码 39 * @param verifySize 验证码长度 40 * @param sources 验证码字符源 41 * @return 42 */ 43 public static String generateVerifyCode(int verifySize, String sources){ 44 if(sources == null || sources.length() == 0){ 45 sources = VERIFY_CODES; 46 } 47 int codesLen = sources.length(); 48 Random rand = new Random(System.currentTimeMillis()); 49 StringBuilder verifyCode = new StringBuilder(verifySize); 50 for(int i = 0; i < verifySize; i++){ 51 verifyCode.append(sources.charAt(rand.nextInt(codesLen-1))); 52 } 53 return verifyCode.toString(); 54 } 55 56 /** 57 * 生成随机验证码文件,并返回验证码值 58 * @param w 59 * @param h 60 * @param outputFile 61 * @param verifySize 62 * @return 63 * @throws IOException 64 */ 65 public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{ 66 String verifyCode = generateVerifyCode(verifySize); 67 outputImage(w, h, outputFile, verifyCode); 68 return verifyCode; 69 } 70 71 /** 72 * 输出随机验证码图片流,并返回验证码值 73 * @param w 74 * @param h 75 * @param os 76 * @param verifySize 77 * @return 78 * @throws IOException 79 */ 80 public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{ 81 String verifyCode = generateVerifyCode(verifySize); 82 outputImage(w, h, os, verifyCode); 83 return verifyCode; 84 } 85 86 /** 87 * 生成指定验证码图像文件 88 * @param w 89 * @param h 90 * @param outputFile 91 * @param code 92 * @throws IOException 93 */ 94 public static void outputImage(int w, int h, File outputFile, String code) throws IOException{ 95 if(outputFile == null){ 96 return; 97 } 98 File dir = outputFile.getParentFile(); 99 if(!dir.exists()){ 100 dir.mkdirs(); 101 } 102 try{ 103 outputFile.createNewFile(); 104 FileOutputStream fos = new FileOutputStream(outputFile); 105 outputImage(w, h, fos, code); 106 fos.close(); 107 } catch(IOException e){ 108 throw e; 109 } 110 } 111 112 /** 113 * 输出指定验证码图片流 114 * @param w 115 * @param h 116 * @param os 117 * @param code 118 * @throws IOException 119 */ 120 public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{ 121 int verifySize = code.length(); 122 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 123 Random rand = new Random(); 124 Graphics2D g2 = image.createGraphics(); 125 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); 126 Color[] colors = new Color[5]; 127 Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, 128 Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, 129 Color.PINK, Color.YELLOW }; 130 float[] fractions = new float[colors.length]; 131 for(int i = 0; i < colors.length; i++){ 132 colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; 133 fractions[i] = rand.nextFloat(); 134 } 135 Arrays.sort(fractions); 136 137 g2.setColor(Color.GRAY);// 设置边框色 138 g2.fillRect(0, 0, w, h); 139 140 Color c = getRandColor(200, 250); 141 g2.setColor(c);// 设置背景色 142 g2.fillRect(0, 2, w, h-4); 143 144 //绘制干扰线 145 Random random = new Random(); 146 g2.setColor(getRandColor(160, 200));// 设置线条的颜色 147 for (int i = 0; i < 20; i++) { 148 int x = random.nextInt(w - 1); 149 int y = random.nextInt(h - 1); 150 int xl = random.nextInt(6) + 1; 151 int yl = random.nextInt(12) + 1; 152 g2.drawLine(x, y, x + xl + 40, y + yl + 20); 153 } 154 155 // 添加噪点 156 float yawpRate = 0.05f;// 噪声率 157 int area = (int) (yawpRate * w * h); 158 for (int i = 0; i < area; i++) { 159 int x = random.nextInt(w); 160 int y = random.nextInt(h); 161 int rgb = getRandomIntColor(); 162 image.setRGB(x, y, rgb); 163 } 164 165 shear(g2, w, h, c);// 使图片扭曲 166 167 g2.setColor(getRandColor(100, 160)); 168 int fontSize = h-4; 169 Font font = new Font("Algerian", Font.ITALIC, fontSize); 170 g2.setFont(font); 171 char[] chars = code.toCharArray(); 172 for(int i = 0; i < verifySize; i++){ 173 AffineTransform affine = new AffineTransform(); 174 affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2); 175 g2.setTransform(affine); 176 g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10); 177 } 178 179 g2.dispose(); 180 ImageIO.write(image, "jpg", os); 181 } 182 183 private static Color getRandColor(int fc, int bc) { 184 if (fc > 255) 185 fc = 255; 186 if (bc > 255) 187 bc = 255; 188 int r = fc + random.nextInt(bc - fc); 189 int g = fc + random.nextInt(bc - fc); 190 int b = fc + random.nextInt(bc - fc); 191 return new Color(r, g, b); 192 } 193 194 private static int getRandomIntColor() { 195 int[] rgb = getRandomRgb(); 196 int color = 0; 197 for (int c : rgb) { 198 color = color << 8; 199 color = color | c; 200 } 201 return color; 202 } 203 204 private static int[] getRandomRgb() { 205 int[] rgb = new int[3]; 206 for (int i = 0; i < 3; i++) { 207 rgb[i] = random.nextInt(255); 208 } 209 return rgb; 210 } 211 212 private static void shear(Graphics g, int w1, int h1, Color color) { 213 shearX(g, w1, h1, color); 214 shearY(g, w1, h1, color); 215 } 216 217 private static void shearX(Graphics g, int w1, int h1, Color color) { 218 219 int period = random.nextInt(2); 220 221 boolean borderGap = true; 222 int frames = 1; 223 int phase = random.nextInt(2); 224 225 for (int i = 0; i < h1; i++) { 226 double d = (double) (period >> 1) 227 * Math.sin((double) i / (double) period 228 + (6.2831853071795862D * (double) phase) 229 / (double) frames); 230 g.copyArea(0, i, w1, 1, (int) d, 0); 231 if (borderGap) { 232 g.setColor(color); 233 g.drawLine((int) d, i, 0, i); 234 g.drawLine((int) d + w1, i, w1, i); 235 } 236 } 237 238 } 239 240 private static void shearY(Graphics g, int w1, int h1, Color color) { 241 242 int period = random.nextInt(40) + 10; // 50; 243 244 boolean borderGap = true; 245 int frames = 20; 246 int phase = 7; 247 for (int i = 0; i < w1; i++) { 248 double d = (double) (period >> 1) 249 * Math.sin((double) i / (double) period 250 + (6.2831853071795862D * (double) phase) 251 / (double) frames); 252 g.copyArea(i, 0, 1, h1, 0, (int) d); 253 if (borderGap) { 254 g.setColor(color); 255 g.drawLine(i, (int) d, i, 0); 256 g.drawLine(i, (int) d + h1, i, h1); 257 } 258 259 } 260 261 } 262 public static void main(String[] args) throws IOException{ 263 File dir = new File("F:/verifies"); 264 int w = 200, h = 80; 265 266 String verifyCode = generateVerifyCode(4); 267 File file = new File(dir, verifyCode + ".jpg"); 268 outputImage(w, h, file, verifyCode); 269 } 270 }
2.图片生成的类:
类名:CommonAction
1 package cn.xxx.common.test; 2 3 import java.io.IOException; 4 5 import javax.servlet.http.HttpSession; 6 7 import org.springframework.context.annotation.Scope; 8 import org.springframework.stereotype.Component; 9 10 import cn.sxt.common.action.BaseAction; 11 @Component("commonAction") 12 @Scope("prototype") 13 public class CommonAction{ 14 /** 15 * 生成随机图片 验证码 16 * @return 17 * @throws IOException 18 */ //randImg方法 (JSP页面 a标签的src访问此方法) 19 public String randImg() throws IOException{ 20 response.setHeader("Pragma", "No-cache"); 21 response.setHeader("Cache-Control", "no-cache"); 22 response.setDateHeader("Expires", 0); 23 response.setContentType("image/jpeg"); 24 25 //生成随机字串 26 String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 27 //存入会话session 28 HttpSession session = request.getSession(true); 29 session.setAttribute("rand", verifyCode.toLowerCase()); 30 //生成图片 31 int w = 200, h = 80; 32 VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); 33 return null; 34 } 35 }
3:JSP页面展示页
Login.jsp
1 <label>验证码:</label> 2 <input class="code" name="code" type="text" size="5" /> 3 <a href="javascript:void(0)"> //这里是对应生成图片的action 4 <span><img id="imgId" onclick="refreshImg()" src="common_randImg.action" alt="" width="75" height="24" /></span> 5 </a>
4。struts2的配置
1 <action name="common_*" class="commonAction" method="{1}"> 2 <result name="{1}">/common/{1}.jsp</result> 3 </action> 4 </package>
注意:
<result name="{1}">/common/{1}.jsp</result> 是把图片输出到的Jsp页面。 需要创建一个空的JSP页面(直接创建jsp页面即可。名字一定要正确)