三个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. attr与prop html与text

  2. C# 入门经典

    C#简介 使用.NETFrmework的含义 使用.NETFrmework的一个重要原因是他可以作为集成各种操作系统的方式 包含了一个非常大的代码库 除了提供这个库以外.NETFrmework还包含. ...

  3. centos安装包选择--liveCD、liveDVD、bin-DVD、netinstall和minimal

    在Centos官方选择下载centos的时候有好几个文件可供下载,包括liveCD.liveDVD和bin-DVD等等.这些文件都有什么区别,我们应该选择哪个文件下载呢? liveDVD版本:它就是一 ...

  4. [学习笔记] 模拟退火 (Simulated Annealing)

    真没想到这东西真的在考场上用到了...顺便水篇blog以示诈尸好了(逃 模拟退火算法 模拟退火是一种随机化算法, 用于求函数的极值qwq 比如给出一个问题, 我们要求最优解的值, 但是可能的方案数量极 ...

  5. java中的异常类型以及区别????

    一.引言 根据JDK的文档我们能够找到异常所在的包:java.lang.Throwable中,Throwable是所有异常类的根类,error是错误,在java.lang.error中,而Except ...

  6. alpha冲刺第三天

    一.合照 二.项目燃尽图 三.项目进展 今天是一个瓶颈期,在昨天被困住的地方今天还是没能解决,所以今天的项目进展并没有发生什么变化. 今天晚上xl和lj去实验室找学姐了,在学姐的帮助下大概有了一点思路 ...

  7. MySQL的小Tips

    交集和差集 MySQL中没有这两个运算,但是有并集运算,所以可以利用这个来间接实现. 差集: SELECT ID FROM ( SELECT DISTINCT A.AID AS ID FROM TAB ...

  8. 源端控制的OpenFlow数据面

    OpenFlow 交换机一般采用 TCAM 存储和查找流表,从而带来了扩展性.成本和能耗的问题.TCAM 成本和能耗过高,存储容量有限,一般交换机中的 TCAM 仅能存储几千条流表项,对 OpenFl ...

  9. 从PRISM开始学WPF(五)MVVM(一)ViewModel?

    从PRISM开始学WPF(一)WPF? 从PRISM开始学WPF(二)Prism? 从PRISM开始学WPF(三)Prism-Region? 从PRISM开始学WPF(四)Prism-Module? ...

  10. Python之旅.第三章.函数3.29

    一.无参装饰器 1 开放封闭原则 软件一旦上线后,就应该遵循开放封闭原则,即对修改源代码是封闭的,对功能的扩展是开放的 也就是说我们必须找到一种解决方案: 能够在不修改一个功能源代码以及调用方式的前提 ...