Java Web实用开发技术-图形验证码

该博客介绍了如何实现一个图形验证码的Servlet,用于登录页面的验证码生成。Servlet通过生成随机字符串并绘制干扰点来创建验证码图像,并将其保存在用户的会话中。登录页面展示验证码图片,并提供刷新功能。当用户提交登录信息时,Servlet会检查输入的验证码是否与会话中的验证码匹配,从而完成登录验证。
摘要由CSDN通过智能技术生成

图形验证码生成(地址为checkcode)

package servlet;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



/**
 * Servlet implementation class CheckCode
 */
@WebServlet("/checkcode")
public class CheckCode extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckCode() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("image/jpeg");
		HttpSession session=request.getSession();
		int width=60;
		int height=30;
		//设置浏览器不要缓存此图片
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no=cache");
		response.setDateHeader("Expires", 0);
		//创建内存图像并获得其图形上下文
		BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		//产生随机验证码
		//定义验证码的字符表
		String chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		char[] rands=new char[4];
		for(int i=0;i<4;i++){
			int rand=(int)(Math.random()*62);
			rands[i]=chars.charAt(rand);
		}
		//产生图像
		//画背景
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, width, height);
		//随机产生120个干扰点
		for(int i=0;i<120;i++){
			int x=(int)(Math.random()*width);
			int y=(int)(Math.random()*height);
			int red=(int)(Math.random()*255);
			int green=(int)(Math.random()*255);
			int blue=(int)(Math.random()*255);
			g.setColor(new Color(red,green,blue));
			g.drawOval(x, y, 1, 0);
		}
		g.setColor(Color.BLACK);//设置字体为黑色
		g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
		//在不同的高度上输出验证码的不同字符
		g.drawString(""+rands[0], 1, 17);
		g.drawString(""+rands[1], 16, 15);
		g.drawString(""+rands[2], 31, 18);
		g.drawString(""+rands[3], 46, 16);
		g.dispose();
		//将图像输出到客户端
		ServletOutputStream sos=response.getOutputStream();
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", baos);
		byte[] buffer=baos.toByteArray();
		response.setContentLength(buffer.length);
		sos.write(buffer);
		baos.close();
		sos.close();
		//将验证码放到session中
		String str=new String(rands);
		session.setAttribute("checkCode", str);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

登录页面(输入界面.jsp)

<%@ 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>登录页面</title>
</head>
<script type="text/javascript">
	function refresh(){
		document.getElementById("img1").src="checkcode?a="+Math.random();
	}
</script>
<body>
<form method="get" name="form1">
用户名:<input type="text" name="userid"
	 onclick="mes.innerHTML=''"value="${param.userid}"/><br>
密码:<input type="password" name="userpwd" value="${param.userpwd}"/><br>
验证码:<input type="text" name="checkcode" />
<img border="0" src="checkcode" id="img1"/>
<input type="submit" value="换一张" onclick="refresh()"/><br>
<input type="submit" value="登录" onclick="form1.action='logcheck'">
<input type="reset" value="重置">
<div id="mes">${info}</div>
</form>
</body>
</html>

处理登录请求的servlet(地址为logcheck)

package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LogCheck
 */
@WebServlet("/logcheck")
public class LogCheck extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogCheck() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String userid=request.getParameter("userid");
		String userpwd=request.getParameter("userpwd");
		String usercheckcode=request.getParameter("checkcode");
		String info="";
		HttpSession session=request.getSession();
		String servercheckcode=(String)session.getAttribute("checkCode");

		if(servercheckcode==null){
			info="验证码为空!";
		}
		else if(!servercheckcode.equalsIgnoreCase(usercheckcode)){
			info="验证码不正确,请重新输入";
		}else if("张三".equals(userid)&&"123".equals(userpwd)){
			info="登录成功!";
		}else{info="用户名或密码错误!";}
		request.setAttribute("info", info);
		RequestDispatcher rd=request.getRequestDispatcher("/输入界面.jsp");
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

其中两个servlet之间的传参也可使用request

 request.getSession().setAttribute("checkCode", str);
 request.getSession().getAttribute("checkCode");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值