1、用Servlet返回相应的文件的时候我们就调用response.setContextType(“image/JPEG”);方法就可以了,这次的案例是写一个验证码的案例。代码和注释内容如下所示:
private static Random ran = new Random(); //声明一个静态的random全局变量
--准备工作.一个得到随即验证码文字的方法,一个随即颜色的方法,一个得到反色颜色的方法
//得到验证码的文字
public String getRamdomString(){
char[] cs = {'1','2','3','4','5','6','7','8','9','A'};
StringBuffer sb = new StringBuffer(); //创建sb拼装验证码String
for(int i=0 ; i < 6 ; i++){
char a = cs[ran.nextInt(cs.length)]; //用random搭配数组的length方法,得到数组的随即字节
sb.append(String.valueOf(a));
}
return sb.toString();
}
//获得随即的颜色
public Color getBackColor(){
return new Color(ran.nextInt(225),ran.nextInt(225),ran.nextInt(225));
}
//获得颜色的反色
public Color getReverseColor(Color c){
return new Color(225-c.getRed(),225-c.getGreen(),225-c.getBlue());
}
//生成验证码的方法
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException {
response.setContentType("image/JPEG"); //设置返回文件格式
String code = this.getRamdomString(); //得到随即字符串
Color backcolor = this.getBackColor(); //得到背景颜色
Color reverseColor= this.getReverseColor(backcolor); //得到背景色的反色
int width = 100;
int height = 30;
//new一个图片流,有长度,宽度和type3个参数
BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D gg= bi.createGraphics(); //得到绘画工具
Font f = new Font(Font.SANS_SERIF,Font.BOLD,16); //声明一个font
gg.setFont(f);
gg.setColor(backcolor); //设置背景色
gg.fillRect(0, 0, width, height); //绘制背景
gg.setColor(reverseColor); //设置绘画工具反色背景色
gg.drawString(code, 18, 20); //写字符串验证码宽18,高20开始
for(int i = 0 ; i < 100 ; i++){ //画100个噪点
gg.setColor(new Color(ran.nextInt(225),ran.nextInt(225),ran.nextInt(225)));
gg.drawRect(ran.nextInt(width), ran.nextInt(height),1,1); //限制宽,高范围
}
ServletOutputStream sos = response.getOutputStream(); //得到返回对象
JPEGImageEncoder jie = JPEGCodec.createJPEGEncoder(sos);//得到编码器。
jie.encode(bi); //将bi编码至图片
bi.flush(); //写至客户端
sos.close();
}
2、WEB开发由浅入深系列BLOG-2(Servlet编写验证码)
最新推荐文章于 2022-02-14 23:36:56 发布