JSP验证码。

 1 package com;
 2
 3 import java.awt.Color;
 4 import java.awt.Font;
 5 import java.awt.Graphics2D;
 6 import java.awt.image.BufferedImage;
 7 import java.io.IOException;
 8 import java.util.Random;
 9
10 import javax.servlet.ServletException;
11 import javax.servlet.ServletOutputStream;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15
16 import com.sun.image.codec.jpeg.JPEGCodec;
17 import com.sun.image.codec.jpeg.JPEGImageEncoder;
18
19 public class IdentityServlet extends HttpServlet {
20     public static final char[] CHARS = { ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘,
21             ‘9‘, ‘0‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘,
22             ‘L‘, ‘M‘, ‘N‘, ‘O‘, ‘P‘, ‘K‘, ‘R‘, ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, ‘X‘,
23             ‘Y‘, ‘Z‘ };
24
25     public static Random random = new Random();
26
27     public static String getRandomString() {// 随机获取6位
28         StringBuffer buffer = new StringBuffer();
29         for (int i = 0; i < 6; i++) {
30             buffer.append(CHARS[random.nextInt(CHARS.length)]);// 随机获取一个字符
31
32         }
33         return buffer.toString();
34     }
35
36     public static Color getRandomColor() {
37         return new Color(random.nextInt(255), random.nextInt(255),
38                 random.nextInt(255));
39     }
40
41     public static Color getReverseColor(Color c) {// 取反色
42         return new Color(255 - c.getRed(), 255 - c.getGreen(),
43                 255 - c.getBlue());
44
45     }
46
47     public void doGet(HttpServletRequest request, HttpServletResponse response)
48             throws ServletException, IOException {
49         response.setContentType("image/jpeg");
50         String randomString = getRandomString();
51         request.getSession(true).setAttribute("randomString", randomString);
52         int width = 100;
53         int height = 30;
54         Color color = getRandomColor();
55         Color reverseColor = getReverseColor(color);
56         BufferedImage bImage = new BufferedImage(width, height,
57                 BufferedImage.TYPE_INT_RGB);
58         Graphics2D graphics2d = bImage.createGraphics();
59         graphics2d.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
60         graphics2d.setColor(color);
61         graphics2d.fillRect(0, 0, width, height);
62         graphics2d.setColor(reverseColor);
63         graphics2d.drawString(randomString, 18, 20);
64         for (int i = 0, n = random.nextInt(100); i < n; i++) {
65             graphics2d.drawRect(random.nextInt(width), random.nextInt(height),
66                     1, 1);
67
68         }
69         ServletOutputStream outputStream = response.getOutputStream();
70         JPEGImageEncoder coder = JPEGCodec.createJPEGEncoder(outputStream);
71         coder.encode(bImage);
72         outputStream.flush();
73     }
74
75 }

需要注意的是在myEclipse中处理图片,需要引入两个包:
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
报错:
Access restriction: The type JPEGImageEncoder is not accessible due to
restriction on required library C:\Java\jre1.6.0_07\lib\rt.jar

此时解决办法:
MyEclipse默认把这些受访问限制的API设成了ERROR。只要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的Deprecated
 and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过。

<%@ 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%>">

    <title>My JSP ‘index.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>

  <body>

    <img src = "servlet/IdentityServlet" id = "identity" onload = "btn.disabled=false;"/>
    <input type = button value="next" onclick="reloadImage()" id = "btn"/>
  </body>

    <script>
        function reloadImage(){
            document.getElementById(‘btn‘).disabled = true;
            document.getElementById(‘identity‘).src = ‘servlet/IdentityServlet?ts=‘+new Date().getTime();

        }
    </script>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>servlet</display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>IdentityServlet</servlet-name>
    <servlet-class>com.IdentityServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>IdentityServlet</servlet-name>
    <url-pattern>/servlet/IdentityServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
时间: 2024-10-18 10:21:36

JSP验证码。的相关文章

JSP验证码

在JSP页面上写随机的4位数验证码 实例化BufferedImage类 得到Graphics画笔给图片填充背景色 然后写上随机数和100个干扰点 用scropt实现刷新验证码 疑问:视频和书上的DrawString 方法不能用 也不知道怎么回事 把String转成了char调用了另外一个drawChars的方法才对 <%@ page language="java" contentType="text/html; charset=GB2312" import =

JSP验证码页面-Serverlet

使用 Get方法,通过设置session和request设置页面状态 <body> <div> <form method=get> <tr> <td align=left>请输入认证码:<input type=text name=rand maxlength=4 value=""></td> <td><img border=0 src="checkcode" onc

JSP验证码简单例子

原文:JSP验证码简单例子 源代码下载地址:http://www.zuidaima.com/share/1550463705320448.htm 几年前用servlet写的一个简单验证码功能.还有许多要完善的,但是验证码已经完善了. 包含登陆界面,可以自己修改下验证码代码把验证码的代码写进后台,生成图片后再输出到页面.也可以把验证码生成更复杂些. 登陆成功  验证失败

jsp验证码的生成

ValidateCodeServlet.java package com.hpe.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import ja

jsp 验证码

<%@page import="java.awt.Graphics2D"%> <%@page import="java.util.Random"%> <%@page import="java.awt.Font"%> <%@page import="javax.imageio.ImageIO"%> <%@page import="java.awt.Color&quo

jsp-5 生成验证码并校验

依然是以上次的代码为底 index.jsp 新增了验证码一栏 注意他的servlet是新建的ImageServlet 而且中间插了一段JS代码用于刷新验证码 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String

java实现生成简单图片验证码

原文:java实现生成简单图片验证码 源代码下载地址:http://www.zuidaima.com/share/1550463428840448.htm 项目载图: 该项目要转换为Dynamic web project http://www.zuidaima.com/blog/1618162161323008.htm 另外缺少jar包: http://www.zuidaima.com/jar/search/jstl-1.0.1.htm http://www.zuidaima.com/jar/s

web项目 验证码 小园dd

1. jsp代码 : 1 <Script> 2 function changeImg(){ 3 document.getElementById("certImg").src ="makeCertPic.jsp?it="+Math.random(); /* +Math.random() */ 4 } 5 </Script> 6 7 8 9 <table width="100%" border="0"

浅尝Java验证码制作(下)

方法三: 用开源组件Jcaptcha实现,与Spring组合使用可产生多种形式的验证码,JCaptcha 即为 Java 版本的 CAPTCHA 项目,其是一个开源项目,支持生成图形和声音版的验证码,在生成声音版的验证码时,需要使用到 FreeTTS.而CAPTCHA 全称 Completely Automated Public Turing Test to Tell Computers and Humans Apart,最早作为卡内基梅隆大学的一个科研项目,用于生成一个人类容易通过而计算机难以