jsp验证码加无刷新更新

来源:互联网 发布:sql数据库安全 编辑:程序博客网 时间:2024/05/22 10:40

JSP做无刷新的验证码:

一共两个页面:

第一个image.jsp

一下是Image.jsp源代码

<%@ page language="java" import="java.util.*,java.awt.image.*,java.awt.*,javax.imageio.*" pageEncoding="GBK" contentType="image/jpeg"%><!-- 记得contentType="image/jpeg" --><%!Color getRandColor(int start,int end,long seed){if(start>255){start=255;}Random random=new Random(seed);int r=start+random.nextInt(end+1-start);int g=start+random.nextInt(end+1-start);int b=start+random.nextInt(end+1-start);return new Color(r,g,b);} %><%int width=60;int height=20;//随机产生的验证码中的字母,可以设置多一点String[] str={"1","a","A","B","c","2","I","8","U","y"};BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//这就算是有纸了,需要知道宽度高度Graphics g=image.getGraphics();//这就算有笔了g.setColor(getRandColor(230,250,System.currentTimeMillis()));//这就算把笔蘸上颜色了g.fillRect(0,0,width,height);//填充底色Random random=new Random(System.currentTimeMillis());//画干扰线g.setColor(getRandColor(160,200,System.currentTimeMillis()));for(int i=0;i<50;i++){g.drawLine(random.nextInt(6),random.nextInt(15),random.nextInt(6)+random.nextInt(56),random.nextInt(7)+random.nextInt(17));}String check=new String();g.setFont(new Font("Times new Roman",Font.PLAIN,18));for(int i=0;i<4;i++){g.setColor(getRandColor(20,110,System.currentTimeMillis()+i*1000));//String ran=String.valueOf(random.nextInt(10));int temp=random.nextInt(10);String ran=str[temp];check+=ran;g.drawString(ran,6+i*13,16);//分别往上写数字}//可以通过session来获取随机产生的验证码session.setAttribute("check",check);g.dispose();//使图像生效//response.setCharacterEncoding("GBK");//request.setCharacterEncoding("GBK");ImageIO.write(image,"JPEG",response.getOutputStream());//将图像输出,三个参数分别为纸,格式,服务器相应的输出流out.clear();out=pageContext.pushBody();//加上这两句,tomcat就没有异常信息%>

然后在其他地方使用。

<body>    <img src="image.jsp" id="code"/> <a href="#" onclick="reload()">刷新</a>     <script>    function reload(){    document.getElementById("code").setAttribute("src","image.jsp?a="+new Date().getTime());    }    </script>  </body>

这样就可以实现使用加无刷新了

来自:小小孩,jsp验证码无刷新


原创粉丝点击