一、实现图形验证码的基础类

VerifyCodeUtils.java,这个类是从网上摘抄的~

package com.comp.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random; import javax.imageio.ImageIO; public class VerifyCodeUtils{ //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符,以及占用太宽的字符W
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVXYZ";
private static Random random = new Random(); /**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
} /**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
} /**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
} /**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
}
} /**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions); g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h); Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4); //绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
} // 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
} shear(g2, w, h, c);// 使图片扭曲 g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.PLAIN, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
//AffineTransform affine = new AffineTransform();
//affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
//g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
} g2.dispose();
ImageIO.write(image, "jpg", os);
} private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
} private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
} private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
} private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
} private static void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2); for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
} } private static void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
} } }
}

二、Controller类的实现

controller类的代码:

    @RequestMapping(value="verifyCode", method = RequestMethod.GET)
public void verifyCode(Model model, Req req,HttpServletRequest request,HttpServletResponse response) {
//response.setContentType("img/jpeg");
try {
OutputStream outputStream=response.getOutputStream();
int w = 200, h = 80;
String code = VerifyCodeUtils.generateVerifyCode(4);
VerifyCodeUtils.outputImage(w, h, outputStream, code);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

注意看,我把

response.setContentType("img/jpeg");

这句注掉了,添加这句话的话,在浏览器中打开,不是查看图片,而是下载图片。去掉就不会下载了,网上的内容真是误人子弟。

不过加上的话,在jsp页面里面通过img标签显示图片也是没有问题的。

三、显示图片

在jsp页面显示这个图片:

<img src="user/verifyCode">

我这篇文章并没有完整的实现验证码,但是已经把最重要的生成验证码图片的功能实现了,想在登录的时候实现验证码功能,还需要把剩下的流程功能实现,我这里就不再累述了。

spring mvc实现登录验证码的更多相关文章

  1. 基于spring mvc的图片验证码实现

    本文实现基于spring mvc的图片验证码,分后台代码和前端页面的展现以及验证码的验证. 首看后台实现代码: @RequestMapping({"authCode"}) publ ...

  2. spring mvc生成注册验证码

    通过Spring MVC为系统添加验证码 1:布局登陆页面,用户名,密码,填写验证码的文本框,及验证码的图片及点击换图 <%@ taglib prefix="c" uri=& ...

  3. Spring MVC过滤器-登录过滤

    以下代码是继承OncePerRequestFilter实现登录过滤的代码: package com.test.spring.filter; import java.io.IOException; im ...

  4. spring mvc实现登录+异常

    登录页面login.jsp在webroot下 <body> <form action="user/login" method="post"&g ...

  5. Spring MVC 的核心应用-1

    使用Spring MVC实现登录.注销 配置文件applicationcontext-jdbc.xml <?xml version="1.0" encoding=" ...

  6. 结合开源软件kaptcha讲解登录验证码功能的实现

    一.验证码生成之配置使用kaptcha 使用google开源的验证码实现类库kaptcha,通过maven坐标引入 <dependency> <groupId>com.gith ...

  7. spring mvc 4.3.2 + mybatis 3.4.1 + mysql 5.7.14 +shiro 幼儿园收费系统 之 登录

    如标题,用spring mvc 4.3.2+mybatis 3.4.1 + mysql 5.7.14 +shiro 开发了一个用于幼儿园的管理系统. 功能模块 包括 账号,角色,权限管理. 幼儿档案管 ...

  8. Spring MVC 中使用 Google kaptcha 验证码

    验证码是抵抗批量操作和恶意登录最有效的方式之一. 验证码从产生到现在已经衍生出了很多分支.方式.google kaptcha 是一个非常实用的验证码生成类库. 通过灵活的配置生成各种样式的验证码,并将 ...

  9. Spring MVC Captcha 验证码

    本文专为不想一遍遍手写验证码代码的”懒猿“而生,只需要添加部分配置文件,拷贝一个控制层代码,就能在页面中方便使用.话不多说,进入主题: 一. Spring MVC 环境实现方式: 1.1 spring ...

随机推荐

  1. 在Hexo中渲染MathJax数学公式

    最近学机器学习涉及很多的数学公式,公式如果用截图显示,会比较low而且不方便.因此需要对Hexo做些配置,支持公式渲染.同时文末整理了各种公式的书写心得,比如矩阵.大小括号.手动编号.上下角标和多行对 ...

  2. HDU 5715 XOR 游戏 二分+字典树

    XOR 游戏 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5715 Description 众所周知,度度熊喜欢XOR运算(XOR百科). 今天,它 ...

  3. POJ 1904 King's Quest tarjan

    King's Quest 题目连接: http://poj.org/problem?id=1904 Description Once upon a time there lived a king an ...

  4. wikioi 1434 孪生素数 水题、素数模版

    1434 孪生素数 时间限制: 1 s 空间限制: 1000 KB 题目等级 : 白银 Silver 题目描述 Description 输出100以内的所有相差6的孪生素数:如, 5 11 7 13 ...

  5. Go语言Web框架gwk介绍 (一)

    今天看到Golang排名到前30名了,看来关注的人越来越多了,接下来几天详细介绍Golang一个web开发框架GWK. 现在博客园支持markdown格式发布文章么?后台的编辑器不太好用嘛. GWK ...

  6. How to check Ubuntu version

    Below you can find some tips on how to check Ubuntu version you are currently running. The first pla ...

  7. C#各种异常处理方式

    .NET的异常处理机制用来发现.处理运行时错误.如果开发人员没有提供异常的处理机制,就默认采用.NET的机制. 通常使用try...catch...finally捕获异常. try { //有可能发生 ...

  8. “System.InvalidOperationException”类型的未经处理的异常在 ESRI.ArcGIS.AxControls.dll 中发生

    问题描述: 新手们进行ArcGIS ArcObject开发时经常会遇到各种十分古怪的问题,比如下面的这个问题: “System.InvalidOperationException”类型的未经处理的异常 ...

  9. <jsp:directive.page import=""/>的用法和解释

    <jsp:directive.page import="zero.space.ch03.BookBean"/>    相当于    <%@ page import ...

  10. cocos2d-x 3.0 事件处理

    參考文章: star特530的CSDN博客:http://blog.csdn.net/star530/article/details/18325493 https://github.com/chuko ...