0
点赞
收藏
分享

微信扫一扫

Web app 验证码实现

窗外路过了谁 2023-03-30 阅读 75


1. 在jsp页面添加验证码           

<tr>
                                 <td height="28"><table width="100%" border="0R" cellspacing="0" cellpadding="1">
                                   <tr>
                                     <td width="20"> </td>
                                     <td width="100"> <span class="STYLE2"><strong>验证码</strong></span></td>
                                     <td width="150"><span class="STYLE2">
                                       <INPUT type="text" name="param_Validate" size="6"
           value=""  maxlength="10">
           <img src="jsp/image.jsp" align='absmiddle' />
                                     </span></td>
                                     <td><span class="STYLE2">(请将图片中的数字填入框中)</span></td>
                                   </tr>
                                 </table></td>
                               </tr>

             


2. 加载jsp/image.jsp, 使用JavaBean

<%@ page contentType="image/jpeg;charset=UTF-8" import="javax.imageio.*"%>
 <jsp:useBean id="image" scope="session" class="cn.com.xxx.fe.servlet.user.ValidationImage"/>
 <%
 //设置页面不缓存
 //response.setHeader("Pragma","No-cache");
 //response.setHeader("Cache-Control","no-cache");
 //response.setDateHeader("Expires", 0);// 输出图象到页面
 ImageIO.write(image.creatImage(), "JPEG", response.getOutputStream());
 out.clear();
 out = pageContext.pushBody();// 将认证码存入SESSION
 session.setAttribute("VERIFY_YCODE",image.sRand);
 %>3. ValidationImage 功能Bean实现
import java.awt.*;
 import java.awt.image.*;
 import java.io.Serializable;
 import java.util.*;
 //v100+ start
 public class ValidationImage implements Serializable{public String sRand = "";
public Color getRandColor(int fc, int bc) {
   Random random = new Random();
   if (fc > 255)
    fc = 255;
   if (bc > 255)
    bc = 255;
   int r = fc + random.nextInt(bc - fc);
   int g = fc + random.nextInt(bc - fc);
   int b = fc + random.nextInt(bc - fc);
   return new Color(r, g, b);
  }public BufferedImage creatImage() {
 int width = 60, height = 20;
   BufferedImage image = new BufferedImage(width, height,
     BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics();
 Random random = new Random();
 g.setColor(getRandColor(200, 250));
   g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
 g.setColor(getRandColor(160, 200));
   for (int i = 0; i < 155; i++) {
    int x = random.nextInt(width);
    int y = random.nextInt(height);
    int xl = random.nextInt(12);
    int yl = random.nextInt(12);
    g.drawLine(x, y, x + xl, y + yl);
   } sRand = "";
 for (int i = 0; i < 4; i++) {
    String rand = String.valueOf(random.nextInt(10));
    sRand += rand;
    g.setColor(new Color(20 + random.nextInt(110), 20 + random
      .nextInt(110), 20 + random.nextInt(110)));
    g.drawString(rand, 13 * i + 6, 16);
   }
   g.dispose();
   return image;
  }
 }
 //v100+ end

举报

相关推荐

0 条评论