首页
IT
登录
6mi
u
盘
搜
搜 索
IT
用html+servlet实现的验证码
用html+servlet实现的验证码
xiaoxiao
2021-03-25
164
servlet简单验证码的实现
@WebServlet(description="annotation",urlPatterns={"/dynamicP"},loadOnStartup=1)
public class DynamicPicture extends HttpServlet
{
//首先声明验证码随机出现的字符数组,这里简写。
public static final char[] chars={'1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','A','B','C','D','E'
,'F','G','H','I','J','K','M','N'};
public static Random random = new Random();
public static String getRandomString()//随机产生五个
{
StringBuilder buffer = new StringBuilder();
for(int i = 0;i < 5;i++)
{
buffer.append(chars[random.nextInt(chars.length)]);
}
return buffer.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());
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); String randomString = getRandomString();
request.getSession(true).setAttribute("randomString", randomString);//传入session,验证时使用
//开始画图
int width=110;
int height=40;
Color color=getRandomColor();
Color reverse=getReverseColor(color);
BufferedImage bI = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = bI.createGraphics();
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,25));
g.setColor(color);
g.fillRect(0, 0, width, height);//绘制背景
g.setColor(reverse);
g.drawString(randomString, 15, 28);
for(int i=0,n=random.nextInt(100);i<n;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();
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
html部分
<td style="margin-left:9px"><img alt="dynamic picture" src="dynamicP" id="identity" style="margin:auto;"></td>
转载请注明原文地址: https://ju.6miu.com/read-1858.html
技术
最新回复
(
0
)