字母+数字验证码(一)

项目龙骨(Servlet项目 自己可以更改为框架式) :

字母+数字验证码(一)_第1张图片

首先将两个类放进去 1. ImageServlet.java

package com.muke;

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;

@SuppressWarnings("serial")
@WebServlet(name = "ImageServlet", urlPatterns = { "/servlet/ImageServlet" })
public class ImageServlet extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200,150,255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len=ch.length,index;
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<4; i++){
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
            g.drawString(ch[index]+"", (i*15)+3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("piccode", sb.toString());
        ImageIO.write(bi, "JPG", response.getOutputStream());
    }
}

LoginServlet.java 类

package com.muke;

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;

@SuppressWarnings("serial")
@WebServlet(name = "LoginServlet", urlPatterns = { "/servlet/LoginServlet" })
public class LoginServlet extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        String piccode = (String) request.getSession().getAttribute("piccode");
        String checkcode = request.getParameter("checkcode");
        checkcode = checkcode.toUpperCase();
response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        if(checkcode.equals(piccode)){
            out.println("验证码输入正确!");
        }else{
            out.println("验证码输入错误!!!");
        }
        out.flush();
        out.close();
    }
}

你可能感兴趣的:(字母+数字验证码)