验证码代码

Number.jsp

 1 <%@ page contentType="image/jpeg"
 2     import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"
 3     pageEncoding="utf-8"%>
 4 <%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜色
 5         Random random = new Random();
 6         if (fc > 255)
 7             fc = 255;
 8         if (bc > 255)
 9             bc = 255;
10         int r = fc + random.nextInt(bc - fc);
11         int g = fc + random.nextInt(bc - fc);
12         int b = fc + random.nextInt(bc - fc);
13         return new Color(r, g, b);
14     }
15 %>
16 <%
17     //设置页面不缓存
18     response.setHeader("Pragma", "No-cache");
19     response.setHeader("Cache-Control", "no-cache");
20     response.setDateHeader("Expires", 0);
21     // 在内存中创建图象
22     int width = 60, height = 20;
23     BufferedImage image = new BufferedImage(width, height,
24             BufferedImage.TYPE_INT_RGB);
25     // 获取图形上下文
26     Graphics g = image.getGraphics();
27     //生成随机类
28     Random random = new Random();
29     // 设定背景色
30     g.setColor(getRandColor(200, 250));
31     g.fillRect(0, 0, width, height);
32     //设定字体
33     g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
34     //画边框
35     //g.setColor(new Color());
36     //g.drawRect(0,0,width-1,height-1);
37     // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
38     g.setColor(getRandColor(160, 200));
39     for (int i = 0; i < 155; i++) {
40         int x = random.nextInt(width);
41         int y = random.nextInt(height);
42         int xl = random.nextInt(12);
43         int yl = random.nextInt(12);
44         g.drawLine(x, y, x + xl, y + yl);
45     }
46     // 取随机产生的认证码(4位数字)
47     String sRand = "";
48     for (int i = 0; i < 4; i++) {
49         String rand = String.valueOf(random.nextInt(10));
50         sRand += rand;
51         // 将认证码显示到图象中
52         g.setColor(new Color(20 + random.nextInt(110), 20 + random
53                 .nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
54         g.drawString(rand, 13 * i + 6, 16);
55     }
56     // 将认证码存入SESSION
57     session.setAttribute("numrand", sRand);
58     // 图象生效
59     g.dispose();
60     // 输出图象到页面
61     ImageIO.write(image, "JPEG", response.getOutputStream());
62     out.clear();
63     out = pageContext.pushBody();
64 %>

jsp页面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>用户登录</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <link href="css/common.css" rel="stylesheet" type="text/css" />
    <link href="css/style.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="js/login.js"></script>

    <script type="text/javascript">
        <%
            String msg = request.getParameter("msg");
            if("registerSuccess".equals(msg)){
                out.print("alert(‘注册成功,系统将自动跳转登录页‘);");
            }
            if("loginError".equals(msg)){
                out.print("alert(‘用户名密码错误,请重新登录‘);");
            }
            if("validateCodeError".equals(msg)){
                out.print("alert(‘验证码错误,请重新输入‘);");
            }
        %>
    </script>

  </head>

<body>
<div class="wrap">
<!-- main begin-->
 <div class="main">
   <div class="sidebar">
     <p><img src="images/img1.jpg" width="443" height="314"  /></p>
   </div>
   <div class="sidebarg">
     <form action="doLogin" method="post">
    <div class="login">
      <dl>
        <dt class="blues">用户登陆</dt>
        <dd><label for="name">用户名:</label>
            <input type="text" name="username" class="inputh" value="${username}" id="name"/></dd>
        <dd><label for="password">密 码:</label>
            <input type="password" name="userpassword" class="inputh" value="${userpassword}" id="password"/></dd>
        <dd>
           <label class="lf" for="passwords">验证码:</label>
           <input type="text" name="inputCode" class="inputh inputs lf" value="" id="passwords"/>
           <span class="wordp lf"><img id="validateCode" src="Number.jsp" width="96" height="27"  /></span>
           <span class="blues lf"><a id="changeCode" href="javascript:void(0);" title="">看不清</a></span>
        </dd>
        <dd>
           <input name=""  type="checkbox" id="rem_u"  />
           <span class="rem_u">下次自动登录</span>
        </dd>
        <dd class="buttom">
           <input name="" type="submit" value="登 录" class="spbg buttombg f14 lf" />
           <input id="register" name="" type="button" value="注 册" class="spbg buttombg f14 lf" />
           <span class="blues  lf"><a href="" title="">忘记密码?</a></span>
           <div class="cl"></div>
        </dd>

      </dl>
    </div>
    </form>
   </div>
  <div class="cl"></div>
 </div>
<!-- main end-->

<!-- footer begin-->
</div>
 <!--footer end-->
</body>
</html>

javas代码用于刷新验证码

$(function(){
    //请自行添加客户端验证

    $("#changeCode").click(function(event){
        $("#validateCode").attr("src","Number.jsp?ran"+Math.random());
        event.preventDefault();
        return false;    //传到登录界面
    });

    $("#register").click(function(){
        window.location.href = "register.jsp";//传达注册界面的验证码
    });
});

servlet代码,用于验证

 1 public void doPost(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         try {
 4             //此处可以添加用户输入验证的代码
 5
 6             String username = request.getParameter("username");
 7             String userpassword = request.getParameter("userpassword");
 8
 9             request.setAttribute("username", username);
10             request.setAttribute("userpassword", userpassword);
11
12             if(!request.getSession().getAttribute("numrand").equals(request.getParameter("inputCode"))){
13                 request.getRequestDispatcher("login.jsp?msg=validateCodeError").forward(request, response);
14             }else{
15                 IUserBiz biz = new UserBizImpl();
16                 Auctionuser user = biz.login(username, userpassword);
17
18                 if(user == null){
19                     request.getRequestDispatcher("login.jsp?msg=loginError").forward(request, response);
20                 }else{
21                     request.getSession().setAttribute("user", user);
22                     response.sendRedirect("auctionList");
23                 }
24             }
25
26
27
28         } catch (Exception e) {
29             // TODO Auto-generated catch block
30             e.printStackTrace();
31             request.setAttribute("message", e.getMessage());
32             request.getRequestDispatcher("error.jsp").forward(request,response);
33         }
34     }
时间: 2024-12-29 11:35:04

验证码代码的相关文章

asp.net中ashx生成验证码代码放在Linux(centos)主机上访问时无法显示问题

最近有个项目加入了验证码功能,就从自己博客以前的代码中找到直接使用,直接访问验证码页面报错如下: 源代码:asp.net中使用一般处理程序生成验证码 Application Exception System.ArgumentException The requested FontFamily could not be found [GDI+ status: FontFamilyNotFound] Description: HTTP 500.Error processing request. De

javascript实现的验证码代码实例

javascript实现的验证码代码实例:验证码大家应该不陌生,主要是为了网站的安全性,防止恶意注册和登陆.验证码实现的方式各有不同,下面是一段用javascript实现的验证码效果,供大家参考之用,希望能够给大家带来帮助.代码如下: <!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="ht

PHP基本的 验证码代码

header('content-type:image/png'); //创建画布并设置颜色,推荐使用下面那个方法 //$im=imagecreate($width,$height); $im=imagecreatetruecolor(200,100) or die('Cannot Initialize GD image'); //创建背景颜色 $bg=imagecolorallocate($im,255,255,255); $line=imagecolorallocatealpha($im,mt

ASP .NET登录界面用户验证码代码

//ASP .NET用户登录界面经常用到验证码代码如下 private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 Label4.Text=RandomNum(4); } public string RandomNum(int n) // { string strchar = "0,1,2,3,4,5,6,7,8,9" ; string[] VcArray = strchar.Split(

php 验证码代码

1.js代码 function fleshVerify(type){ //重载验证码 var timenow = new Date().getTime(); if (type) { $('verifyImg').src= '/os/index.php/Admin/Public/verify/adv/1/'+timenow; }else{ $('verifyImg').src= '/os/index.php/Admin/Public/verify/'+timenow; } }

调取创蓝253国际短信验证码-代码示例2

说明: 以下代码只是为了方便客户测试而提供的示例代码,客户可以根据自己的需要另行编写 该代码仅供学习和研究接口使用,只是提供了一个参考 require 'net/http' require 'uri' require 'json' params = { "account" => "", "password" => "a.123456", 手机号码,格式(区号+手机号码),例如:8615800000000,其中86为

2-13 如何解决验证码代码实战

from selenium import webdriverimport timeimport random#导入PIL模块和Image:from PIL import Image#导入expected_conditions预期包判断标题是否正确:from selenium.webdriver.support import expected_conditions as EC#导入WebDriverWaitfrom selenium.webdriver.support.wait import We

Java验证码代码

1 public class VerifyCodeController { 2 3 private int width = 90;//定义图片的width 4 private int height = 20;//定义图片的height 5 private int codeCount = 4;//定义图片上显示验证码的个数 6 private int xx = 15; 7 private int fontHeight = 18; 8 private int codeY = 16; 9 char[]

TP登陆验证码代码

public function chkcode() { $Verify=new \Think\Verify(array( 'fontSize'=>30, //验证码字体大小 'length' =>4, //验证码位数 'useNoise' =>TRUE, //关闭验证码杂点 )); $Verify->entry(); } <tr> <td>验证码:</td> <td> <input type="text" n