当前位置: 首页 > 图文教程 > Java技术 > J2EE > jsp生成验证码

J2EE
重复提交的问题
MVC和MVP的一些思考
J2EE流程
J2EE之我见
j2ee 13种核心技术
关于J2EE程序员的武器探讨
分析J2EE架构的6个最佳实践
J2EE WEB层的曙光 -- JSF
“J2EE 服务支撑平台(OTP)”解决方案
J2EE--如何实现servlet中的发信功能?
J2EE中的设计模式
XML和J2EE的完美结合
让 J2EE 脱离容器,你做得到吗?
J2EE会话外观模式与值对象
J2EEweb开发中的缓存问题的研究
J2EE与电子商务应用
J2EE:J2EE平台架构上开发CRM的技术过程控制
J2EE:XML和J2EE的组合技术
J2EE:Apache HTTPServer与Tomcat/JBoss的配置
J2EE:编程者你必须弄懂的问题

J2EE 中的 jsp生成验证码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 89 ::
收藏到网摘: n/a

调用方法    
  <img   src="http://...../getImg">    
   
  原理,在servlet中随机生成一个4位数字1000-9999    
  然后把这数字写入session    
  输出一个图片,上面写有这四个数字    
  在服务器端根据用户输入的数字和    
  session中的值比较。

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page language="java" import="java.util.*" %>
<%@ page language="java" import="java.io.*" %>
<%@ page language="java" import="java.awt.*" %>
<%@ page language="java" import="java.awt.image.*" %>
<%@ page language="java" import="com.sun.image.codec.jpeg.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title> </title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="Wang Shiqiang" />
  <meta name="keywords" content="Wang Shiqiang" />
  <meta name="description" content="" />
</head>

<body>
<%
    response.setContentType("text/html;charset=gb2312");
    request.setCharacterEncoding("gb2312");

    out.print("==================Test for thumbtail picture=============");

    //-----------------------上传完成,开始生成缩略图-------------------------  
    java.io.File file = new java.io.File("E:\\1110168154_58348.jpg");//saveurl);        //读入刚才上传的文件
    String newurl="E:\\1110168154_58348_min.jpg";//request.getRealPath("/")+url+filename+"_min."+ext;  //新的缩略图保存地址
    Image src = javax.imageio.ImageIO.read(file);                     //构造Image对象
    float tagsize=287;
    int old_w=src.getWidth(null);                                     //得到源图宽
    int old_h=src.getHeight(null); 
    int new_w=0;
    int new_h=0;                            //得到源图长
    int tempsize;
    out.print("<br/>the old width is :"+old_w+" the old height is "+old_h+"<br/>");
    float tempdouble;
    if(old_w>old_h){
     tempdouble=old_w/tagsize;
    }else{
     tempdouble=old_h/tagsize;
    }
    new_w=Math.round(old_w/tempdouble);
    new_h=Math.round(old_h/tempdouble);//计算新图长宽
    out.print("the new width is :"+new_w+" the new height is "+new_h+"<br/>");
    BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
    tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);       //绘制缩小后的图
    FileOutputStream newimage=new FileOutputStream(newurl);          //输出到文件流
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);     
    encoder.encode(tag);                                               //近JPEG编码
     newimage.close();  
    /*
    */
%>
</body>
</html>