1、index.jsp
<body>
<script type="text/javascript">
function refresh(){
loginForm.imgValidate.src = "validate.jsp?id=" + Math.random();
}
</script>
<form name="loginForm" action="checkCode.jsp" 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()">
<a href="" onclick="refresh()">重新获取验证码</a>
<br>
<input type="submit" value="登录">
</form>
</body>
2、validate.jsp
<body>
<%
response.setHeader("Cache-Control","no-cache");
// 在内存中创建图象
int width = 70, 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 random = new Random();
String sRand = "";
// 输出随机的验证文字
String ctmp = "";
int itmp = 0;
for (int i = 0; i < 4; i++) {
if((random.nextInt(2)+1)==1){
// 生成0~9的数字(ascll码)
itmp = random.nextInt(10) + 48;
ctmp = String.valueOf((char) itmp);
}else{
// 生成A~Z的字母(ascll码)
itmp = random.nextInt(26) + 65;
ctmp = String.valueOf((char) itmp);
}
sRand += ctmp;
Color color = new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110));
g.setColor(color); //设置文字颜色
}
//将验证码存入session
session.setAttribute("randStr", sRand);
//将验证码显示到图象中
g.setColor(Color.black);
g.setFont(new Font("", Font.PLAIN, 20));
g.drawString(sRand, 10, 17);
// 随机产生100个干扰点,使图象中的验证码不易被其他程序探测到
for (int i = 0; i < 100; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x, y, 1, 1);
}
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
</body>
3、checkCode.jsp
<body>
<%
String acc = "1102";
String pawd = "123456";
request.setCharacterEncoding("utf-8");
String account = request.getParameter("account");
session.setAttribute("account",account);
String password = request.getParameter("password");
String code = request.getParameter("code");
String randStr = (String) session.getAttribute("randStr");
response.setCharacterEncoding("utf-8");
if (code.equals(randStr)){
if (account.equals(acc) && password.equals(pawd)){
System.out.println("登录成功");
response.sendRedirect(request.getContextPath()+"/success.jsp");
}
else {
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
} else {
System.out.println("验证码错误");
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
%>
</body>
4、success.jsp
<body>
<%
String account = (String) session.getAttribute("account");
%>
<h3>恭喜
<%= account %> 用户成功登录
</h3>
</body>
5、error.jsp
<body>
账户或者密码错误
</body>