Java后台代码(CheckCodeServlet.java)
package web; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckCodeServlet extends HttpServlet { /* * 返回一张动态图片 * */ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/jpeg"); //获取字节流 OutputStream os=response.getOutputStream(); //图片映射区,理解成画板就行,画验证码 // BufferedImage image=new BufferedImage(width,height,imageType); BufferedImage image=new BufferedImage(80,40,BufferedImage.TYPE_INT_RGB); //画笔 Graphics g=image.getGraphics(); //添加背景颜色(随机) Random r=new Random(); g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));//Color(red,green,blue);rgb格式的颜色设置 g.fillRect(0, 0, 80, 40);//画矩形区域 //画字符串 g.setColor(Color.black);//设置验证码的颜色 g.setFont(new Font(null,Font.BOLD,20));//设置验证码的字体 Font(字体,样式,大小) String num=getNum(5);//调入验证码 g.drawString(num, 5, 30);//(字符串内容,X坐标,Y坐标) //划线,干扰机器人识别验证码 for(int i=0;i<6;i++){ //画6条线 g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));//设置线的颜色 g.drawLine(r.nextInt(80),r.nextInt(80),r.nextInt(80),r.nextInt(80));//g.drawLine(起点X坐标,起点Y坐标,终点X坐标,终点Y坐标); } //压缩 传输(画出的图片比较大,需要压缩,画出的是24位图) ImageIO.write(image, "jpeg", os); } //返回正确的验证码 //length:验证码的长度 public String getNum(int length){ String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";//常量,为了根据长度挑出随机的验证码 Random r=new Random(); StringBuffer sf=new StringBuffer(); for(int i=0;i<length;i++){ int index=r.nextInt(str.length());//取str的下标 char c=str.charAt(index);//根据下标取字符 sf.append(c);//字符放入字符串缓冲区 } return sf.toString();//转换成字符串返回 } }
web.xml配置文件
<servlet> <servlet-name>CheckCodeServlet</servlet-name> <servlet-class>web.CheckCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckCodeServlet</servlet-name> <url-pattern>/checkCode</url-pattern> </servlet-mapping>
text.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> </head> <body> <input > 图片:<img id="num" src="checkCode"><a href="javascript:;" onclick="document.getElementById('num').src='checkCode?'+new Date().getTime();">换一张</a> </body> </html>