JSP Cookie状态管理

 

JSP中创建与使用Cookie

  创建Cookie对象

    Cookie newCookie = new Cookie(String key, Object value);

  写入Cookie对象

    response.addCookie(newCookie);

  读取Cookie对象

    Cookie[] cookies = request.getCookies();

  常用方法

    void setMaxAge(int expiry)  设置cookie有效期,单位-秒

    void setValues(String value)    对cookie进行赋值

    String getName()       获取cookie的名称

    String getValue()       获取cookie的值

    int getMaxAge()        获取cookie有效时间,单位-秒

 

通过Cookie实现登录状态记录,示例代码:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.net.HttpCookie" %>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
    <head>
        <!-- Page title -->
        <title>imooc - Login</title>
        <!-- End of Page title -->
        <!-- Libraries -->
        <link type="text/css" href="css/login.css" rel="stylesheet" />    
        <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />    
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="js/easyTooltip.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
        <!-- End of Libraries -->    
    </head>
    <body>
    <%
        String username = "";
        String password = "";
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie c:cookies){
                if(c.getName().equals("username")){
                    username = c.getValue();
                }
                if(c.getName().equals("password")){
                    password = c.getValue();
                }
            }
        }
    %>
    <div id="container">
        <div class="logo">
            <a href="#"><img src="assets/logo.png" alt="" /></a>
        </div>
        <div id="box">
            <form action="do_login.jsp" method="post">
            <p class="main">
                <label>用户名: </label>
                <input name="username" value="<%=username%>" />
                <label>密码: </label>
                <input type="password" name="password" value="<%=password%>">

            </p>

            <p class="space">
                <label>7天免登陆</label>
                <input type="checkbox" name="isUseCookie" checked="checked">
                <input type="submit" value="登录" class="login" style="cursor: pointer;"/>
            </p>
            </form>
        </div>
    </div>
    </body>
</html>
HTML-Login.jsp

相关文章:

  • 2021-06-28
  • 2021-05-26
  • 2021-08-10
  • 2021-07-15
  • 2021-08-05
  • 2021-10-18
猜你喜欢
  • 2021-04-17
  • 2021-11-23
  • 2021-08-10
  • 2022-12-23
  • 2022-01-11
  • 2021-12-19
  • 2021-11-21
相关资源
相似解决方案