后台产生验证码图片,然后以图片流的形式响应给客户端
制作验证码图片
ValidateCodeImage.java
@Component
public class ValidateCodeImage {
// 验证码字符集
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
// 字符数量
private static final int SIZE = 4;
// 干扰线数量
private static final int LINES = 5;
// 宽度
private static final int WIDTH = 80;
// 高度
private static final int HEIGHT = 40;
// 字体大小
private static final int FONT_SIZE = 28;
/**
* 生成随机验证码及图片
* 返回的数组中,第1个值是验证码,第2个值是图片
*/
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
// 1.创建空白图片
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.获取图片画笔
Graphics graphic = image.getGraphics();
// 3.设置画笔颜色
graphic.setColor(Color.LIGHT_GRAY);
// 4.绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 5.画随机字符
Random ran = new Random();
for (int i = 0; i <SIZE; i++) {
// 取随机字符索引
int n = ran.nextInt(chars.length);
// 设置随机颜色
graphic.setColor(getRandomColor());
// 设置字体大小
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 画字符
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT / 2);
// 记录字符
sb.append(chars[n]);
}
// 6.画干扰线
for (int i = 0; i < LINES; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
// 7.返回验证码和图片
return new Object[]{sb.toString(), image};
}
/**
* 随机取色
*/
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
/* public static void main(String[] args) throws IOException {
Object[] objs = createImage();
BufferedImage image = (BufferedImage) objs[1];
System.out.println("验证码:"+objs[0]);
OutputStream os = new FileOutputStream("WebRoot/Common/validatecode/yzm.png");
ImageIO.write(image, "gif", os);
os.close();
}*/
}
前台jsp调用:
<img alt="验证码" id="yzm" src="${pageContext.request.contextPath}/yzm.action" onclick="reloadcode()" title="点击更换验证码" style="cursor: pointer; padding-left:10px;" />
action响应
@RequestMapping(value="/yzm.action")
@ResponseBody
public String createYZMimage(HttpServletRequest request,HttpServletResponse response){
Object[] objs = yzmimage.createImage();
BufferedImage image=(BufferedImage) objs[1];
System.out.println("验证码:"+objs[0]);
yzmCode=(String) objs[0];
//String path="";
try {
ImageIO.write(image, "gif", response.getOutputStream());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "yzmSuccess";
}
看不清换一张验证码
// 看不清 换一张验证码
function reloadcode(){
document.getElementById("yzm").src = "${pageContext.request.contextPath}/yzm.action?s=" + Math.random();
}
写在这边,应该也就可以了,但是对于初学者需要注意到的是@ResponseBody需要在spring的配置文件去描述一下
<!-- 配置使用@ResponseBody方法返回数据的bean -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
<list>
<!-- 配置该bean是为了解决返回字符串的中文乱码问题,因为StringHttpMessageConverter默认编码为ISO-8859-1 -->
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 返回JSON数据时一定要配置该bean -->
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
希望这个程序能帮助到你们,本人亲测这个程序有用。