import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.awt.image.*;
import java.awt.*;
import com.sun.image.codec.jpeg.*;
/** * * 在Web.xml中布署: CodePicServlet com.liuxu.servlet.CodePicServlet CodePicServlet /verifycode * * 在JSP中写上: * * * 在调用时,运行String random = (String) session.getAttribute("verifyCode"); * 得到产生的验证码 * */public class CodePicServlet extends HttpServlet {
//改成Servlet,就重写service方法就不会出现IllegalStateException异常了,不要写在JSP中 protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String chose = "0123456789";
//abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ Random rand = new Random();
HttpSession session = request.getSession(true);
//设置显示内容 response.setContentType("image/jpeg");
//设置页面不缓存 response.addHeader("pragma", "NO-cache");
response.addHeader("Cache-Control", "no-cache");
response.addDateHeader("Expries", 0);
// 在内存中创建图象 int width = 65, height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文 Graphics g = image.getGraphics();
//以下填充背景颜色 g.setColor(new Color(51, 102, 255));
g.fillRect(0, 0, width, height);
//画边框 // g.setColor(Color.BLACK); // g.drawRect(0, 0, width - 1, height - 1); // 随机产生很多条干扰线,使图象中的认证码不易被其它程序探测到 for (int i = 0; i < 30; i++) {
g.setColor(getRandColor(100, 150));
int x = rand.nextInt(width);
int y = rand.nextInt(height);
int xl = rand.nextInt(10);
int yl = rand.nextInt(10);
g.drawLine(x, y, x + xl, y + yl);
}
//设置字体 g.setFont(new Font("Times New Roman", Font.BOLD + Font.ITALIC, 16));
//设置字体颜色 g.setColor(Color.WHITE);
// 取随机产生的认证码(4位数字) String sRand = "";
for (int i = 0; i < 4; i++) {
String ranChar = String.valueOf(chose.charAt(rand.nextInt(chose.length())));
sRand += ranChar;
//画一个出来 g.drawString(ranChar, 14 * i + 6, 15);
}
//在session中会有一个代码的对象 session.setAttribute("verifyCode", String.valueOf(sRand));
// 图象生效 g.dispose();
ServletOutputStream outStream = response.getOutputStream();
//将输出流建立成一个JPEG的文件编码 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
encoder.encode(image);
outStream.flush();
outStream.close();
}
//给定范围获得随机颜色 Color getRandColor(int beginColor, int endColor) {
Random random = new Random();
if (beginColor > 255) {
beginColor = 255;
}
if (endColor > 255) {
endColor = 255;
}
int r = beginColor + random.nextInt(endColor - beginColor);
int g = beginColor + random.nextInt(endColor - beginColor);
int b = beginColor + random.nextInt(endColor - beginColor);
return new Color(r, g, b);
}
}
阅读(228) | 评论(0) | 转发(0) |