src 目录下com.xieyuan包MyServlet.java文件(Servlet文件)
package com.xieyuan;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.corba.se.impl.javax.rmi.CORBA.Util;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class MyServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public MyServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
execute(request, response);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
execute(request, response);
}
private static final char CHARS[]={'2','3','4','5','6','7','8','9','A','B','C','D','E',
'F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V',
'W','X','Y','Z'
};
public static Random random=new Random();
//生成随机数字,len为需要随机数字的个数
public static String getRandomString(int len)
{
StringBuilder builder=new StringBuilder();
for(int i=0;i
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
}
}
This is the description of my J2EE component
This is the display name of my J2EE component
MyServlet
com.xieyuan.MyServlet
MyServlet
/servlet/MyServlet
index.jsp
接着部署您的WEB 应用,此时访问:
http://127.0.0.1:8080/Test/servlet/MyServlet
可以看到一张图片验证码。但是,这种效果好吗?这,并不是我们想要的,图片验证码应该混搭在HTML页面里,做登录等功能才对。
那么,接下来我们来做个JSP页面,直接使用项目WebRoot目录下的,index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page

结果就是我们想要的了
可以看到,无论我们点击多少次 “换一张图片”按钮,网页始终没有刷新,页面最后更新时间也没变,变的就是图片验证码!