(转载)session token机制

http://blog.chinaunix.net/uid-26642709-id-3061264.html

使用session token时,必须用struts2表标签库,不能用html
通过session token防止重复提交:
当客户端请求页面时,服务器会通过token标签生成一个随机数,并且将随机数放置到session当中,然后将随机数发向客户端;如果客户第一次提交,那么浏览器会将该随机数发往服务器,服务器端会接收到该随机数并且与session中所保存的随机数进行比较,这时两者的值是相同的,服务器认为是第一次提交,并且将更新服务器端的这个随机数值;如果此时再次重复提交,那么客户端向服务器端的随机数还是之前的那个,而服务器端的随机数则已经发生了变化,两者不同,服务器就认为这事重复提交,进而转向invalid.token所指向的结果页面。
 
token.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib prefix = "s" uri= "/struts-tags"   %>  
  <body>
 <s:form action = "token.action" theme = "simple">
 username: <s:textfield name = "username"></s:textfield><br>
 password:<s:password name = "password"></s:password><br>
 
 <s:token></s:token>
 <s:submit value = "submit "></s:submit>
  
 </s:form>
  </body>
</html>
struts.xml

    <action name = "token" class = "com.shengsiyuan.struts2.TokenAction">
     <result name = "success">/tokenSuccess.jsp</result>
     <result name = "invalid.token">tokenFail.jsp</result> <!-- 次是不时input,算是特例 -->
  <interceptor-ref name = "token"></interceptor-ref>
  <interceptor-ref  name= "defaultStack"></interceptor-ref>
    </action>
   
TokenAction.java
package com.shengsiyuan.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class TokenAction extends ActionSupport 
{
 private String username ; 
 private String password ;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 } 
 @Override
 public String execute() throws Exception {
  return SUCCESS ;
 }
}
tokenSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib prefix = "s" uri = "/struts-tags" %>
 <html>
  <body>  
 username:<s:property value = "username"/><br>
 password:<s:property value = "password"/>
 

  </body>
</html>
tokenFail.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
  <body>
 不用重复提交表单
  </body>
</html>

posted on 2016-03-11 10:43  吴号虎  阅读(2251)  评论(0编辑  收藏  举报

导航