Servlet生成验证码并在Servlet后台验证完成登陆

再做一个图像验证码,发现网上都是Servlet的生成代码,由于自己刚接触JSP和Servlet,对Session等功能不太熟,后台验证整了近一个小时,才明白生么意思,先把代码贴出来,共享一下。

//生成验证码

package djr.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class IdentityServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final char[] CHARS={'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q',
		'R','S','T','U','V','W','X','Y','Z'};
	public static Random random=new Random();
	
	public static String getRandomString(){
		StringBuffer buffer=new StringBuffer();
		for(int i=0;i<6;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{
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		response.setContentType("image/jpeg");
		
		String randomString=getRandomString();
		
		int width=100;
		int height=30;
		
		Color color=getRandomColor();
		Color reverse=getReverseColor(color);
		
		BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
		Graphics2D g=bi.createGraphics();
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));
		g.setColor(color);
		g.fillRect(0, 0, width, height);
		g.setColor(reverse);
		g.drawString(randomString, 18, 20);
		for(int i=0,n=random.nextInt(100);i<n;i++){
			g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
		}
		
		request.getSession(true).setAttribute("randomString", randomString);
		System.out.println("后台产生验证码:"+randomString);
		
		ServletOutputStream out=response.getOutputStream();
		
		JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
		encoder.encode(bi);
		out.flush();
		g.dispose();
	}
}


//一个HTML文件测试
<%@ page language="java" pageEncoding="UTF-8"
contentType="text/html; charset=UTF-8"%>
<%@ include file="taglibs.inc.jsp" %>
<html>
<head>
<title>登录</title>
</head>
<script type="text/javascript">
function login(){
if(formName.txtUserID.value==""){
alert("请输入用户名");
return false;
}
if(formName.pwdUserPWD.value==""){
alter("请输入密码");
return false;
}
if(formName.identityChar.value==""){
alter("请输入验证码");
return false;
}
}
function reloadImage(){
document.getElementById('btn').disbled=true;
document.getElementById('identity').src='IdentityServlet?ts='+new Date().getTime();
}
</script>
<body>

<form action="userlogin" name="formName" method="post">
<div align="center">
<h1>用户登录</h1>
<table width="300" border="1">
<tr>
<td width="86">用户名</td>
<td width="198"><input type="text" name="txtUserID" /></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pwdUserPWD" /></td>
</tr>
<tr>
<td colspan="1" align="center"><input type="text" name="identityChar"></td>
<td colspan="1" align="center"><img src="IdentityServlet" id="identity" onload="btn.disabled =false;"/>
<input type="button" value="换个图片" onclick="reloadImage()" id="btn">
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="Submit" value="登录" onclick="login()" /></td>
</tr>

</table>
</div>

</form>
</body>
</html>

//后台验证
package djr.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import djr.dao.EmailDAO;
import djr.dao.UserDAO;
import djr.db.DbFactory;
import djr.dto.EmailDTO;
import djr.dto.UserDTO;
import djr.mail.MailManager;

public class LoginServlet extends HttpServlet {

/**
* 处理登录信息
*/
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String url = request.getServletPath();

//进行验证码后台的判断,这是通过Servlet实现的生成和验证功能。
if (url.toUpperCase().indexOf("USERLOGIN") != -1)
{

//主要是通过Session完成验证
System.out.println("后台验证验证码结果:"+(String)request.getSession(true).getAttribute("randomString"));
if(IdentityServlet.getRandomString()!=(String)request.getSession(true).getAttribute("randomString")){
url="index.jsp";
}
else{
// 登录邮件系统
UserDTO userDTO = new UserDTO();
userDTO.setUserid(request.getParameter("txtUserID"));
userDTO.setPassword(request.getParameter("pwdUserPWD"));

Connection conn = DbFactory.getConnection();

UserDAO userDAO = new UserDAO();
if (userDAO.findUser(userDTO, conn))
{
request.getSession().setAttribute("userinfo", userDTO);
MailManager mailMgr = new MailManager();
mailMgr.setUser(userDTO.getUserid());
mailMgr.setPassword(userDTO.getPassword());
if (mailMgr.receiveMail())
{
EmailDTO emailDTO = new EmailDTO();
emailDTO.setUserID(userDTO.getUserid());
List<EmailDTO> mailList = new EmailDAO().getMailList(
emailDTO, conn);
request.getSession().setAttribute("eMailList", mailList);
}

DbFactory.closeConn(conn);

url = "main.jsp";
}
else
{
url = "err.jsp";
}

}
}
else if (url.toUpperCase().indexOf("LOGOUT") != -1)
{
// 退出邮件系统
request.getSession().invalidate();
url = "index.jsp";
}
System.out.println(""+url);
RequestDispatcher rd=request.getRequestDispatcher(url);
rd.forward(request, response);

}
}

希望看懂原理,代码不能直接Copy,我的是整个项目下的东西哦!红色标注的是关键!!!!

posted @ 2011-09-25 12:30  java_li  阅读(889)  评论(2编辑  收藏  举报