---
title: "在Web中动态生成验证码：Servlet和Rest模式"
author: "zeroliu"
date: "2008-09-24T10:23:39Z"
tags: []
slug: "web-servlet-rest"
draft: false
lastmod: "2008-09-24T10:23:39Z"
id: 246182
url: "https://zeroliu.iteye.com/blog/246182"
---

【虎.无名】登录处理常用到一个生成随机校验码图片的处理。下面是一套简单的servlet实现，但是似乎还不支持中文字符串。于是对齐做了一些改进。
参考原型：<http://blog.csdn.net/zhanngle/archive/2007/12/03/1913402.aspx> 在Web中动态生成验证码
**相关资源：**<http://zeroliu.iteye.com/admin/blogs/240006>【虎.无名】自定义Java的REST行为分发器
<http://zeroliu.iteye.com/admin/blogs/246182>在Web中动态生成验证码：Servlet和Rest模式
<http://hi.baidu.com/zeorliu/blog/item/281caf5141ce241e367abe82.html>用Servlet动态生成随机验证码(摘) zt
**改进：**
1，图形中的文字不支持中文，需要修改Font设置：
//Font f = new Font("Times New Roman",Font.PLAIN,18);//不支持中文
//g.setFont(new Font("Times New Roman",Font.PLAIN,18)));//不支持中文
g.setFont(new Font("MyFont", Font.ITALIC, fontSize*3/2)); 
2，定义多种输出方法，增加参数定义图片和字体的大小；
public static void nextJpg(OutputStream os,String code, int width, int height, int fontSize) throws IOException；
public static String nextJpg(String jpg_name, String code,int width,int height, int fontSize) throws IOException；
public static void nextJpg(HttpServletResponse response, String code, int width, int height, int fontSize) throws IOException；
3，允许多种输出（tableId=10,36,62）
private static char charstable10;//存放10个字符,在随机生成key时使用 
private static char charstable36;//存放 36个字符,在随机生成key时使用 
private static char charstable62;//存放 62个字符,在随机生成key时使用 
4，改为Rest模式，使用自定义的REST实现，（tableId=10,36,62，codeLen为输出随即码长度）
/rest/jpg/{tableId}/{codeLen} ＝ com.infothunder.restpay.ResourceJpg
5，（TODO）输出多种图片格式，不限于jpg图片，资源定义如下：
#/rest/jpg/{cTab}/{cLen}/{m}		= com.infothunder.restpay.ResourceJpg
/rest/jpg/{cTab}/{cLen}/{m}			= com.infothunder.restpay.ResourceJpgSms
6，使用方式：<span style="color:red">
/rest/jpg/10/8/m.jpg 只有数字，输出jpg格式
/rest/jpg/62/4/m.png 含数字和大小写，输出png格式
/rest/jpg/36/6/mobileNo.sms 定义ResourceJpgSms扩展，可以通过短信发送检验码，而不是图片检验码，mobileNo为手机号</span>
参考Servlet定义：

```java
public class RandomServlet extends HttpServlet{
	private static final long serialVersionUID = 4281511561201577496L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String randCode = RandomUtils.nextStr36(4);//nextStr62 nextStr10
		RandomUtils.nextJpg(response, randCode, 75, 20, 18);
		request.getSession().setAttribute("RANDOM_CODE", randCode);			
		System.out.println("# RandomServlet.doGet().nextJpg() = "+randCode);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		doGet(request,response); 
	} 
}
```

参考Rest资源定义

```java
public class ResourceJpg extends ResourceBase {
	private final static Logger _log = LoggerFactory.getLogger(ResourceJpg.class);
	protected final static int fontSize = 20;
	@Override public String getIdName() {
		//return "codeLen";//（如果未定义，则会调用doList而不是doShow）
		return "m";//（如果未定义，则会调用doList而不是doShow）
	}
	@Override public void doShow(HttpServletRequest req, HttpServletResponse res, Map uriAttr, String id) throws IOException, ServletException{
		String uri = Util.getMapValue(uriAttr, "URI", "");
		int cTab = Util.getMapValue(uriAttr, "cTab", 62);//==(62|36|10)
		int cLen = Util.getMapValue(uriAttr, "cLen", 4);//支持后缀 rest/jpg/10/4/m.jpg
		//int cLen = Integer.parseInt(id);//去掉了.xml后缀
		if (cLen<4)	cLen = 4;
		String randCode = null; 
		if (cTab==10) {			
			randCode = RandomUtils.nextStr10(cLen);
		}else if (cTab==36) {
			randCode = RandomUtils.nextStr36(cLen);
		}else {
			randCode = RandomUtils.nextStr62(cLen);
		}
		String ext = this.getUriAttribute("EXT", null);
		if (".jpg".equalsIgnoreCase(ext) || ".jpeg".equalsIgnoreCase(ext)) {
			RandomUtils.nextImage(res, randCode, cLen*(fontSize-2), fontSize, fontSize-2, "jpeg");
		}else if (".png".equalsIgnoreCase(ext)) {
			RandomUtils.nextImage(res, randCode, cLen*(fontSize-2), fontSize, fontSize-2, "png");
		}else if (".bmp".equalsIgnoreCase(ext)) {
			RandomUtils.nextImage(res, randCode, cLen*(fontSize-2), fontSize, fontSize-2, "bmp");
		}else {//和jpg等效 >> 为了方便扩展，调用子方法；
			this.doShowExt(req, res, uriAttr, id, ext, randCode);
		}
		req.getSession().setAttribute("RANDOM_CODE", randCode);
		_log.debug("# doShow({}).nextImage() = "+randCode, uri, ext);
	}
	@Override public void doList(HttpServletRequest req, HttpServletResponse res, Map uriAttr) throws IOException, ServletException{
		_log.debug("# doList()...{}", uriAttr);
	}
	protected void doShowExt(HttpServletRequest req, HttpServletResponse res, Map uriAttr, String id, String ext, String randCode) throws IOException, ServletException{
		int codeLen = randCode.length();
		RandomUtils.nextJpg(res, randCode, codeLen*(fontSize-2), fontSize, fontSize-2);
		//_log.debug("# doShowExt()...{}", randCode);
	}
}
```