1:新建一个servlet,名为“imgServlet.java”用于生成带图片的验证码
public class imgServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* BufferedImage(int width, int height, int imageType)
构造一个类型为预定义图像类型之一的 BufferedImage。
*/
BufferedImage bi = new BufferedImage(80,35,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
//先画一个显示验证码的底板,为红色,大小为80 35
g.setColor(Color.red);
g.fillRect(0, 0, 80, 35);
/**
* 设置验证码
*/
char[] arry = "abcdefg1234567890".toCharArray();
Random r = new Random();
StringBuffer sb = new StringBuffer();
for(int i=0; i<4; i++) {
int index = r.nextInt(arry.length);
Font f = new Font(Font.MONOSPACED,Font.BOLD,30);
g.setFont(f);
g.setColor((new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255))));
/**
* drawString(String str, int x, int y)
使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。
*/
g.drawString(arry[index]+"", i*20, 30);
sb.append(arry[index]);
}
//将验证码的内容放在session中
request.getSession().setAttribute("piccode", sb.toString());
//图片的输出流,返回到客户端
ImageIO.write(bi, "JPG", response.getOutputStream());
}
}
2:新建一个jsp文件,用于接收验证码图片
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</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">
<!-- 利用script语句刷新验证码 -->
<script type="text/javascript">
function reLoadCode() {
var time = new Date();
document.getElementById("imagecode").src="imgServlet?id="+time;
}
</script>
</head>
<body>
<form action="login" method="post">
<p align="center">姓名:<input type="text" name="name"/></p>
<p align="center">密码:<input type="password" name="password"/></p>
<p align="center">
<img src="imgServlet" alt="验证码" id="imagecode"/>
<a href="javaScript:reLoadCode()" >看不清</a>
</p>
<P align="center">验证码:<input type="text" name="imgcode"/></P>
<p align="center"><input type="submit" value="登录"><input type="reset" value="重置"></p>
</form>
</body>
</html>