jsp是如何实现Cookie的

来源:互联网 发布:淘宝网商贷 编辑:程序博客网 时间:2024/06/07 19:45

以下是jsp实现cookie的一个简单的例子

    Cookie是存储在客户机的文本文件,它们保存了大量轨迹信息。在servlet技术基础上,JSP显然能够提供对HTTP cookie的支持。通常有三个步骤来识别回头客:1. 服务器脚本发送一系列cookie至浏览器。比如名字,年龄,ID号码等等。2. 浏览器在本地机中存储这些信息,以备不时之需。3 . 当下一次浏览器发送任何请求至服务器时,它会同时将这些cookie信息发送给服务器,然后服务器使用这些信息来识别用户或者干些其它事情。

这里以一个记住登陆用户名和密码的例子来测试cookie
控制器的代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>    <%        request.setCharacterEncoding("utf-8");        String uname = request.getParameter("uname");        String password = request.getParameter("pwd");        if(request.getParameter("uname").equals("liu") && request.getParameter("pwd").equals("liu")){            Cookie c1 = new Cookie("uname",uname);            Cookie c2 = new Cookie("password",password);            // 设置cookie的生命周期            c1.setMaxAge(10);            c2.setMaxAge(10);            response.addCookie(c1);            response.addCookie(c2);            request.getRequestDispatcher("index.jsp").forward(request, response);        }else{            response.sendRedirect("login.jsp");            session.setAttribute("uname", request.getParameter("uname"));        }    %></body></html>

登陆页面的代码如等下:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>    <%        if(session.getAttribute("uname") != null){            out.print("登陆失败!");        }    %>    <%        Cookie[] cookies = request.getCookies();        String uname = "";        String password = "";        for(Cookie c : cookies){            if(c.getName().equals("uname")){                uname = c.getValue();            }            if(c.getName().equals("password")){                password = c.getValue();            }        }    %>    <form action="doLogin.jsp" method="post">        <table>            <tr>                <td></td>                <td><h4>请登陆用户名</h4></td>                <td></td>            </tr>            <tr>                <td>用户名:</td>                <td><input type="text" name="uname" value="<%=uname %>"/></td>                <td></td>            </tr>            <tr>                <td>密&nbsp;码:</td>                <td><input type="password" name="pwd" value="<%=password %>"/></td>                <td></td>            </tr>            <tr>                <td></td>                <td><input type="submit" value="登陆"/><input type="reset" value="取消"/></td>                <td></td>            </tr>        </table>    </form></body></html>
原创粉丝点击