用户在登录页输入用户名和密码后,点击“记住用户名和密码”复选框,登录后先检查此用户名密码的用户是否存在,如果存在就把用户名密码存进cookie并发回客户端;用户再次进入登录页时,会先request.getCookies(),如果得到的cookies不为null,则通过cookie.getName()与后台存入的cookie对比,如果用户名和密码都匹配就给两个输入框赋cookie中得值。目前我遇到的问题有两个,1.是新存的cookie不能覆盖同名cookie,2.jsp页面用request取cookie得到的是null。现在把代码贴出:
jsp code:
<%@ page contentType="text/html; charset=gb2312" language="java" import="com.image.entity.*,java.util.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>用户登录</title>
<style>
BODY {
PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 12px; PADDING-BOTTOM: 0px;  PADDING-TOP: 100px; MARGIN: 0px; text-align: center;
}
.wenzi {
FONT-SIZE: 12px; color:#000000; FONT-FAMILY: '宋体'; text-align: left; padding-left:25px;
}
.STYLE1 {color: #FFFFFF}
.STYLE2 {FONT-SIZE: 12px; color: #FFFFFF; FONT-FAMILY: '宋体'; text-align: left; padding-left: 25px; }
</style>
<script>
function qingkong(){
document.all.uname.value="";
document.all.psd.value="";
document.all.namepsd.value="";
}
function checkform(){
var uname = document.getElementById("uname");
var psd = document.getElementById("psd");
if(uname.value.length==0){
alert("请输入您要登录的用户名!");
return false;
}
if(psd.value.length==0){
alert("请输入您要登录的密码!");
return false;
}
}
</script>
</head>
<body>
<%
PicUser user = (PicUser)session.getAttribute("userbean");
if(user!=null){
session.invalidate(); 
}
String usernameCookie = null;    
String passwordCookie = null;
System.out.println(request);    
Cookie[] cookies = request.getCookies();
 %>
<div align="justify">
  <table border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
      <td ><img src="images/lobg1.jpg"  height="41%" /></td>
    </tr>
    <tr>
      <td bgcolor="#2479B2">   
  <table align="right" width="500" border="0" cellspacing="0" cellpadding="0">
      <tr>
          <td>
          <form method="post" onsubmit="return checkform()" action="servlet/UserService?code=checklogin">
          <%
          if (null!=cookies ||cookies != null) { 
  for (Cookie cookie : cookies) {  
    if("username".equals(cookie.getName())){    
      usernameCookie = cookie.getValue(); // 得到cookie的用户名   
      System.out.println(usernameCookie);
    }    
    if("pwd".equals(cookie.getName())){    
      passwordCookie = cookie.getValue(); // 得到cookie的密码
      System.out.println(passwordCookie); 
    }    
  }  
          if ((usernameCookie != null && passwordCookie != null)||(null!=usernameCookie && null!=passwordCookie)) { // 如果存在
%>
<table width="216" height="10%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td height="27"  class="STYLE2">用户名:</td>
<td width="129">
                  <input name="uname" id="uname"  tabindex="10" type="text" class="table_select" value="<%=usernameCookie %>"  style=" height:20;width:123px;" />
</td>
              </tr>
              <tr>
                <td height="27" class="STYLE2">密&nbsp;&nbsp;码:</td>
<td>
                  <input name="psd" id="psd" tabindex="11" type="password" class="table_select" value="<%=passwordCookie %>" style=" height:20;width:123px" />
</td>
              </tr>
  <tr>
                <td colspan="2"  valign="top" height="20"  align="center" class="wenzi" >    &nbsp;&nbsp;
                  <span class="STYLE1">
                  <input type="checkbox" id="namepsd" name="namepsd" value="mian" />
                  记住用户名和密码</span></td>
  </tr>
  <tr>
     <td width="87" align="right"><input type="submit" value="登录" /></td> <td align="center"><input type="button" value="重置" onClick="qingkong()" /></td>
      </tr>     
            </table>

<%
      }else{
   %>
   <table width="216" height="104" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td height="27"  class="wenzi STYLE1">用户名:</td>
<td width="129">
                  <input name="uname" id="uname" tabindex="10" type="text" class="table_select" value=""  style=" height:20;width:123px;" />
</td>
              </tr>
              <tr>
                <td height="27" class="STYLE2">密&nbsp;&nbsp;码:</td>
<td>
                  <input name="psd" id="psd" tabindex="11" type="password" class="table_select" value="" style=" height:20;width:123px" />
</td>
              </tr>
  <tr>
                <td colspan="2"  valign="top" height="20"  align="center" class="wenzi" >    &nbsp;&nbsp;
                  <input type="checkbox" id="namepsd" name="namepsd" value="mian" />
                  <span class="STYLE1">记住用户名和密码</span></td>
  </tr>
  <tr>
     <td width="87" align="right"><input  type="submit"  value="登录" /></td> <td align="center"><input type="button" value="重置" onClick="qingkong()" /></td>
      </tr>     
            </table> 
            <%
            }
         }else{
         %>
         <table width="216" height="104" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td height="27"  class="STYLE2">用户名:</td>
<td width="129">
                  <input name="uname" id="uname" tabindex="10" type="text" class="table_select" value=""  style=" height:20;width:123px;" />
</td>
              </tr>
              <tr>
                <td height="27" class="STYLE2">密&nbsp;&nbsp;码:</td>
<td>
                  <input name="psd" id="psd" tabindex="11" type="password" class="table_select" value="" style=" height:20;width:123px" />
</td>
              </tr>
  <tr>
                <td colspan="2"  valign="top" height="20"  align="center" class="wenzi" >    &nbsp;&nbsp;
                  <input type="checkbox" id="namepsd" name="namepsd" value="mian" />
                  <span class="STYLE1">记住用户名和密码</span></td>
  </tr>
  <tr>
     <td width="87" align="right"><input  type="submit"  value="登录" /></td> <td align="center"><input type="button" value="重置" onClick="qingkong()" /></td>
      </tr>     
            </table> 
         
         <%
         }
         %>
            </form>             
          </td>          
        </tr>
      </table>
  </td>
    </tr>    
  </table>
</div>
</body>
</html>servlet code:
                           String uname = request.getParameter("uname");
String psd= request.getParameter("psd");
String ns = request.getParameter("namepsd");
PicUser user = userdao.getUserBylogin(uname, psd);
if(null==user){
String str="用户名或密码错误,请重新登录!";
//跳回登陆页面
}else{
if(null==ns){
HttpSession session = request.getSession();
session.setAttribute("userbean", user);
response.sendRedirect("../index.jsp");
}else{
if("mian"==ns ||"mian".equals(ns)||ns.equals("mian")){
Cookie Ckie1 = new Cookie("username", user.getUsername());  //实例对象 
Ckie1.setMaxAge(60 * 60 * 24 * 14);  //设置存活时间 
response.addCookie(Ckie1); //保存在客户端

Cookie Ckie2 = new Cookie("pwd", psd);  //实例对象 
Ckie2.setMaxAge(60 * 60 * 24 * 14);  //设置存活时间 
response.addCookie(Ckie2); //保存在客户端 

 }
}
HttpSession session = request.getSession();
session.setAttribute("userbean", user);
response.sendRedirect("../index.jsp");
}请各位高手帮我看看是怎么回事,以及应该怎么改,谢谢.....

解决方案 »

  1.   

    你直接这样Cookie[] cookies = request.getCookies(); 肯定是空的,
    应该通过索引来获取
    Cookie   myCookie[]=request.getCookies();   
    Cookie   newCookie=   myCookie[0]; 试试看行不  
      

  2.   

    你这个代码是对的 至少不会是空 除非客户端本身就没cookie给你个类package www.gbsou.com.common;import java.util.*;
    import org.apache.http.client.CookieStore;
    import org.apache.http.cookie.Cookie;
    import org.apache.http.cookie.CookieIdentityComparator;/**
     * Cookie操作类
     *
     * @author shaliang
     * @date 2009-04-29
     * @version 1.0
     */
    public class UpdateableCookieStore implements CookieStore {    public UpdateableCookieStore() {
        }    /**
         * 根据Cookie名来获得其索引
         *
         * @param cookieName cookie名
         * @return 返回指定Cookie的索引 没有则返回-1
         */
        private int getIndexOfCookie(String cookieName) {
            for (int i = 0; i < cookies.size(); i++) {
                Cookie c = (Cookie) cookies.get(i);
                if (c.getName().equals(cookieName))
                    return i;
            }        return -1;
        }    /**
         * 获取Cookie
         *
         * @param name Cookie名
         * @return Cookie对象
         */
        public Cookie getCookie(String name) {
            int index = getIndexOfCookie(name);
            if (index == -1)
                return null;
            else
                return (Cookie) cookies.get(index);
        }    /**
         * 根据Cookie名删除Cookie对象
         *
         * @param name Cookie名
         */
        public void removeCookie(String name) {
            int index = getIndexOfCookie(name);
            if (index == -1) {
                return;
            } else {
                cookies.remove(index);
                return;
            }
        }    /**
         * 增加Cookie对象
         *
         * @param cookie 要写入的Cookie对象
         */
        public synchronized void addCookie(Cookie cookie) {
            if (cookie != null) {
                for (Iterator it = cookies.iterator(); it.hasNext();)
                    if (cookieComparator.compare(cookie, (Cookie) it.next()) == 0) {
                        it.remove();
                        break;
                    }            if (!cookie.isExpired(new Date()))
                    cookies.add(cookie);
            }
        }    /**
         * 增加一组Cookie对象
         *
         * @param cookie 要写入的Cookie对象数组
         */
        public synchronized void addCookies(Cookie cookies[]) {
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++)
                    addCookie(cookies[i]);        }
        }    /**
         * 获取Cookie对象集合
         */
        public synchronized List getCookies() {
            return Collections.unmodifiableList(cookies);
        }    /**
         * 清除过期的Cookie
         * @param date 指定日期
         */
        public synchronized boolean clearExpired(Date date) {
            if (date == null)
                return false;
            boolean removed = false;
            for (Iterator it = cookies.iterator(); it.hasNext();)
                if (((Cookie) it.next()).isExpired(date)) {
                    it.remove();
                    removed = true;
                }        return removed;
        }    public String toString() {
            return cookies.toString();
        }    /**
         * 清除所有Cookie
         */
        public synchronized void clear() {
            cookies.clear();
        }    private final ArrayList cookies = new ArrayList();
        private final Comparator cookieComparator = new CookieIdentityComparator();
    }
      

  3.   

    private void getCookies(HttpServletRequest request){
    String username="";
    String password="";
    Cookie cookie [] = request.getCookies();
    for(Cookie c:cookie){
    String key = c.getName();
    if("username".equals(key)){
    username = c.getValue();
    }
    if("password".equals(key)){
    password = c.getValue();
    }

    request.getSession().setAttribute("username", username);
    request.getSession().setAttribute("password", password);
    }
    }