最近在学习Java Web开发,做了一个生成网页随机图片验证码的例子,在此记录。
一、新建Servlet项目:
在MyEclipse中新建Servlet项目,一步步操作就OK,在此不再赘述。建好之后文件目录树如下图:
二、源代码实现:
(1)java代码:
package com.zdt.identity;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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;
public class Servlet1 extends HttpServlet {
//随机字符集合
public static final char[] CHARS = {'0','1','2','3','4','5','6',
'7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//随机数
public static Random random = new Random();
//获取6位随机数
public static String getRandomString() {
//字符串缓存
StringBuffer strBuffer = new StringBuffer();
//循环从字符集中随机取出6个字符
for (int i = 0; i < 6; i++) {
strBuffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return strBuffer.toString();
}
//获取随机颜色
public static Color getRandomColor() {
return new Color(random.nextInt(255), random.nextInt(255),
random.nextInt(255));
}
//获取某一颜色的反色
public static Color getReverseColor(Color c) {
return new Color(255 - c.getRed(), 255 - c.getGreen(),
255 - c.getBlue());
}
/**
* Constructor of the object.
*/
public Servlet1() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置输出的类型,此处为图片
response.setContentType("image/jpeg");
//获取随机字符串
String randomString = getRandomString();
//把随机字符串绑定到当前会话
request.getSession(true).setAttribute("randomString", randomString);
int width = 100;//图片宽度
int height = 30;//图片高度
//获取一种随机颜色
Color color = getRandomColor();
//获取上述颜色的反色
Color reverseColor = getReverseColor(color);
//根据宽度和高度,创建一个彩色图片
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_BGR);
//获取绘图对象
Graphics2D graphics2d = bi.createGraphics();
//设置字体
graphics2d.setFont(new Font(Font.SANS_SERIF,
Font.BOLD, 16));
//设置颜色
graphics2d.setColor(color);
//绘制背景
graphics2d.fillRect(0, 0, width, height);
//设置背景颜色,与字符颜色相反
graphics2d.setColor(reverseColor);
//绘制随机字符
graphics2d.drawString(randomString, 18, 20);
//绘制随机噪音点,最多绘制100个
for (int i = 0, n = random.nextInt(100); i < n; i++) {
graphics2d.drawRect(random.nextInt(width),
random.nextInt(height), 1, 1);
}
//响应的输出流
ServletOutputStream servletOutputStream = response.getOutputStream();
//转换成JPEG格式
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(servletOutputStream);
//对图片编码
encoder.encode(bi);
//输出到客户端
servletOutputStream.flush();
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
注意:在导入JPEG图片处理包JPEGCodec和JPEGImageEncoder时可能会报错,解决方案见: http://blog.csdn.net/u013149325/article/details/44838283
(2)写web.xml配置文件,主要代码如下:
Servlet1
This is the display name of my J2EE component
This is the description of my J2EE component
com.zdt.identity.Servlet1
Servlet1
/servlet/Servlet1
identity.html
This is my HTML page.
三、程序部署
安装Tomcat并部署成windows服务的教程:http://www.blogjava.net/lushengdi/archive/2010/07/01/324952.html
找到Tomcat的安装目录,在webapps目录下新建一个文件夹,命名servletTest,把项目编译后的WebRoot文件夹下的所有文件复制到servletTest文件夹中,Tomcat会自动加载项目。
四、结果演示
在浏览器地址栏中输入:http://localhost:8080/servletTest/identity.html,回车,结果如下图:
点击“换个图片”按钮,图片就会变化