使用JavaScript刷新验证码

今天学习了验证码的开发,日常生活中经常点验证码,今天自己也来做一个验证码


                                                   

首先是用一个文件产生随机验证码:



<%@page import="java.awt.*"%>
<%@page import="java.util.*"%>
<%@page import="java.awt.Graphics"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<body>
<%
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

g.setColor(new Color(200,200,200));
g.fillRect(0, 0, width, height);

Random rnd = new Random();
int rndNum = rnd.nextInt(9000)+1000;
String randS = String.valueOf(rndNum);


session.setAttribute("randS",randS);

g.setColor(Color.black);
g.setFont(new Font("",Font.PLAIN,20));
g.drawString(randS, 10, 17);

for(int i = 0;i<=100;i++){
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
g.drawOval(x, y, 1, 1);
}

ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>


但是验证码单独出现不安全,我们采用验证码和表单组合提交


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<body>
欢迎来到本系统<br>
<form action="/AJAX1/servlets/Loginservlet" method="post">
<br>
请您输入账号:<input type="text" name="account"/><br>
请您输入密码:<input type = "password" name="password"/><br>
验证码:<input type="text" name="code" size="10">
<img border=0 src ="validate.jsp">
<input type = "button" value="登录">
</form>

</body>
</html>



验证码的刷新方法很多,做方便的是点击验证码图片:



<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function refresh(){
loginForm.imgValidate.src="validate.jsp?id="+Math.random();

}

</script>
欢迎登录本系统<br>
<form name="loginForm" action="/AJAX1/servlets/Loginservlet" method="post">
请你输入账号:<input type="text" name = "account"><br>
请你输入密码:<input type="password" name="password"><br>
请输入验证码:<input type="text" name="code" size="10">
<img name="imgValidate" src="validate.jsp" onclick="refresh()"><br>
<input type="button" value="登录">
</form>


</body>
</html> 


这样我们就可以点击验证码进行刷新了。





猜你喜欢

转载自blog.csdn.net/wem603947175/article/details/78916870