页面
<%@ page language="java" contentType="text/html; charset=UTF-8" 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" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath%>"> <title>Insert title here</title> <script type="text/javascript"> var changeimg = function(img){ var timenow = new Date().getTime() ; img.src=\'#\'" /script> </head> <body> <img src="imgServlet" id="safeCodeImg" onclick="changeimg(this)" style="width: 60px;height: 20px;"/> <img src="img2Servlet" onclick="changeimg2(this)" /> </body> </html>
后台:servlet
package com.liu.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; 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 com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * Servlet implementation class ImgServlet */ @WebServlet("/img2Servlet") public class Img2Servlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * 获取随机颜色 * @param fc * @param bc * @return */ private Color getColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (fc < 0) fc = 0; if (bc > 255) bc = 255; if (bc < 0) bc = 0; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * @see HttpServlet#HttpServlet() */ public Img2Servlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置输出 必须设置为这个 response.setContentType("image/jpeg"); // 产生随机数 Random r = new Random(); // 把随机数绘制成图像 BufferedImage imgbuf = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);// 产生缓冲图像,40宽20高 Graphics2D g = imgbuf.createGraphics();// 取得缓冲的绘制环境 // 开始绘制 g.setColor(getColor(200, 250));// 设定背景色 g.fillRect(0, 0, width, height); // 随机产生15条干扰线 g.setColor(getColor(160, 200)); for (int i = 0; i < 15; i++) { int x = r.nextInt(width); int y = r.nextInt(height); int xl = r.nextInt(12); int yl = r.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } // 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到 g.setColor(getColor(120, 240)); for (int i = 0; i < 100; i++) { int x = r.nextInt(width); int y = r.nextInt(height); g.drawOval(x, y, 0, 0); } g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); String scode = ""; for (int i = 0; i < 4; i++) { String rand = String.valueOf(r.nextInt(10)); scode += rand; g.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110))); // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(rand, 13 * i + 6, 16); } //保存到session中 request.getSession().setAttribute("code", scode); // 输出图片 通过流的方式 ServletOutputStream out = response.getOutputStream(); // JPEGCodec.createJPEGEncoder(out);转码 // 产生JPEG的图像加码器 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(imgbuf); out.flush(); } }
package com.liu.servlet; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Date; import java.util.Random; 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 com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * Servlet implementation class ImgServlet */ @WebServlet("/imgServlet") public class ImgServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ImgServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 必须设置image/jpeg response.setContentType("image/jpeg"); int length = 4; // 设置默认生成4个数字 Date d = new Date(); long lseed = d.getTime(); java.util.Random r = new Random(lseed); // 设置随机种子 StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { str.append(r.nextInt(9)); // 生成随机数字 } // 可以在此加入保存验证码的代码 // 创建内存图像 BufferedImage bi = new BufferedImage(40, 16, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.clearRect(0, 0, 16, 40); g.setColor(Color.green.CYAN); System.out.println("--------------"+str); g.drawString(str.toString(), 4, 12); try { // 输出图片 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response .getOutputStream()); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(1.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(bi); } catch (Exception ex) { } } }
效果