Struts学习笔记5——验证码

图片验证功能

1 创建3 个jsp 页面

tplogin.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="tp.do">
  <p>用户名:
    <label>
    <input name="username" type="text" id="username" />
    </label>
  </p>
  <p>密码:
    <label>
    <input name="password" type="text" id="password" />
    </label>
  </p>
  <p>验证码;
    <label>
    <input name="tupian" type="text" id="tupian" />
    </label>
  <td><img src="image1.jsp"/>&nbsp; <a href="tplogin.jsp">换一格${requestScope.tupian}</a></td>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="提交" />
    </label>
</p>
</form>


</body>
</html>


说明:所要注意的是<form id="form1" name="form1" method="post" action=" tp.do ">
     <td>验证码
        <input name="tupian" type="text" id="tupian" />
  <img src="image1.jsp">&nbsp;<a href="tplogin.jsp">换一格${requestScope.tupian}</a></td>
    </tr>
    <tr>
      <td>


Image1.jsp
<%@page contentType="image/jpeg; charset=gb2312" %>
<jsp:useBean id="image" class="dao.ImageEnsure" />
adc
<%
	String str=image.getEnsure(0,0,response.getOutputStream());//取得真正的验证码信息
	session.setAttribute("tupian", str); //将这个真正的验证码信息保存在一个对象当中。以便日后核对
	
%>


说明:session.setAttribute("tupian", str) 中的tupian 对应的是
   <tr>
      <td>验证码
        <input name="tupian" type="text" id="tupian" />
  <img src="image1.jsp">&nbsp; <a href=" tplogin.jsp ">换一格</a></td>
    </tr>

的tupian 
<jsp:useBean id="image" class="dao.ImageEnsure" />
这个是引用一个类生成验证码的图片,对应的是dao包里面的ImageEnsure 这个类



Ok.jsp
ok恭喜你验证成功了


ImageEnsure 类

package dao;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;

import javax.imageio.ImageIO;

public class ImageEnsure {
	public ImageEnsure() {
	}

	private char mapTable[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
			'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
			'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
			'9' };

	// 这是一个数据字典,验证码当中的信息都是来自这个数组
	public String getEnsure(int width, int height, OutputStream os) {

		if (width <= 0)
			width = 100;
		if (height <= 0)
			height = 50;

		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		// 获取图形上下文
		Graphics g = image.getGraphics();

		// 设定背景色
		g.setColor(new Color(0xCCCCFF));
		g.fillRect(0, 0, width, height); // 用刚才的颜色填充矩形(开始x坐标,开始y坐标,终止x坐标,终止y坐标)

		// 画边框
		g.setColor(Color.black); // 更改颜色
		g.drawRect(0, 0, width - 1, height - 1); // 画个框

		// 取随机产生的认证码
		String strEnsure = "";

		// 4代表4位验证码
		for (int i = 0; i < 4; ++i) {
			strEnsure += mapTable[(int) (mapTable.length * Math.random())];
		}

		// 将认证码显示到图象中
		g.setColor(Color.black);
		g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18)); // 18表示字号
		String str = strEnsure.substring(0, 1);
		g.drawString(str, 8, 15);
		str = strEnsure.substring(1, 2);
		g.drawString(str, 20, 17);
		str = strEnsure.substring(2, 3);
		g.drawString(str, 35, 15);
		str = strEnsure.substring(3, 4);
		g.drawString(str, 45, 17);

		// 随机产生30个干扰点
		Random rand = new Random();
		for (int i = 0; i < 30; i++) {
			int x = rand.nextInt(width);
			int y = rand.nextInt(height);
			g.drawOval(x, y, 1, 1);
		}

		// 释放图形上下文
		g.dispose();

		try {
			// 输出图象到页面
			ImageIO.write(image, "JPEG", os);
		} catch (IOException e) {
			return "";
		}

		return strEnsure;
	}
	
	 /* public static void main(String []args) { try{ BufferedOutputStream os =
	  new BufferedOutputStream( new FileOutputStream("c:\\test.jpg"));
	  
	 new ImageEnsure().getEnsure(100, 200, os); os.flush(); os.close(); }
	 catch(Exception e) {} }
	 */

}



1个action
package action;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class TpAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		String tupian=request.getParameter("tupian");
		HttpSession session=request.getSession();
		String a=(String)session.getAttribute("tupian");
		if(!(request.getSession().getAttribute("tupian").equals(tupian))){
			request.setAttribute("tupian","验证码错误");
			return mapping.findForward("nook");
		}
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		if(username.equals("11")&&password.equals("11")){
			session.setAttribute("username", username);
			session.setAttribute("log","ok");
			return mapping.findForward("ok");
		}
		return mapping.findForward("nook");
		
	}
}


Struts-config.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans />
  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action path="/tp" type="action.TpAction">
      <forward name="ok" path="/ok.jsp" />
      <forward name="nook" path="/tplogin.jsp" />
    </action>

  </action-mappings>

  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>


你可能感兴趣的:(apache,jsp,servlet,struts,OS)