Servlet:response生成图片验证码(二)

2014-11-24 09:24:20 · 作者: · 浏览: 1
nse) throws ServletException, IOException
{
response.setCharacterEncoding("utf-8");
//设置返回的文件编码
response.setContentType("image/jpeg");
//获取随机码
String getRandomCode=getRandomString(5);
//将随机码放到Session中
request.getSession().setAttribute("randomcode", getRandomCode);
int width=100;
int height=30;
Color color=getColor();
Color reverseColor=getReverseColor(color);
//创建一个彩色图片
BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g=bi.createGraphics();
g.setFont(new Font(null,Font.BOLD,16));
g.setColor(color);
g.fillRect(0,0,width,height);
g.setColor(reverseColor);
g.drawString(getRandomCode, 18,20);
//绘制噪点,最多100个
for(int i=0,n=random.nextInt(100);i
{
g.drawRect(random.nextInt(width), random.nextInt(height), 1,1);
}
ServletOutputStream out=response.getOutputStream();
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(bi);
out.flush();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
}
}
配置好web.xml
[java]
< xml version="1.0" encoding="UTF-8" >
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
This is the description of my J2EE component
This is the display name of my J2EE component
MyServlet
com.xieyuan.MyServlet
MyServlet
/servlet/MyServlet
index.jsp
接着部署您的WEB 应用,此时访问:
可以看到一张图片验证码。但是,这种效果好吗?这,并不是我们想要的,图片验证码应该混搭在HTML页面里,做登录等功能才对。
那么,接下来我们来做个JSP页面,直接使用项目WebRoot目录下的,index.jsp
[java]
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
<script language="java script" >
function reloadImage()
{
document.getElementById("btn").disabled=true;
document.getElementById("img").src="servlet/MyServlet timestamp="+new Date().getTime();
}



<script>document.write("页面最后更新:"+document.lastModified)
html>