Java生成验证码

来源:互联网 发布:cdn网络 多线程 编辑:程序博客网 时间:2021/10/28 21:48

我们在进行一些用户注册或者用户登录的时候经常会需要输入验证码。比如我们csnd发表博文的时候也是需要输入验证码的。下面我们就用Java来实现一下验证码的生成。

首先我们先来建立一个javaweb的工程,建立工程的过程我就不细说了。然后我们就进行具体代码的编写

1、建立一个jsp的验证页面,呈现效果如下,因为此时还没有生成验证码图片,所以图片部分还没有显示

具体代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script type="text/javascript">function reloadCode(){var time = new Date().getTime();document.getElementById("imagecode").src = "<%=request.getContextPath()%>/ImageServlet?d="+time;}</script></head><body><form action="<%=request.getContextPath()%>/loginServlet" method="get"><input type="text" name="checkcode"/><img alt="验证码" id = "imagecode" src="<%=request.getContextPath()%>/ImageServlet0"><a href="javascript:reloadCode();">看不清</a><input type="submit" value="提交"/></form></body></html>

2、建立一个servlet,用来生成验证码图片,不多废话,直接上代码

package com.slowly.servlet;import java.awt.Color;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class imageservlet */@WebServlet("/imageservlet")public class imageservlet extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public imageservlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/*绘制图片*/BufferedImage bufferedimage = new BufferedImage(68,22,BufferedImage.TYPE_3BYTE_BGR);Graphics graphics = bufferedimage.getGraphics();Color color = new Color(200, 150, 255);graphics.setColor(color);graphics.fillRect(0, 0, 68, 22);/*定义图片中要生成的字母和数字*/char ch[]= "ABCDEFGHIJKLMNOPQRSTUWWXYZ0123456789".toCharArray();Random randow = new Random();int len=ch.length,index;StringBuffer stringbuffer = new StringBuffer();/*将4个字母或数字写到图片里*/for(int i=0; i<4; i++){index = randow.nextInt(len);graphics.setColor(new Color(randow.nextInt(88),randow.nextInt(188),randow.nextInt(255)));graphics.drawString(ch[index]+"", (i*15)+3, 18);stringbuffer.append(ch[index]);}/*保存生成的验证码*/request.getSession().setAttribute("piccode", stringbuffer.toString());/*输出绘制的图片*/ImageIO.write(bufferedimage, "JPG", response.getOutputStream());}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

此时页面的显示效果如下,可以看出验证码图片效果已经显示出来了



3、建立一个servlet来判断提交的验证码和生成的验证码是否一致,代码如下:

package com.slowly.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class loginServlet */public class loginServlet extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public loginServlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String piccode = (String)request.getSession().getAttribute("piccode");//随机生成的验证码String logincode = request.getParameter("checkcode");//接收表单输入的验证码logincode = logincode.toUpperCase();response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();//比较随机生成的验证码和表单生成的验证码是否一致if(piccode.equals(logincode)){out.print("验证码正确");}else{out.print("验证码错误!!!");}out.flush();out.close();}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

好了,这样就可以进行验证码验证了,


当然建立servlet时需要配置一下,xml,这个对servlet有所了解的应该都知道怎么配置,这里不是讲解的重点,配置代码如下;

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.4">  <servlet>    <servlet-name>ImageServlet</servlet-name>    <servlet-class>com.slowly.servlet.imageservlet</servlet-class>  </servlet>  <servlet>  <servlet-name>loginServlet</servlet-name>  <servlet-class>com.slowly.servlet.loginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ImageServlet</servlet-name>    <url-pattern>/ImageServlet</url-pattern>  </servlet-mapping>  <servlet-mapping>  <servlet-name>loginServlet</servlet-name>  <url-pattern>/loginServlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

本文是慕课网Java生成验证码学习的总结

0 0