java怎么拦截某个对象
273
2023-07-29
java实现登录验证码
本文实例为大家分享了java实现登录验证码的具体代码,供大家参考,具体内容如下
1、ValidateCode.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import org.springframework.stereotype.Service;
/**
* 登录验证码
*
*/
public class ValidateCode {
/**
* 得到验证码图片
* @param out
* @param number 验证数字
* @throws ServletException
* @throws IOException
*/
public void getImage(OutputStream out,String number)
throws ServletException, IOException {
//0.创建空白图片
BufferedImage image=new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
//1.获取图片画笔
Graphics g = image.getGraphics();
Random r=new Random();
/http:///2.设置画笔颜色(Random类中的nextInt(n)返回一个大于等于0,小于n的随机数)
g.setColor(new Color(r.nextInt(255),r.nextInt(255), r.nextInt(255)));
//3.绘制矩形的背景
g.fillRect(0, 0, 100, 30);
//4.调用自定义的方法,获取长度为4的字母数字组合的字符串
g.setColor(new Color(0,0,0));
g.setFont(new Font(null,Font.BOLD,24));
//5.设置颜色字体后,绘制字符串(x/y,最左边字符所处的位置)
g.drawString(number, 20, 24);
//6.绘制8条干扰线(alpha表示透明度)
for(int i=0;i<8;i++){
g.setColor(new Color(r.nextInt(255),r.nextInt(255), r.nextInt(255),r.nextInt(255)));
g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
}
ImageIO.write(image, "jpeg", out);
}
//自定义方法,获取长度为size的字母数字组合的字符串
public String getNumber(int size){
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String number="";
Random r = new Random();
for(int i=0;i number+=str.charAt(r.nextInt(str.length())); } return number; } } 2、Controller @RequestMapping(value = "/check",method={RequestMethod.GET}) @ResponseBody public void check(HttpServletRequest req) { try { HttpServletResponse response = this.getResponse(); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + "vcode.jpeg"); String number = validateCode.getNumber(4); validateCode.getImage(response.getOutputStream(),number); } catch (Exception e) { } } 3、html 效果图
number+=str.charAt(r.nextInt(str.length()));
}
return number;
}
}
2、Controller
@RequestMapping(value = "/check",method={RequestMethod.GET})
@ResponseBody
public void check(HttpServletRequest req) {
try {
HttpServletResponse response = this.getResponse();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + "vcode.jpeg");
String number = validateCode.getNumber(4);
validateCode.getImage(response.getOutputStream(),number);
} catch (Exception e) {
}
}
3、html
效果图
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~