java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java web验证码

java web验证码实现代码分享

作者:没头没脑没烦恼

这篇文章主要为大家分享了java web验证码的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

验证码的作用:通常的登录或者注册系统时,都会要求用户输入验证码,以此区别用户行为和计算机程序行为,目的是有人防止恶意注册、暴力破解密码等。

实现验证码的思路:用 server 实现随机生成数字和字母组成图片的功能,用 jsp 页面实现显示验证码和用户输入验证码的功能,再用 server 类分别获取图片和用户输入的数据,判断两个数据是否一致。 
代码实现 

1.编写数字、英文随机生成的 server 类,源码:

package com;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class logcheck extends HttpServlet {

 public logcheck() {
  super();
 }

 
 public void destroy() {
  super.destroy(); 
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doPost(request, response);
 }


 /*实现的核心代码*/
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("image/jpeg");
  HttpSession session=request.getSession();
  int width=60;
  int height=20;
  
  //设置浏览器不要缓存此图片
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
  
  //创建内存图像并获得图形上下文
  BufferedImage image=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
  Graphics g=image.getGraphics();
  
  /*
   * 产生随机验证码
   * 定义验证码的字符表
   */
  String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  char[] rands=new char[4];
  for(int i=0;i<4;i++){
   int rand=(int) (Math.random() *36);
   rands[i]=chars.charAt(rand);
  }
  
  /*
   * 产生图像
   * 画背景
   */
  g.setColor(new Color(0xDCDCDC));
  g.fillRect(0, 0, width, height);
  
  /*
   * 随机产生120个干扰点
   */
  
  for(int i=0;i<120;i++){
   int x=(int)(Math.random()*width);
   int y=(int)(Math.random()*height);
   int red=(int)(Math.random()*255);
   int green=(int)(Math.random()*255);
   int blue=(int)(Math.random()*255);
   g.setColor(new Color(red,green,blue));
   g.drawOval(x, y, 1, 0);
  }
  g.setColor(Color.BLACK);
  g.setFont(new Font(null, Font.ITALIC|Font.BOLD,18));
  
  //在不同高度输出验证码的不同字符
  g.drawString(""+rands[0], 1, 17);
  g.drawString(""+rands[1], 16, 15);
  g.drawString(""+rands[2], 31, 18);
  g.drawString(""+rands[3], 46, 16);
  g.dispose();
  
  //将图像传到客户端
  ServletOutputStream sos=response.getOutputStream();
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ImageIO.write(image, "JPEG", baos);
  byte[] buffer=baos.toByteArray();
  response.setContentLength(buffer.length);
  sos.write(buffer);
  baos.close();
  sos.close();
  
  session.setAttribute("checkcode", new String(rands));
 }

 
 public void init() throws ServletException {
  // Put your code here
 }

}

2.用于显示验证码的页面

<%@ 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>index</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">
  -->
 </head>
 
 <body>
 <form action="yanzheng" method="post">
   <input type="text" name="name" size="5" maxlength="4">
  <a href="index.jsp"><img border="0" src="logcheck"></a><br><br>
  &nbsp&nbsp&nbsp&nbsp&nbsp<input type="submit" value="提交">
 </form>
 </body>
</html>

3.用于检验输入的验证码是否正确:

package com;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class yanzheng extends HttpServlet {

 public yanzheng() {
  super();
 }

 public void destroy() {
  super.destroy(); 
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doPost(request, response);
 }
 /*核心代码*/
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  String info=null;
  /*获取输入的值*/
  String value1=request.getParameter("name");

  /*获取图片的值*/
  HttpSession session=request.getSession();
  String value2=(String)session.getAttribute("checkcode");

  /*对比两个值(字母不区分大小写)*/
  if(value2.equalsIgnoreCase(value1)){
   info="验证码输入正确";
  }else{
   info="验证码输入错误";
  }
  System.out.println(info);
  request.setAttribute("info", info);
  request.getRequestDispatcher("/login.jsp").forward(request, response);
 }

 
 public void init() throws ServletException {
  // Put your code here
 }

}

4.显示输入结构界面(输入验证码是否正确): 

<%@ 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>My JSP 'login.jsp' starting page</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">
 -->

 </head>
 
 <body>
 <%=request.getAttribute("info") %>
 </body>
</html>

5.项目结构、效果截图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文