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 }
View Code

需要注意的是在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:Javajre1.6.0_07lib t.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>
原文地址:https://www.cnblogs.com/pengpengzhang/p/5790617.html