请问java 如何使用cookie来登录?我知道.net下有个叫做WebClient的类,可以把cookie加上实现登录。请教java源码例子,谢谢~

解决方案 »

  1.   

    Interface HttpServletResponse 
       addCookiepublic void addCookie(Cookie cookie)Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.Parameters:
    cookie - the Cookie to return to the client
      

  2.   

      <%
       //从提交的HTML表单中获取,用户名
       String userName=request.getParameter("username");
       //以"username", userName 值/对 创建一个Cookie
       Cookie theUsername=new Cookie("username",userName);
       response.addCookie(theUsername);
      %>
      ..............
      <%
       Cookie myCookie[]=request.getCookies();//创建一个Cookie对象数组
       for(int n=0;n=cookie.length-1;i++);//设立一个循环,来访问Cookie对象数组的每一个元素
       Cookie newCookie= myCookie[n];
       if(newCookie.getName().equals("username")); //判断元素的值是否为username中的值
        {%>
         你好,<%=newCookie.getValue()%>!//如果找到后,向他问好
        <%}
      %>http://blog.csdn.net/xiaoyycq/article/details/3891266
    百度一下就搜到了,楼主要多多百度哦
      

  3.   


    <%Cookie[] cookies = request.getCookies();
    String user_name = "";
    String user_pass = "";
    if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
    if (cookies[i].getName().equals("userName")) {
    user_name = cookies[i].getValue();
    } else if (cookies[i].getName().equals("userPass")) {
    user_pass = cookies[i].getValue();
    }
    }
    }
     %>
    <center>
    <html:form action="login.do" method="post" onsubmit="return checkLogin();">
    <table class="login">
    <tr>
    <td>
    <img src="imgs/login_center.jpg">
    </td>
    </tr>
    <tr>
    <td>
    用户名&nbsp;&nbsp;
    <input title="java" type="text" name="name" id="login_account" style="width:150px" 
    value="<%=user_name %>">
    </td>
    </tr>
    <tr>
    <td>
    <font class="warning">
    <%=info%>
    </font>
    密 码&nbsp;&nbsp;
    <input title="java" type="password" name="pass" id="login_password" style="width:150px"
    value="<%=user_pass %>">
    </td>
    </tr>
    <tr>
    <td>
    <input class="btn" type="submit" value="登录">
    </td>
    </tr> </table>
    </html:form>