生成验证码
package com.itheima.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 验证码
* @author thinkpad
*
*/
public class servletDemo4 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width=110;
int height=25;
int imageType=BufferedImage.TYPE_INT_RGB;
//在内存中创建一个图像对象
BufferedImage img=new BufferedImage(width, height, imageType);
//创建画笔
Graphics g =img.getGraphics();
//给图片添加背景颜色
g.setColor(Color.PINK);
g.fillRect(1, 1, width-2, height-2);
//添加边框颜色
g.setColor(Color.RED);
g.drawRect(0, 0, width-1, height-1);
//添加文字
g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 15));
g.setColor(Color.BLUE);
Random rand=new Random();
int position=20;
for (int i = 0; i < 4; i++) {
g.drawString(rand.nextInt(10)+"", position, 18);
position+=20;
}
//添加9跟干扰线
for (int i = 0; i < 9; i++) {
g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
}
//将图片以对象方式输出到客户端
ImageIO.write(img, "jpg", response.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function changeCode(){
var img=document.getElementsByTagName("img")[0];
img.src="/day05_1/demo2?time="+new Date().getTime();
}
</script>
<title>Insert title here</title>
</head>
<body>
<form action="#" method="post">
用户名:<input type="text" name="userName"><br>
密码:<input type="password" name="password"><br>
验证码:<input type="text" name="code">
<img src="/day05_1/demo2" onclick="changeCode()"><a href="javascript:changeCode()">看不清,换一张</a><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>
本文介绍了一个使用Java Servlet生成验证码的示例代码。该Servlet通过创建一个带有随机数字的图片作为验证码,并允许用户通过点击刷新按钮更换验证码。此外,还提供了一个简单的登录页面用于展示验证码。

2万+

被折叠的 条评论
为什么被折叠?



