首页 > 代码库 > Servlet中的cookie和session

Servlet中的cookie和session

保存数据的2中方式

  • Cookie
  • Session

Cookie

我们可以将一些信息保存到cookie中,cookie存放在对应的浏览器目录里面。每个站点可以保存20个cookie,最大长度不超过4k。同时,由于http协议是明文传输,所以使用cookie的时候存在一些安全性问题。

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

       {

              try

              {

                     Cookie[] cookies = req.getCookies();

                     boolean usernameFound = false;

                     if(null != cookies)

                     {

                           System.out.println("cookie found");

                           for(Cookie item : cookies)

                           {

                                  System.out.println(item.getName());

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

                                  {

                                         usernameFound = true;

                                         System.out.println("username = " + item.getValue());

                                         break;

                                  }

                           }

                     }

                     if(!usernameFound)

                     {

                           System.out.println("没有任何cookie");

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

                           resp.addCookie(username);

                     }

              }

              catch(Exception exception)

              {

                     System.out.println("异常:" + Tools.getCurrentTime());

                     System.out.println(exception);

              }

             

       }

 

 

Session

Session通过cookie保存,每个session有一个唯一的ID(通过getId()获取)。默认情况下session过期时间为30分钟,可以通过代码或者配置的方式设置session失效时期,代码优先于配置文件。

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

{

     HttpSession session = req.getSession();

     if(null != session)

     {

           System.out.println("session 未过期");

     }

     else

     {

           System.out.println("session 过期");

     }

     //设置session失效时间为2分钟

     session.setMaxInactiveInterval(60 * 2);

     session.setAttribute("count", 999);

     session.invalidate();

}

 

也可以通过通过部署描述服务配置失效时间web.xml

<session-config>

                <session-timeout>30</session-timeout>

</session-config>

 

Servlet中的cookie和session