JSP之Cookie的实现

时间:2023-03-09 19:29:40
JSP之Cookie的实现

在我们浏览网页的时候,经常会看到自己曾经浏览过的网页的具体的一些信息,那这些究竟是通过什么来实现的呢?难道是有人在监视我们的电脑吗?其实不是的,实现这一功能就是利用了我们接下来看到的cookie技术。cookie本身其实就是保存在我们浏览器客户端的一个txt 文件,每次我们打开相应的额浏览网页就会自动的调用这个问价,然后查看练得具体的内容,然后你就可以看到自己的浏览记录了。

相对比而言,有客户端的信息保存,当然也会有服务器端的信息保存了,但是二者实现的原理不同,而且其功能也不相同。下面让我们先对比一些二者的不同之处:

Session是保存在服务器端的的用户信息内容,保存的信息的类型是Object类型,也就是java中最为常见的类。热切这些信息会随着会话(也就是客户端与服务器之间的交互)的结束就会销毁,虽然它保存的是比较重要的信息。

而Cookie则是在客户端保存信息,保存的信息的数据类型是String类型,最重要的是Cookie可以长期的保存在客户端中,其实你也可以自己手动设置Cookie的生存周期,以及是否要在客户端写进Cookie,当然咯,使用Cookie保存信息终究是不安全的,所以一般只用它来保存一些不重要的信息。

那么闲话不多说,让我们开始用代码说话吧。

首先我们需要一个浏览器页面,我们用jsp来实现。原理就是制作一个表单,显示我们要填写的信息,然后又增加了一个判断是否勾选了checkbox,以减去手动输入用户名及密码的步骤,过程中有可能出现中文乱码的情况,所以我们加上了java.net.*包下的解码函数URLDecoder.encode(String,"字符编码集")代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<%@ page import="java.net.*"%>

<!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>Login Jsp PaFfge</title>

</head>

<body>

    <br>

    <%

        request.setCharacterEncoding("utf-8");

        String username = "";

        String password = "";

        Cookie[] cookies = request.getCookies();

        if (cookies != null && cookies.length > 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");

                }

            }

        }

    %>

    <br>

    <form name="loginForm" action="dologin.jsp" method="post">

        <table>

            <tr>

                <td>用户名:</td>

                <td><input type="text" name="username" value="<%=username%>" /></td>

            </tr>

            <tr>

                <td>密码:</td>

                <td><input type="password" name="password"

                    value="<%=password%>" /></td>

            </tr>

            <tr>

                <td colspan="2"><input type="checkbox" name="isUseCookie"

                    checked="checked" />十天内记住我的登录状态</td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" value="登录" /><input

                    type="reset" value="取消" /></td>

            </tr>

        </table>

    </form>

</body>

</html>

做好了登陆界面,那么我们当然需要一个处理登陆界面的逻辑了,于是dologin.jsp就派上了用场,其主要的功能就是生成Cookie和删去Cookie,分别对应变淡中是否勾选了checkbox的两种情况代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

    <%@ page import="java.net.*" %>

<!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>DoLogin jsp Page</title>

</head>

<body>

    <h1>登录成功</h1>

    <hr>

    <br>

    <br>

    <br>

    <%

       request.setCharacterEncoding("utf-8");

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

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

       if(isUseCookies!=null&&isUseCookies.length>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>0)

          {

             for(Cookie c:cookies)

             {

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

                {

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

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

                }

             }

          }

       }

    %>

    <a href="users.jsp" target="_blank">查看用户信息</a>

</body>

</html>

从上面我们看到了一个超链接,指向的就是我么用Cookie记录的用户的信息,需要注意的是,我们创建Cookie的时候用的编码集一定要和解码时的一致,否则只能得到乱码,那么代码如下:

<%@page import="java.net.URLDecoder"%>

<%@ 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>Users JSP Page</title>

</head>

<body>

    <h1>User Info</h1>

    <%

        request.setCharacterEncoding("utf-8");

        String username = "";

        String password = "";

        Cookie[] cookies = request.getCookies();

        if (cookies != null && cookies.length > 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");

                }

            }

        }

    %>

    <br>

    <br> UserName:<%=username%>

    Password:<%=password%>

</body>

</html>

好了,以上就是我们的代码的全部内容了,接下来让我们看一下具体的展示界面吧: