日期:2014-05-17  浏览次数:20881 次

jsp 保存用户名密码问题
index.jsp
<%@ page contentType="text/html;charset=gb2312"%>
<html>
<head>
<title>登陆</title>
</head>
<body>
<center>
<h1>
<font color="blue">
用户登录
</font>
</h1>
<hr>
<form action=1.jsp method=post>
用户名称:<input type="text" value=<%=request.getAttribute("loginname")%> name=loginname /><br>
密码: <input type="Password" value=<%=request.getAttribute("loginpass")%> name=loginpass /><br>
<input type=checkbox name=rememberme1 value=on>记住用户名<br>
<input type=checkbox name=rememberme2 value=on>记住密码<br>
<input type=submit value="登陆">
<input type=reset value="重置"><BR>
</center>
</body>
</html>
1.jsp
<%@ page contentType="text/html;charset=gb2312"%>
<%!String name;%>  
<%!String pass; %>
<%
String userName=request.getParameter("loginname");
String userPass=request.getParameter("loginpass");
String rememberMe1=request.getParameter("rememberme1");
String rememberMe2=request.getParameter("rememberme2");
boolean bool=false;
if (userName.equals("abc") && userPass.equals("123")){
  if(rememberMe1 != null && rememberMe1.equals("on")){
  Cookie myCookie1=new Cookie("cookiename",userName);
  response.addCookie(myCookie1);
  myCookie1.setMaxAge(60*60*24);
  session.setAttribute("loginname",name);
  }
  if(rememberMe2 != null && rememberMe2.equals("on")){
  Cookie myCookie2=new Cookie("cookiepass",userPass);
  response.addCookie(myCookie2);
  myCookie2.setMaxAge(60*60*24); 
  session.setAttribute("loginpass",pass);
  }
  bool=true; 
  }
  Cookie cookies[]=request.getCookies();  
  if (cookies != null) {
  name=null;  
  pass=null;  
  for (int i = 0; i < cookies.length; i++) {  
  Cookie cookie = cookies[i];  
  if (cookie.getName().equals("cookiename")) {  
  name = cookie.getValue(); 
   
  System.out.println("1234");
  }  
  if (cookie.getName().equals("cookiepass")) {  
  pass = cookie.getValue();
   
  System.out.println("4");
  }  
  }  
  if(bool){  
  response.sendRedirect("login.jsp");  
  }
  } 
%>
login.jsp
<%@ page contentType="text/html;charset=gb2312"%>
登陆成功
<a href=index.jsp>重新登录</a>



能获取到cookie但是密码和用户名不保存求助

------解决方案--------------------
你放值的时候用的是session,session.setAttribute("loginpass",pass);
取值时却是request,value=<%=request.getAttribute("loginname")%肯定取不到的啊,要一致