利用重写url机制简单实现验证码换一张的功能

重写URL机制:为了保证一个url的地址唯一,可每次向服务器传递的参数不一样即可。

由数据请求的抱头信息可分析到:抱头信息包括http协议,IP地址,端口号,工程名,请求参数列表,要想访问的资源不发生变化,只能变化参数连表。

此处在实现验证码的换一张的功能时,就是利用了改变参数列表的值进行刷新。

详细代码实现:

<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.awt.Font"%>
<%@page import="java.awt.Color"%>
<%@page import="java.awt.Graphics"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@ page contentType="image/jpeg" language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
int w=100;
int h=30;
BufferedImage bi=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics g=bi.getGraphics();
Color c=g.getColor();
Font f=g.getFont(); 
Random r=new Random();
Color bg=new Color(150+r.nextInt(100),150+r.nextInt(100),150+r.nextInt(100));
g.setColor(bg);
g.fillRect(0, 0, w, h);
String code="";

for(int i=1;i<=4;i++){
int num=r.nextInt(10);
code=code+num;
Color num_c=new Color(r.nextInt(150),r.nextInt(150),r.nextInt(150));
g.setColor(num_c);
g.drawString(String.valueOf(num), 20*i, h/2);
}
request.getSession().setAttribute("code", code);
//清空缓存
response.setHeader("pragma", "bo-cache");
response.setHeader("cache-control", "bo-cache");
response.addDateHeader("expires", 0);
ImageIO.write(bi, "jpeg", response.getOutputStream());
out.close();
 %>
添加登录页面:

<%@ page contentType="text/html; charset=utf-8"  language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
function changeimage(){
var d=new Date();//生成时间戳,
document.getElementById("img").src="image.jsp?t="+d;//由变化的时间使参数连表发生变化,url重写
}

</script>
  </head>
  
  <body>
  <font color="red">${requestScope.msg }</font>
   <form action="loginServlet" method="post">
   name:<input type="text" name="uname"><br>
   pwd:<input type="pwd" name="upwd"><br>
   code:<input type="text" name="code" size="5"><img id="img" alt="" src="image.jsp "><a οnclick="changeimage()">换一张</a><br>
   <input type="submit" >
   
   </form>
  </body>
</html>
利用时间的变化,每次生成时间戳,传参给请求的url,达到重写url的目的,从而实现了换一张的刷新功能。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值