前台jsp页面与servlet传输图片验证码

效果图

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#acc {
    width: 40px
}
</style>
<script type="text/javascript">
            function change(){
                var yzm = document.getElementById("yzm");
                yzm.src = "GetImgServlet?a="+new Date().getTime();    
            }
        </script>
</head>
<body>
    <form action="login.action">
        account:<input type="text"><br> password:<input
            type="password"><br> messyzm:<input type="text" id="acc"
            name="qtyzm"> <img title="点击换图" id="yzm" src="GetImgServlet"onclick="change()">
            看不清
            <br> 
            <input type="submit"
            value="submit">
    </form>
</body>
</html>

验证码类

package cn.itcast.vcode.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
    private int w = 70;
    private int h = 35;
     private Random r = new Random();
     // {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
    private String[] fontNames  = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
    private String codes  = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    private Color bgColor  = new Color(255, 255, 255);
    private String text ;
    
    private Color randomColor () {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }
    
    private Font randomFont () {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];
        int style = r.nextInt(4);
        int size = r.nextInt(5) + 24; 
        return new Font(fontName, style, size);
    }
    
    private void drawLine (BufferedImage image) {
        int num  = 3;
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        for(int i = 0; i < num; i++) {
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h); 
            g2.setStroke(new BasicStroke(1.5F)); 
            g2.setColor(Color.BLUE); 
            g2.drawLine(x1, y1, x2, y2);
        }
    }
    
    private char randomChar () {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }
    
    private BufferedImage createImage () {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 
        Graphics2D g2 = (Graphics2D)image.getGraphics(); 
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
         return image;
    }
    
    public BufferedImage getImage () {
        BufferedImage image = createImage(); 
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        StringBuilder sb = new StringBuilder();
        // 向图片中画4个字符
        for(int i = 0; i < 4; i++)  {
            String s = randomChar() + ""; 
            sb.append(s); 
            float x = i * 1.0F * w / 4; 
            g2.setFont(randomFont()); 
            g2.setColor(randomColor()); 
            g2.drawString(s, x, h-5); 
        }
        this.text = sb.toString(); 
        drawLine(image); 
        return image;        
    }
    
    public String getText () {
        return text;
    }
    
    public static void output (BufferedImage image, OutputStream out) 
                throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}

package com.zhang.test;

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.vcode.utils.VerifyCode;

/**
 * Servlet implementation class GetImgServlet
 */
@WebServlet(urlPatterns= {"/GetImgServlet","/login.action"})
public class GetImgServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public GetImgServlet() {
        super();
       
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                 String type=request.getRequestURI();
                 if(type.endsWith("GetImgServlet")) {
                       VerifyCode vc = new VerifyCode();                        
                        BufferedImage bi = vc.getImage();                                            
                        request.getSession().setAttribute("yzm", vc.getText());                                    
                        vc.output(bi, response.getOutputStream());
                 }else {
                     String mess=request.getSession().getAttribute("yzm").toString().toLowerCase();
                     String qtyzm=request.getParameter("qtyzm").toLowerCase();
                     System.out.println(mess+"***"+qtyzm);
                    if(mess.equals(qtyzm)) {
                         response.getWriter().write("successLogin");
                    }else {
                         response.getWriter().write("failLogin");
                    }                     
                     
                 }
                
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        doGet(request, response);
    }

}
因为浏览器缓存问题所以点击更换验证码要加new Date().getTime();

并导入java包

猜你喜欢

转载自blog.csdn.net/Boxzhang/article/details/81808570
今日推荐