日期:2014-05-18  浏览次数:20705 次

java文件中怎么不能从会话中取值
在java文件中,设置了session的值。然后在java文件中,在把会话中的值session取出来。但是取不出来。在jsp页面这么做可以。为什么?
代码如下
Token.java
public static void saveToken(HttpServletRequest request){
String tokey=new Date().getTime()+"";//根据当前日期和时间转换成字符串
request.getSession().setAttribute("token",tokey);
}
//判断用户请求页面的session和当前会话中的session是否一致
public static boolean isToken(HttpServletRequest request){
boolean bool=false;
String token1=(String)request.getSession().getAttribute("token");
System.out.println("token1======================"+token1);
String token2=request.getParameter("token");
System.out.println("token2====================="+token2);
if(token1.equals(token2)){
bool=true;
}
return bool;
}
//将会话中的标识号清除
public static void resetToken(HttpServletRequest request){
request.getSession().setAttribute("token","");
}


  ValidateToken.java代码如下
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
if(Token.isToken(request)){
Token.resetToken(request);
request.setAttribute("userName",request.getParameter("userName"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("birthday",request.getParameter("birthday"));
request.setAttribute("tel",request.getParameter("tel"));
request.getRequestDispatcher("result.jsp").forward(request,response);
}else{
PrintWriter out=response.getWriter();
out.print("<script language='javascript'>");
out.print("alert('您已经提交申请了,请不要重复进行提交')");
out.print("history.go(-1)");
out.print("</script>");
out.close();
}
}

jsp页面 userReg.jsp代码如下
<form action="ValidateToken" method="post">
  姓名:<input name="userName" type="text"/><br>
  生日:<input name="birthday" type="text"/><br>
  电话:<input name="tel" type="text"/><br>
  邮箱:<input name="mail" type="text"><br>

  <%
  String token=(String)request.getSession().getAttribute("token");
  out.print("token========================"+token);
  //String tokey=new Date().getTime()+"";
  //request.getSession().setAttribute("took",tokey);
  //String token=(String)request.getSession().getAttribute("took");
  //out.print("token=============="+token);
  %>
  <input type="hidden" name="token" value='<%=request.getSession().getAttribute("token") %>'><br>


  <input type="submit" value="提交">&nbsp;&nbsp;
  <input type="reset" value="重置"