servlet与jsp实现动态验证码

我们模拟一个简单的登录界面,如果登录成功则跳转到success.jsp,若失败则转发到log.jsp界面并显示错误信息

案例代码如下:

登录界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <script type="text/javascript">
    
    	function change() {
    		//因为我们不想为获取验证码来进行整个页面的刷新,所以我们使用javascript脚本来实现局部刷新
    		var element = document.getElementById("123");
    		element.setAttribute("src", "/day_11-2/CreateImageTest?time=" + new Date().getTime());//我们为什么要在最后加上一个参数呢?因为如果我们不加参数的话讨厌的服务器会缓存图片刷新图片不起作用
    	}
    </script>
    
    <title>My JSP 'log.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
<!--   当浏览器禁用了cookie时我们可以使用url重写的方法达到同样的效果 -->
<!-- response.encodeURL("/day_11/LogServlet");当客户端禁用cookie时会自动生成带JSESSIONID参数的的url路径即:/day_11/LogServlet;JSESSIONID=********
当没有禁用是会返回原值 -->
  <body>
  <% 
  	String error = (String)request.getAttribute("error");
  	if(error != null) {
  %>
 	 <font color="red"><h6 align="center"><%=error%></h6></font>
  <%
  	}
  %>
  <form action=<%=response.encodeURL("/day_11-2/LogServlet") %> method="post">
	  <h1 align="center">登陆</h1>
	  <table align="center">
	   	<tr>
	   		<td>用户名:</td>
	   		<td><input type="text" name="username"></td>
	   	</tr>
	   	<tr>
	   		<td>密码:</td>
	   		<td><input type="password" name="password"></td>
	   	</tr>
	   	<tr >
	   		<td>验证码:</td>
	   		<td><input type="text" name="rcode" /> <img id="123" src="/day_11-2/CreateImageTest"><!-- 用来请求回去servlet生成验证码并返回 -->
	   		 <a href="javascript:change()" ><font size="1" >看不清换一张</font></a><!-- 当我们点击该超链接时出发change()方法 -->
	   		  </td>
	   	</tr>
	   	<tr>
	   		<td><input type="submit" value="登陆"></td>
	   		<td><input type="submit" value="注册"></td>
	   	</tr>
	   </table>
   </form>
  </body>
</html>


验证servlet:

package com.servlet.www;

import java.io.IOException;
import java.io.PrintWriter;

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

public class LogServlet extends HttpServlet {

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

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String rcode = request.getParameter("rcode");
		String s = (String)request.getSession().getAttribute("rcode");
		if("weijinhao".equals(username)) {
			if("123456".equals(password)) {
					if(s.equals(rcode)) {
						HttpSession session = request.getSession();
						session.setAttribute("username",username);
						response.setStatus(302);
						response.setHeader("location", response.encodeURL("/day_11-2/jsp/success.jsp"));
					}
					else {
						request.setAttribute("error", "验证码错误");
						request.getRequestDispatcher(response.encodeURL("/jsp/log.jsp")).forward(request, response);
					}
				
			}
			else {
				request.setAttribute("error", "密码错误");
				request.getRequestDispatcher(response.encodeURL("/jsp/log.jsp")).forward(request, response);
			}
		}
		else {
			request.setAttribute("error", "账户名错误");
			request.getRequestDispatcher(response.encodeURL("/jsp/log.jsp")).forward(request, response);
		}
	}

}



动态生成验证码的servlet:

package com.servlet.www;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

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

import cn.itcast.vcode.utils.VerifyCode;

public class CreateImageTest extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		VerifyCode vc = new VerifyCode();//我们使用这个对象来在内存中划出我们想要的验证码
		BufferedImage bi = vc.getImage();//获得验证码
		String rcode = vc.getText();//得到验证码的字符串表示
		rcode = rcode.toLowerCase();//应为我们输入的验证码都是不区分大小写的所以我们全部转化成小写的
		HttpSession s = request.getSession();//我们使用session来实现属性在多个servlet中的传递
		s.setAttribute("rcode",rcode);
		VerifyCode.output(bi, response.getOutputStream());//输出验证码到请求的位置,因为是图片所以我们输出的是字节流
	}

}


生成验证码的工具类:

package cn.itcast.vcode.utils;

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

import javax.imageio.ImageIO;

public class VerifyCode {
	private int w = 70;
	private int h = 35;
 	private Random r = new Random();
 	// {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
	private String[] fontNames  = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
	private String codes  = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
	private Color bgColor  = new Color(255, 255, 255);
	private String text ;
	
	private Color randomColor () {
		int red = r.nextInt(150);
		int green = r.nextInt(150);
		int blue = r.nextInt(150);
		return new Color(red, green, blue);
	}
	
	private Font randomFont () {
		int index = r.nextInt(fontNames.length);
		String fontName = fontNames[index];
		int style = r.nextInt(4);
		int size = r.nextInt(5) + 24; 
		return new Font(fontName, style, size);
	}
	
	private void drawLine (BufferedImage image) {
		int num  = 3;
		Graphics2D g2 = (Graphics2D)image.getGraphics();
		for(int i = 0; i < num; i++) {
			int x1 = r.nextInt(w);
			int y1 = r.nextInt(h);
			int x2 = r.nextInt(w);
			int y2 = r.nextInt(h); 
			g2.setStroke(new BasicStroke(1.5F)); 
			g2.setColor(Color.BLUE); 
			g2.drawLine(x1, y1, x2, y2);
		}
	}
	
	private char randomChar () {
		int index = r.nextInt(codes.length());
		return codes.charAt(index);
	}
	
	private BufferedImage createImage () {
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 
		Graphics2D g2 = (Graphics2D)image.getGraphics(); 
		g2.setColor(this.bgColor);
		g2.fillRect(0, 0, w, h);
 		return image;
	}
	
	public BufferedImage getImage () {
		BufferedImage image = createImage(); 
		Graphics2D g2 = (Graphics2D)image.getGraphics();
		StringBuilder sb = new StringBuilder();
		// 向图片中画4个字符
		for(int i = 0; i < 4; i++)  {
			String s = randomChar() + ""; 
			sb.append(s); 
			float x = i * 1.0F * w / 4; 
			g2.setFont(randomFont()); 
			g2.setColor(randomColor()); 
			g2.drawString(s, x, h-5); 
		}
		this.text = sb.toString(); 
		drawLine(image); 
		return image;		
	}
	
	public String getText () {
		return text;
	}
	
	public static void output (BufferedImage image, OutputStream out) 
				throws IOException {
		ImageIO.write(image, "JPEG", out);
	}
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值