三个servlet的实现:

package app02c;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookies的实现(设置cookie)
 */
@WebServlet( name = "PreferenceServlet", urlPatterns = "/preference")
public class PreferenceServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 主菜单
    public static final String MENU =
            "<div style='background:#e8e8e8;"
            + "padding:15px'>"
            + "<a href='cookieClass'>Cookie Class</a>&nbsp;&nbsp;"
            + "<a href='cookieInfo'>Cookie Info</a>&nbsp;&nbsp;"
            + "<a href='preference'>Preference</a>" + "</div>";   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PreferenceServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * 主页的选择
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            writer.print("<html><head>" + "<title>Preference</title>"
                    + "<style>table {" + "font-size:small;"
                    + "background:NavajoWhite }</style>"
                    + "</head><body>"
                    + MENU
                    + "Please select the values below:"
                    + "<form method='post'>"
                    + "<table>"
                    + "<tr><td>Title Font Size: </td>"
                    + "<td><select name='titleFontSize'>"
                    + "<option>large</option>"
                    + "<option>x-large</option>"
                    + "<option>xx-large</option>"
                    + "</select></td>"
                    + "</tr>"
                    + "<tr><td>Title Style & Weight: </td>"
                    +"<td><select name='titleStyleAndWeight' multiple>"
                    + "<option>italic</option>"
                    + "<option>bold</option>"
                    + "</select></td>"
                    + "</tr>"
                    + "<tr><td>Max. Records in Table: </td>"
                    + "<td><select name='maxRecords'>"
                    + "<option>5</option>"
                    + "<option>10</option>"
                    + "</select></td>"
                    + "</tr>"
                    + "<tr><td rowspan='2'>"
                    + "<input type='submit' value='Set'/></td>"
                    + "</tr>"
                    + "</table>" + "</form>" + "</body></html>");
    }

    /**
     * 设置cookie
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String maxRecords = request.getParameter("maxRecords");
        // 下拉列表multiple属性的获取方式
        String[] titleStyleAndWeight = request
                .getParameterValues("titleStyleAndWeight");
        String titleFontSize =
                request.getParameter("titleFontSize");
        // 设置cookie
        response.addCookie(new Cookie("maxRecords", maxRecords));
        response.addCookie(new Cookie("titleFontSize",
                titleFontSize));

        // delete titleFontWeight and titleFontStyle cookies first
        // Delete cookie by adding a cookie with the maxAge = 0;
        
        Cookie cookie = new Cookie("titleFontWeight", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        cookie = new Cookie("titleFontStyle", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        if (titleStyleAndWeight != null) {
            for (String style : titleStyleAndWeight) {
                if (style.equals("bold")) {
                    // 添加cookie
                    response.addCookie(new
                            Cookie("titleFontWeight", "bold"));
                } else if (style.equals("italic")) {
                    response.addCookie(new Cookie("titleFontStyle",
                            "italic"));
                }
            }
        }

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><head>" + "<title>Preference</title>"
                + "</head><body>" + MENU
                + "Your preference has been set."
                + "<br/><br/>Max. Records in Table: " + maxRecords
                + "<br/>Title Font Size: " + titleFontSize
                + "<br/>Title Font Style & Weight: ");

        // titleStyleAndWeight will be null if none of the options
        // was selected
        if (titleStyleAndWeight != null) {
            writer.println("<ul>");
            for (String style : titleStyleAndWeight) {
                writer.print("<li>" + style + "</li>");
            }
            writer.println("</ul>");
        }
        writer.println("</body></html>");
    }

}

package app02c;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 显示数据,根据接受的cookie来选择输出数量
 */
@WebServlet( name = "CookieClassServlet", urlPatterns = "/cookieClass")
public class CookieClassServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    // 设置显示的数据
    private String[] methods = {
            "clone", "getComment", "getDomain",
            "getMaxAge", "getName", "getPath",
            "getSecure", "getValue", "getVersion",
            "isHttpOnly", "setComment", "setDomain",
            "setHttpOnly", "setMaxAge", "setPath",
            "setSecure", "setValue", "setVersion"
    };
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieClassServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取cookie
        Cookie[] cookies = request.getCookies();
        Cookie maxRecordsCookie = null;
        if (cookies != null) {
            // 遍历cookie
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("maxRecords")) {
                    maxRecordsCookie = cookie;
                    break;
                }
            }
        }
        
        int maxRecords = 5; // default
        if (maxRecordsCookie != null) {
            try {
                maxRecords = Integer.parseInt(
                        maxRecordsCookie.getValue());
            } catch (NumberFormatException e) {
                // do nothing, use maxRecords default value
            }
        }
        
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.print("<html><head>" + "<title>Cookie Class</title>"
                + "</head><body>"
                + PreferenceServlet.MENU
                + "<div>Here are some of the methods in " +
                        "javax.servlet.http.Cookie");
        writer.print("<ul>");
        
        for (int i = 0; i < maxRecords; i++) {
            writer.print("<li>" + methods[i] + "</li>");
        }
        writer.print("</ul>");
        writer.print("</div></body></html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

package app02c;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据接受到cookie来显示详细信息
 */
@WebServlet(name = "CookieInfoServlet", urlPatterns = "/cookieInfo")
public class CookieInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        StringBuilder styles = new StringBuilder();
        // 设置修饰
        styles.append(".title {");
        if (cookies != null) {
            // 根据设置的cookie显示
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                if (name.equals("titleFontSize")) {
                    styles.append("font-size:" + value + ";");
                } else if (name.equals("titleFontWeight")) {
                    styles.append("font-weight:" + value + ";");
                } else if (name.equals("titleFontStyle")) {
                    styles.append("font-style:" + value + ";");
                }
            }
        }
        styles.append("}");
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.print("<html><head>" + "<title>Cookie Info</title>"
                + "<style>" + styles.toString() + "</style>"
                + "</head><body>" + PreferenceServlet.MENU
                + "<div class='title'>"
                + "Session Management with Cookies:</div>");
        writer.print("<div>");

        // cookies will be null if there's no cookie
        if (cookies == null) {
            writer.print("No cookie in this HTTP response.");
        } else {
            writer.println("<br/>Cookies in this HTTP response:");
            // 显示cookie
            for (Cookie cookie : cookies) {
                writer.println("<br/>" + cookie.getName() + ":"
                        + cookie.getValue());
            }
        }
        writer.print("</div>");
        writer.print("</body></html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

servlet之cookie实现的更多相关文章

  1. Servlet/JSP-05 Cookie

    一. 问题? HTTP协议是一种无状态协议,服务器本身无法识别出哪些请求是同一个浏览器发出的,浏览器的每一次请求都是独立的.现实业务中服务器有时候需要识别来自同一个浏览器的一系列请求,例如购物车,登录 ...

  2. Servlet 利用Cookie实现一周内不重复登录

    import java.io.IOException;import java.io.PrintWriter; import javax.servlet.ServletException;import ...

  3. JavaWeb学习记录总结(二十九)--Servlet\Session\Cookie\Filter实现自动登录和记住密码

    一.Servlet package autologin.servlet.login; import java.io.IOException;import java.security.MessageDi ...

  4. 动手学servlet(四) cookie和session

    Cookie   cookie是保存在客户端的一个“键值对”,用来存储用户的一些信息 cookie的应用: -在电子商务会话中标识用户 -对网站进行定制,比如你经常浏览哪些内容,就展示哪些页面给你 - ...

  5. Servlet & JSP - Cookie

    关于 Cookie 的内容,参考 HTTP - Cookie 机制 获取来自客户端的 cookie request.getCookies 方法可以获取来自 HTTP 请求的 cookie,返回的是 j ...

  6. Servlet 笔记-Cookie 处理

    Cookie 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息. 识别返回用户包括三个步骤: 服务器脚本向浏览器发送一组 Cookie.例如:姓名.年龄或识别号码等. 浏览器将这些信息存储在本地 ...

  7. Type mismatch: cannot convert from javax.servlet.http.Cookie[] to org.apache.tomcat.util.http.parser.Cookie[] 的一种可能

    今天用到Cookie时,写了一个Cookie数组,发现报错“Type mismatch: cannot convert from javax.servlet.http.Cookie[] to org. ...

  8. java用servlet、cookie实现一个阅读记录

    效果如图 代码1 package com.xiaostudy.servlet; import java.io.IOException; import java.io.PrintWriter; impo ...

  9. servlet(5) - Cookie和session - 小易Java笔记

    1.会话概述 (1)会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. (2)会话过程中的数据不宜保存在request和servle ...

随机推荐

  1. 循环while do---while for循环

    一.循环结构 (.^▽^) 1.循环不是无休止进行的,满足一定条件的时候循环才会继续,称为"循环条件",循环条件不满足的时候,循环退出 2.循环结构是反复进行相同的或类似的一系列操 ...

  2. python全栈学习--day4

    列表 说明:列表是python中的基础数据类型之一,它是以[]括起来,每个元素以逗号隔开,而且他里面可以存放各种数据类型比如:   1 li = ['alex',123,Ture,(1,2,3,'wu ...

  3. 用 Go 编写一个简单的 WebSocket 推送服务

    用 Go 编写一个简单的 WebSocket 推送服务 本文中代码可以在 github.com/alfred-zhong/wserver 获取. 背景 最近拿到需求要在网页上展示报警信息.以往报警信息 ...

  4. %f使用时的注意事项

    1不是所有定义都用int,使用浮点函数需要把int改成float才能正常工作 2保留一位小数时要打入%0.1f,保留两位小数时要打入%0.2f,而不是%0.01f

  5. Bate测试报告

    1 测试中找出的bug Bug类型 总数 描述 修复的bug 10 1.注册成功并没有直接跳转到登录页面: 2.学校地区无限制,数字也可以: 3.虽然相同用户名不能注册,但是只是显示,注册失败,却没有 ...

  6. python 之反射

    通过字符串的形式导入模块 通过字符串的形式,去模块中寻找制定的函数,并执行getattr(模块名,函数名,默认值) 通过字符串的形式,去模块中设置东西setattr(模块名,函数名/变量名,lambd ...

  7. SQL的介绍及MySQL的安装

    基础篇 - SQL 介绍及 MySQL 安装               SQL的介绍及MySQL的安装 课程介绍 本课程为实验楼提供的 MySQL 实验教程,所有的步骤都在实验楼在线实验环境中完成, ...

  8. 【iOS】OC-AFNetworking 2.0 跟踪文件上传进度

    我是较新的 AFNetworking 2.0.使用下面的代码片段,我已经能够成功地将一张照片上传到我的 url.我想要跟踪的增量上载进度,但我找不到这样做 2.0 版的示例.我的应用程序是 iOS 7 ...

  9. android 时间获取以及时间格式化

    Android中获取系统时间有多种方法,可分为Java中Calendar类获取,java.util.date类实现,还有android中Time实现 现总结如下: 方法一: void getTime1 ...

  10. SUN平台服务器光纤共享存储互斥失败如何恢复数据?

    服务器数据恢复故障描述: 服务器最初的设计思路为将两台SPARC SOLARIS系统通过光纤交换机共享同一存储作为CLUSTER使用,正常情况下A服务器工作,当A服务器发生故障宕机后即可将其关机然后开 ...