创建命令如下:
mvn archetype:generate -DgroupId=com.gao.web -DartifactId=VerifyCode -DarchetypeArtifactId=maven-archetype-webapp
mvn -Dwtpversion=1.0 eclipse:eclipse
package com.niu.gao;
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 javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * @Description: (生成验证码Servlet) * @author:relieved * @date:2015-7-25 */
public class GenerateCodeServlet extends HttpServlet {
/** * serialVersionUID */
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//图像数据缓冲区 构造函数 第一个参数为宽 第二个参数为高 第三个为图片类型
BufferedImage bi = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
//绘制图片
Graphics grap = bi.getGraphics();
//设置字体
Font f = new Font("宋体",Font.ITALIC ,20);
grap.setFont(f);
//背景颜色
Color color = new Color(200,160,255);
//设置背景颜色
grap.setColor(color);
grap.fillRect(0, 0, 100, 25);//坐标 绘制图片宽、高
//验证码内容
char[] content = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random ran = new Random();//根据随机数来取组合验证码内容
int len = content.length,index;
StringBuffer generateCode = new StringBuffer();//存储随机生成的验证码
//生成6位的验证码
for(int i = 0;i<6;i++){
index = ran.nextInt(len);
//设置验证码颜色
grap.setColor(new Color(ran.nextInt(100), ran.nextInt(180),ran.nextInt(255)));
//将字符画在画板上
grap.drawString(content[index]+"", i*16+3, 19);
generateCode.append(content[index]);
}
//将生成的验证码放在session中以便之后验证用到
req.getSession().setAttribute("verifyCode", generateCode.toString());
//将生成的验证码图片输出
ImageIO.write(bi, "PNG", resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
验证验证码的Servlet代码如下:
package com.niu.gao;
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 javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Description: (验证验证码Servlet)
* @author:relieved
* @date:2015-7-25
*/
public class VerifyCodeServlet extends HttpServlet {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String codeValue = req.getParameter(“verifyCode”);
String verifyValue = req.getSession().getAttribute(“verifyCode”).toString();
resp.setCharacterEncoding(“GBK”);
resp.setContentType(“text/html”);
resp.getWriter().write(““);
if(codeValue!=null&&codeValue!=”“&&verifyValue!=null&&verifyValue!=”“&&codeValue.equalsIgnoreCase(verifyValue)){
resp.getWriter().write(“验证成功!”);
}else{
resp.getWriter().write(“验证失败!”);
}
resp.getWriter().write(“
再试一次“);
resp.getWriter().write(““);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
web.xml文件配置如下
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>VerifyCode</display-name>
<servlet>
<servlet-name>verifyCode</servlet-name>
<servlet-class>com.niu.gao.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>verifyCode</servlet-name>
<url-pattern>/verifyCode/submit.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>generateCode</servlet-name>
<servlet-class>com.niu.gao.GenerateCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>generateCode</servlet-name>
<url-pattern>/generate/verifyCode.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
jsp页面如下
<%@ 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>VerifyCode</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">
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript"> var path="<%=path%>"; $( document ).ready(function() { $("#codeImg").on("click",function(){ $('#codeImg').prop('src',path+'/generate/verifyCode.do?nocache='+new Date().getTime()); }); }); </script>
</head>
<body style="text-align: center;">
<h2>Hello World!</h2>
<form action="<%=path%>/verifyCode/submit.do" method="post" autocomplete="false">
<span style="margin: 10px 0 0 10px;vertical-align: baseline;">
请输入验证码:<input name="verifyCode" type="text" />
</span>
<img id="codeImg" style="vertical-align: bottom;margin: 10px 0 0 10px;cursor: pointer;" alt="验证码" src="<%=path%>/generate/verifyCode.do">
<input type="submit" value="验证">
</form>
</body>
</html>
效果图如下