验证码

作者: _FireFly_ | 来源:发表于2021-03-17 22:08 被阅读0次
登录页面

登录页面

<%@ page contentType="text/html; charset=utf-8"%>


<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
  <head>
    <title>前台登录</title>
    <base href="<%=basePath%>">
    <link style="text/css" rel="stylesheet" href="css/style.css">
      <script type="text/javascript">
              //点击验证码图片更换验证码
          function reloadcheckcode(img){
              img.src = "images/checkcode.jpg?"+Math.random();
          }
          if(window.parent != window){
              window.parent.location = window.location;
          }
      </script>
  </head>
  <body bgcolor="#AA8D60">
    <center>
      <form action="userServlet" METHOD="get" id="aa" focus.="userName">
          <input type="hidden" name="method" size="40" value="userLogin">
          <table background="images/login/loginB.jpg" width="500" height="500" border="0" cellspacing="0" cellpadding="0" style="margin-top:90">
              <tr height="175">
                  <td colspan="2" style="text-indent:145">

                  </td>
              </tr>
              <tr height="45">
                  <td align="right" width="35%">用户名:</td>
                  <td>&nbsp;&nbsp;<input type="text" name="username" size="30"  />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="user/reg.do?method=userReg">[用户注册]</a></td>
              </tr>
              <tr height="30">
                  <td align="right">密&nbsp;&nbsp;码:</td>
                  <td>&nbsp;&nbsp;<input type="password"  name="password" redisplay="false" size="30"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="index.jsp">[返回首页]</a></td>
              </tr>

              <tr height="40">
                  <td align="right"><img src="images/checkcode.jpg" id="safecode" onclick="reloadcheckcode(this)" title="如果看不清,请点击本图片换一张"/></td>
                  <td>&nbsp;&nbsp;<input type="text"  name="checkCode" redisplay="false" size="30"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="index.jsp">[返回首页]</a></td>
              </tr>

              <tr height="60">
                  <td colspan="2" >${errorMessage}</td>
              </tr>

              <tr>
                  <td></td>
                  <td>
                      &nbsp;
                      <image src="images/login/bsup.gif" onmousedown="this.src='images/login/bsdown.gif'" onclick="document.getElementById('aa').submit()" onmouseup="this.src='images/login/bsup.gif'"/>
                      <image src="images/login/brup.gif" onmousedown="this.src='images/login/brdown.gif'" onmouseup="this.src='images/login/brup.gif'" />
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      
                  </td>                  
              </tr>
          </table>
          <table width="500" border="0" width="350" cellspacing="0" cellpadding="0">
              <tr><td colspan="2"><img src="images/login/loginE.jpg"></td></tr>                               
          </table>
      </form>
    </center>
  </body>
</html>

生成验证码的servlet类

package com.servlets;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class CheckcodeServlet extends HttpServlet {

    private int width;//验证码的宽度
    private int height; //验证码的高度
    private int number;  //验证码的位数
    private String codes;  //验证码的内容     ABCDEFGHIJKLMNOPQRSTUVWXYZ
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        //从servlet的配置参数中获取设定验证码的宽高位数和验证码的内容  
        //比如这里就是从26个字母中随机选择其中的4个
        width = Integer.parseInt(config.getInitParameter("width"));
        height = Integer.parseInt(config.getInitParameter("height"));
        number = Integer.parseInt(config.getInitParameter("number"));
        //codes内容为26个字母   ABCDEFGHIJKLMNOPQRSTUVWXYZ   通过读取配置内容在servlet的xml中
        codes = config.getInitParameter("codes");
    }

    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置我输出的格式,是一张图片的格式
        response.setContentType("image/jpeg");
        //创建了一个带缓冲功能的图片对象
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //Graphics2D这个东西,相当于是一个画笔
        Graphics2D g = image.createGraphics();
        
        //给画笔添加颜色    这里画笔被填上白色墨水  用来画验证码的白色背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        
        //给画笔再添加黑色    这里用来画验证码的黑色边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width-1, height-1);
        
        Random random = new Random();
        

        //这里根据验证码的总宽度来确定每个验证码应该占据的位置大小
        //比如一共四个验证码,宽度为13,高为6   x=3 y=2 则 A出现在坐标(1,2) B(4,2) C(7,2) D(10,2)
        int x = (width - 1) / number;
        int y = height -4;
        
        //验证码的内容,用来存在session中与用户登录时输入的验证码进行对比
        StringBuffer sb = new StringBuffer();
        
        //这里来随机生成4个字母
        for(int i=0; i<number; i++){
            String code = String.valueOf( codes.charAt( random.nextInt(codes.length())) );
            
            //生成的字母颜色为随机颜色
            int red = random.nextInt(255);
            int green = random.nextInt(255);
            int blue = random.nextInt(255);
            g.setColor(new Color(red,green,blue));
            
            //设置验证码的字体  粗细  大小
            Font font = new Font("Arial",Font.BOLD,random(height/2,height));
            g.setFont(font);
            //比如一共四个验证码,宽度为13,高为6   x=3 y=2 则 A出现在坐标(1,2) B(4,2) C(7,2) D(10,2)
            g.drawString(code, i * x + 1, y);
            
            sb.append(code);
        }
        
        //将生成的验证码存入session中    用来和用户在登录页面输入的进行比对
        request.getSession().setAttribute("codes", sb.toString());

        //在验证码图片上画50个半径为1的随机颜色小点  用来干扰识别
        for(int i=0; i<50; i++){
            int red = random.nextInt(255);
            int green = random.nextInt(255);
            int blue = random.nextInt(255);
            g.setColor(new Color(red,green,blue));
            g.drawOval(random.nextInt(width), random.nextInt(height), 1, 1);
        }
        
        OutputStream out = response.getOutputStream();
        //创建一个和指定输出流关联的JPEGImageEncoder对象,相当于把image作为一个输出流进行输出
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(image);

        out.flush();
        out.close();
        
    }
    

    private int random(int min,int max){
        int m = new Random().nextInt(999999) % (max - min);
        return m + min;
    }

}

CheckcodeServlet的xml配置

 <servlet>
        <servlet-name>CheckcodeServlet</servlet-name>
        <servlet-class>com.servlets.CheckcodeServlet</servlet-class>
        <init-param>
            <param-name>width</param-name>
            <param-value>44</param-value>
        </init-param>
        <init-param>
            <param-name>height</param-name>
            <param-value>20</param-value>
        </init-param>
        <init-param>
            <param-name>number</param-name>
            <param-value>4</param-value>
        </init-param>
        <init-param>
            <param-name>codes</param-name>
            <param-value>ABCDEFGHIJKLMNOPQRSTUVWXYZ</param-value>
        </init-param>
    </servlet>

相关文章

网友评论

      本文标题:验证码

      本文链接:https://www.haomeiwen.com/subject/spqycltx.html