JSP——(图片验证码)

一,Servlet生成图片验证码

第一步:创建一个生成图片的ImageServlet类

package com.lmc.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

第二步:创建一个数据缓存图像对象

//其中width表示图像的宽度,height表示图像的高度,最后一个参数表示图像字节灰度图像
BufferedImage  b = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

第三步:获取BufferedImage的绘制对象,再设置一些属性

//获取BufferedImage的绘制对象
Graphics g = b.getGraphics();
//绘制干扰线
for (int i = 0;i < 5; i++){
    int x1 = random.nextInt(59);
    int y1 = random.nextInt(29);
    int x2 = random.nextInt(59);
    int y2 = random.nextInt(29);
    g.drawLine(x1,y1,x2,y2);
}
// 设置画笔的一些属性(比如颜色、字体风格、背景、前景色等等)

第四步:创建一个图片验证的jsp页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 19/7/26
  Time: 14:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


图片验证

代码:

package com.lmc.servlet;

import javax.imageio.ImageIO;
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.util.Random;

public class ImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //创建一个数据缓存图像对象
        BufferedImage b = new BufferedImage (60, 30, BufferedImage.TYPE_BYTE_GRAY);
        //创建字符源
        String charSourses = "abcdefghijklmnopqrstuvwxyz0123456789";
        String numStr = "";
        Random random = new Random();
        for (int i = 0;i < 4; i++){
            int num = random.nextInt(charSourses.length() - 1);
            numStr += charSourses.substring(num,num+1);
        }
        //获取BufferedImage的绘制对象
        Graphics g = b.getGraphics();
        //绘制干扰线
        for (int i = 0;i < 5; i++){
            int x1 = random.nextInt(59);
            int y1 = random.nextInt(29);
            int x2 = random.nextInt(59);
            int y2 = random.nextInt(29);
            g.drawLine(x1,y1,x2,y2);
        }
        // 设置画笔的一些属性(比如颜色、字体风格、背景、前景色等等)
        g.drawString(numStr, 12, 19);
        request.getSession().setAttribute("checkCode",numStr);
        ImageIO.write(b, "jpg",response.getOutputStream());


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

二,使用Kaptcha插件生成验证码

1. 导入相应的jar包

​ kaptcha-2.3.jar

2. 写一个生成验证码图片的servlet

package com.eight.servlet;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class KaptchaServlet extends HttpServlet implements Servlet {
	private Properties props;
	private Producer kaptchaProducer;
	private String sessionKeyValue;

	public KaptchaServlet() {
		this.props = new Properties();

		this.kaptchaProducer = null;

		this.sessionKeyValue = null;
	}

	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);

		ImageIO.setUseCache(false);

		Enumeration initParams = conf.getInitParameterNames();
		while (initParams.hasMoreElements()) {
			String key = (String) initParams.nextElement();
			String value = conf.getInitParameter(key);
			this.props.put(key, value);
		}

		Config config = new Config(this.props);
		this.kaptchaProducer = config.getProducerImpl();
		this.sessionKeyValue = config.getSessionKey();
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setDateHeader("Expires", 0L);

		resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

		resp.addHeader("Cache-Control", "post-check=0, pre-check=0");

		resp.setHeader("Pragma", "no-cache");

		resp.setContentType("image/jpeg");

		String capText = this.kaptchaProducer.createText();
		String s1 = capText.substring(0, 1);
		String s2 = capText.substring(1, 2);
		String culs = "+-*";
		Random random = new Random();
		char cul = culs.charAt(random.nextInt(3));
		int r = 0;
		switch(cul){
			case '+':
				r = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
				break;
			case '-':
				r = Integer.valueOf(s1).intValue() - Integer.valueOf(s2).intValue();
				break;
			case '*':
				r = Integer.valueOf(s1).intValue() * Integer.valueOf(s2).intValue();
				break;
		}
		
		req.getSession().setAttribute(this.sessionKeyValue, String.valueOf(r));

		BufferedImage bi = this.kaptchaProducer.createImage(s1 + cul + s2 + "=?");

		ServletOutputStream out = resp.getOutputStream();

		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
}

第三步:在web.xml上配置一些信息

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

 
    <servlet>
        <servlet-name>Kaptchaservlet-name>
        <servlet-class>com.eight.servlet.KaptchaServletservlet-class>
        <init-param>
            <description>图片边框,合法值:yes , nodescription>
            <param-name>kaptcha.borderparam-name>
            <param-value>yesparam-value>
        init-param>
        <init-param>
            <description>
            边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
            description>
            <param-name>kaptcha.border.colorparam-name>
            <param-value>blackparam-value>
        init-param>
        <init-param>
            <description>边框厚度,合法值:>0description>
            <param-name>kaptcha.border.thicknessparam-name>
            <param-value>1param-value>
        init-param>
        <init-param>
            <description>图片宽 200description>
            <param-name>kaptcha.image.widthparam-name>
            <param-value>200param-value>
        init-param>
        <init-param>
            <description>图片高 50description>
            <param-name>kaptcha.image.heightparam-name>
            <param-value>50param-value>
        init-param>
        <init-param>
            <description>图片实现类description>
            <param-name>kaptcha.producer.implparam-name>
            <param-value> com.google.code.kaptcha.impl.DefaultKaptcha param-value>
        init-param>
        <init-param>
            <description>文本实现类description>
            <param-name>kaptcha.textproducer.implparam-name>
            <param-value>
            com.google.code.kaptcha.text.impl.DefaultTextCreator
            param-value>
        init-param>
        <init-param>
            <description>文本集合,验证码值从此集合中获取description>
            <param-name>kaptcha.textproducer.char.stringparam-name>
            <param-value>1234567890param-value>
        init-param>
        <init-param>
            <description>验证码长度 5description>
            <param-name>kaptcha.textproducer.char.lengthparam-name>
            <param-value>2param-value>
        init-param>
        <init-param>
            <description>字体 Arial, Courierdescription>
            <param-name>kaptcha.textproducer.font.namesparam-name>
            <param-value>Arial, Courierparam-value>
        init-param>
        <init-param>
            <description>字体大小 40px.description>
            <param-name>kaptcha.textproducer.font.sizeparam-name>
            <param-value>40param-value>
        init-param>
        <init-param>
            <description> 字体颜色,合法值: r,g,b 或者 white,black,blue. description>
            <param-name>kaptcha.textproducer.font.colorparam-name>
            <param-value>blackparam-value>
        init-param>
        <init-param>
            <description>文字间隔 2description>
            <param-name>kaptcha.textproducer.char.spaceparam-name>
            <param-value>2param-value>
        init-param>
        <init-param>
            <description>干扰实现类description>
            <param-name>kaptcha.noise.implparam-name>
            <param-value>
                 
                com.google.code.kaptcha.impl.DefaultNoise
            param-value>
        init-param>
        <init-param>
            <description> 干扰颜色,合法值: r,g,b 或者 white,black,blue. description>
            <param-name>kaptcha.noise.colorparam-name>
            <param-value>blackparam-value>
        init-param>
        <init-param>
            <description>
            图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            description>
            <param-name>kaptcha.obscurificator.implparam-name>
            <param-value> com.google.code.kaptcha.impl.WaterRipple param-value>
        init-param>
        <init-param>
            <description>背景实现类description>
            <param-name>kaptcha.background.implparam-name>
            <param-value> com.google.code.kaptcha.impl.DefaultBackground param-value>
        init-param>
        <init-param>
            <description>背景颜色渐变,开始颜色description>
            <param-name>kaptcha.background.clear.fromparam-name>
            <param-value>greenparam-value>
        init-param>
        <init-param>
            <description>背景颜色渐变,结束颜色description>
            <param-name>kaptcha.background.clear.toparam-name>
            <param-value>whiteparam-value>
        init-param>
        <init-param>
            <description>文字渲染器description>
            <param-name>kaptcha.word.implparam-name>
            <param-value>
            com.google.code.kaptcha.text.impl.DefaultWordRenderer
        param-value>
        init-param>
        <init-param>
            <description> session中存放验证码的key键 description>
            <param-name>kaptcha.session.keyparam-name>
            <param-value>KAPTCHA_SESSION_KEYparam-value>
        init-param>
        <init-param>
            <description>
            The date the kaptcha is generated is put into the HttpSession. This is the key value for that item in the session.
            description>
            <param-name>kaptcha.session.dateparam-name>
            <param-value>KAPTCHA_SESSION_DATEparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>Kaptchaservlet-name>
        <url-pattern>/randomcode.jpgurl-pattern>
    servlet-mapping>
web-app>

3. 在jsp页面写入验证码图片标签和相关js


random

4. 在登录验证的servlet中判断验证码是否正确

	//验证码验证
	private void codeCheck(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
        //创建一个json对象
		JSONObject json = new JSONObject();
        //获取图片验证码上面的数据
		String code = (String) request.getSession()
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        //获取用户输入的验证码数据
		String str = request.getParameter("imageCode");
		System.out.println(code+"  "+str);
		if(code.equals(str)){
			json.put("status","true");
		}else {
			json.put("status","error");
		}
		PrintWriter out = response.getWriter();   
		out.print(json); 
		out.flush();
		out.close();
	}

你可能感兴趣的:(JavaWeb基础,JSP)