---
title: "JSP的Cookie在登录中的应用"
author: "cakin24"
date: "2017-10-08T08:37:51Z"
tags: []
categories: ["编程语言"]
slug: "jsp-cookie"
draft: false
lastmod: "2017-10-08T08:37:51Z"
id: 2395463
url: "https://cakin24.iteye.com/blog/2395463"
---

一 功能需求

实现记忆用户名和密码功能。

 

二 代码

1、login.jsp

&lt;%@ page language="java" import="java.util.\*,[java.net](http://java.net/).\*" contentType="text/html; charset=utf-8"%&gt;

&lt;%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%&gt;

 

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

&lt;html&gt;

  &lt;head&gt;

    &lt;base href="&lt;%=basePath%&gt;"&gt;

   

    &lt;title&gt;My JSP 'index.jsp' starting page&lt;/title&gt;

        &lt;meta http-equiv="pragma" content="no-cache"&gt;

        &lt;meta http-equiv="cache-control" content="no-cache"&gt;

        &lt;meta http-equiv="expires" content="0"&gt;   

        &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;

        &lt;meta http-equiv="description" content="This is my page"&gt;

        &lt;!--

        &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;

        --&gt;

  &lt;/head&gt;

 

  &lt;body&gt;

    &lt;h1&gt;用户登录&lt;/h1&gt;

    &lt;hr&gt;

    &lt;%

      request.setCharacterEncoding("utf-8");

      String username="";

      String password = "";

      Cookie\[] cookies = request.getCookies();

      if(cookies!=null&&cookies.length&gt;0)

      {

           for(Cookie c:cookies)

           {

              if(c.getName().equals("username"))

              {

                   username =  URLDecoder.decode(c.getValue(),"utf-8");

              }

              if(c.getName().equals("password"))

              {

                   password =  URLDecoder.decode(c.getValue(),"utf-8");

              }

           }

      }

    %&gt;

    &lt;form name="loginForm" action="dologin.jsp" method="post"&gt;

       &lt;table&gt;

         &lt;tr&gt;

           &lt;td&gt;用户名：&lt;/td&gt;

           &lt;td&gt;&lt;input type="text" name="username" value="&lt;%=username %&gt;"/&gt;&lt;/td&gt;

         &lt;/tr&gt;

         &lt;tr&gt;

           &lt;td&gt;密码：&lt;/td&gt;

           &lt;td&gt;&lt;input type="password" name="password" value="&lt;%=password %&gt;" /&gt;&lt;/td&gt;

         &lt;/tr&gt;

         &lt;tr&gt;

           &lt;td colspan="2"&gt;&lt;input type="checkbox" name="isUseCookie" checked="checked"/&gt;十天内记住我的登录状态&lt;/td&gt;

         &lt;/tr&gt;

         &lt;tr&gt;

           &lt;td colspan="2" align="center"&gt;&lt;input type="submit" value="登录"/&gt;&lt;input type="reset" value="取消"/&gt;&lt;/td&gt;

         &lt;/tr&gt;

       &lt;/table&gt;

    &lt;/form&gt;

  &lt;/body&gt;

&lt;/html&gt;

2、dologin.jsp

&lt;%@ page language="java" import="java.util.\*,[java.net](http://java.net/).\*" contentType="text/html; charset=utf-8"%&gt;

&lt;%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%&gt;

 

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

&lt;html&gt;

  &lt;head&gt;

    &lt;base href="&lt;%=basePath%&gt;"&gt;

   

    &lt;title&gt;My JSP 'dologin.jsp' starting page&lt;/title&gt;

   

        &lt;meta http-equiv="pragma" content="no-cache"&gt;

        &lt;meta http-equiv="cache-control" content="no-cache"&gt;

        &lt;meta http-equiv="expires" content="0"&gt;   

        &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;

        &lt;meta http-equiv="description" content="This is my page"&gt;

        &lt;!--

        &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;

        --&gt;

 

  &lt;/head&gt;

 

  &lt;body&gt;

    &lt;h1&gt;登录成功&lt;/h1&gt;

    &lt;hr&gt;

    &lt;br&gt;

    &lt;br&gt;

    &lt;br&gt;

    &lt;%

       request.setCharacterEncoding("utf-8");

       //首先判断用户是否选择了记住登录状态

       String\[] isUseCookies = request.getParameterValues("isUseCookie");

       if(isUseCookies!=null&&isUseCookies.length&gt;0)

       {

          //把用户名和密码保存在Cookie对象里面

          String username = URLEncoder.encode(request.getParameter("username"),"utf-8");

          //使用URLEncoder解决无法在Cookie当中保存中文字符串问题

          String password = URLEncoder.encode(request.getParameter("password"),"utf-8");

         

          Cookie usernameCookie = new Cookie("username",username);

          Cookie passwordCookie = new Cookie("password",password);

          usernameCookie.setMaxAge(864000);

          passwordCookie.setMaxAge(864000);//设置最大生存期限为10天

          response.addCookie(usernameCookie);

          response.addCookie(passwordCookie);

       }

       else

       {

          Cookie\[] cookies = request.getCookies();

          if(cookies!=null&&cookies.length&gt;0)

          {

             for(Cookie c:cookies)

             {

                if(c.getName().equals("username")||c.getName().equals("password"))

                {

                    c.setMaxAge(0); //设置Cookie失效

                    response.addCookie(c); //重新保存。

                }

             }

          }

       }

    %&gt;

    &lt;a href="users.jsp" target="\_blank"&gt;查看用户信息&lt;/a&gt;

   

  &lt;/body&gt;

 

&lt;/html&gt;

3、users.jsp

&lt;%@ page language="java" import="java.util.\*,[java.net](http://java.net/).\*" contentType="text/html; charset=utf-8"%&gt;

&lt;%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%&gt;

 

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

&lt;html&gt;

  &lt;head&gt;

    &lt;base href="&lt;%=basePath%&gt;"&gt;

   

    &lt;title&gt;My JSP 'users.jsp' starting page&lt;/title&gt;

   

        &lt;meta http-equiv="pragma" content="no-cache"&gt;

        &lt;meta http-equiv="cache-control" content="no-cache"&gt;

        &lt;meta http-equiv="expires" content="0"&gt;   

        &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;

        &lt;meta http-equiv="description" content="This is my page"&gt;

        &lt;!--

        &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;

        --&gt;

 

  &lt;/head&gt;

 

  &lt;body&gt;

    &lt;h1&gt;用户信息&lt;/h1&gt;

    &lt;hr&gt;

    &lt;%

      request.setCharacterEncoding("utf-8");

      String username="";

      String password = "";

      Cookie\[] cookies = request.getCookies();

      if(cookies!=null&&cookies.length&gt;0)

      {

           for(Cookie c:cookies)

           {

              if(c.getName().equals("username"))

              {

                   username = URLDecoder.decode(c.getValue(),"utf-8");

              }

              if(c.getName().equals("password"))

              {

                   password = URLDecoder.decode(c.getValue(),"utf-8");

              }

           }

      }

    %&gt;

    &lt;BR&gt;

    &lt;BR&gt;

    &lt;BR&gt;

         用户名：&lt;%=username %&gt;&lt;br&gt;

         密码：&lt;%=password %&gt;&lt;br&gt;

  &lt;/body&gt;

&lt;/html&gt;

 

三 测试

![](http://dl2.iteye.com/upload/attachment/0127/2646/f4b81369-8a43-3f0a-aab9-eeff8852a2ef.png)