在JSP页面中动态生成图片验证码的方法实例

JSP教程 2025-07-31

在JSP页面中动态生成图片验证码

%@ page language="java" pageEncoding="UTF-8"%
%@ page 
import="java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*" %
%@ taglib http://struts.a**pa*che.org/tags-bean"http://struts.a**pa*che.org/tags-bean" 
prefix="bean" %
%@ taglib http://struts.ap*a**che.org/tags-html"http://struts.ap*a**che.org/tags-html" 
prefix="html" %
%@ taglib http://struts.apa*c*h*e.org/tags-logic"http://struts.apa*c*h*e.org/tags-logic" 
prefix="logic" %
%@ taglib http://struts.**ap*ache.org/tags-tiles"http://struts.**ap*ache.org/tags-tiles" 
prefix="tiles" %
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
html:html lang="true"
 head
  html:base /
  titleMyJsp.jsp/title
meta http-equiv="pragma" content="no-cache"
meta http-equiv="cache-control" content="no-cache"
meta http-equiv="expires" content="0"  
meta http-equiv="keywords" content="keyword1,keyword2,keyword3"
meta http-equiv="description" content="This is my page"
!--
link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" 
--
 /head
 body
h3在jsp页面生成验证码/h3
hr/
%
 //out.clear();
 //response.setContentType("image/jpeg");//设置响应类型
 //response.addHeader("pragma","NO-cache");
 //response.addHeader("Cache-Control","no-cache");
 //response.addDateHeader("Expries",0);
 int width=400, height=30;//图片的大小(宽和高)
 //构架画布,第一个参数表示画布的宽,第二个参数表示画布的高,第三个参数的含义有待确定
 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 Graphics g = image.getGraphics();//实例化画图对象
 //以下设置背景色
 g.setColor(Color.yellow); 
 Font DeFont=new Font("宋体", Font.ITALIC, 20);
 g.setFont(DeFont);
 //将已经设置好的背景颜色填充到指定的画布区域
 g.fillRect(0,0, width, height);
 //置字体色
 g.setColor(Color.blue);
 int x=10,y=10,xl=550,yl=15;
 g.drawLine(x,y,x+xl,y+yl); 
 //在画布中画椭圆形,参数为椭圆的坐标,用于确定椭圆的大小
 g.drawOval(0,10,200,10);
 //在画布上输出文字信息,第一个参数表示要显示的文字,第二和第三个参数表示起始点的X、Y坐标
 g.drawString("想要输出的文字-我是陈杉",70,20);
 g.dispose();
 ServletOutputStream outStream = response.getOutputStream();
 JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(outStream);
 encoder.encode(image);
 outStream.close();
%
 /body
/html:html

--将该文件保存为pic.jsp,该文件负责生成图片!如果要在其他的页面显示该图片只需要写上

img src="pic.jsp"/

仅此一句就ok了,适用于生成各种验证码!

总结