在web工程目录中添加工具包,如图:
创建一个Servlet,代码如下:
注意:如果你的tomcat版本低于7.0,就没有@WebServlet("/ValidateCode")注解;
这时就需要你自己动手为Servlet类在web.xml中注册
package com.qf.test; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.dsna.util.images.ValidateCode; /** * Servlet implementation class ValidateCode */ @WebServlet("/ValidateCode") public class ValidateCode01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ValidateCode code = new ValidateCode(300, 100, 5, 20); code.write(response.getOutputStream()); String string = code.getCode(); System.out.println("=====code===="+string); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
效果图:
控制台获取生成的验证码: