//index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<script type="text/javascript">
function reloadCode(){
var time=new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/ImgeServlet?d="+time;
}
</script>
</head>
<body>
验证码:<input type="text" name="checkcode">
<img alt="验证码" id="imagecode" src="<%=request.getContextPath() %>/servlet/ImgeServlet"/>
<a href="javascript:reloadCode();">看不清 </a> <br>
</body>
</html>
//ImageServlet.java
package com.muke;
import java.awt.Color;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
BufferedImage bi = new BufferedImage(80, 22, BufferedImage.TYPE_INT_RGB);
//画一个图片
Graphics g=bi.getGraphics();
Color c=new Color(200,150,255);
g.setColor(c);
g.fillRect(0, 0, 80, 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());
}
}
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.muke.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
梦影剑魂
相关分类