Servlet cookie 赋值与取值及页面之前传值处理方法

Servlet cookie 赋值与取值及页面之前传值处理方法,下面先是讲一下关于如何获取与给cookies设置值,然后再利用一个实例详细值了servlet cookie实例操作。

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

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

public class AddCookieServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String data = request.getParameter("data");
    Cookie cookie = new Cookie("MyCookie", data);
    response.addCookie(cookie);
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<B>MyCookie has been set to");
    pw.println(data);
    pw.close();
  }
}

cookie 获取

 

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

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

public class GetCookiesServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Cookie[] cookies = request.getCookies();

    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<B>");
    for (int i = 0; i < cookies.length; i++) {
      String name = cookies[i].getName();
      String value = cookies[i].getValue();
      pw.println("name = " + name + "; value = " + value);
    }
    pw.close();
  }
}

根据上面的实例我们来看看servlet cookie的页面之间传递

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class MyServlet extends HttpServlet {
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
   
    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;
   
    //Get the 'mycookie' Cookie if it exists
    if (cookies != null){
        for (int i = 0; i < cookies.length; i++){
            if (cookies[i].getName().equals("mycookie")){
              cookie = cookies[i];
             }
        }//end for
    }//end if
      
    if (cookie == null){
       newCookie=true;
      //Get the cookie's Max-Age from a context-param element
      //If the 'cookie-age' param is not set properly
      //then set the cookie to a default of -1, 'never expires'
      int maxAge;
      try{
           maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
           } catch (Exception e) {
            maxAge = -1;
           }
     
       //Create the Cookie object
    
        cookie = new Cookie("mycookie",""+getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
       
        }//end if
        // get some info about the cookie
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
   
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Cookie info</title>"); 
        out.println("</head>");
        out.println("<body>");
       
        out.println("<h2> Information about the cookie named "mycookie"</h2>");
       
        out.println("Cookie value: "+cookie.getValue()+"<br>");
        if (newCookie){
        out.println("Cookie Max-Age: "+cookie.getMaxAge()+"<br>");
        out.println("Cookie Path: "+cookie.getPath()+"<br>");
        }
       
        out.println("</body>");
        out.println("</html>");
   
        out.close();
    }
    private long getNextCookieValue(){
   
    /*This produces a cookie value to show how to create Cookie objects. If
      this method was heavily used in a production environment it may
      produce too many objects; synchronization of a single Date object
      might be better, based on performance testing. At any rate a
      production environment would produce a unique cookie value in a
      different manner such as from a unique database ID. */

    //returns the number of milleseconds since Jan 1, 1970
    return new java.util.Date().getTime();
   
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
       
        doGet(request,response);
    }
}
 
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>
        <init-param>
            <param-name>
                go
            </param-name>
            <param-value>
                weather
            </param-value>
        </init-param>
            
    </servlet>
   
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
 

 

时间: 2024-07-29 18:15:17

Servlet cookie 赋值与取值及页面之前传值处理方法的相关文章

数据库组件 Hxj.Data (三十)(Asp.Net 页面自动赋值与取值)

在项目中的页面中经常会遇到界面的赋值与取值,特别是页面中项特别多的时候,取值和赋值往往是 体力活. 在组件中添加了一个简单的辅助,取值通过Request.From[""]来实现,赋值则 document.getElementById("").value来实现. 下面我们来看示例代码: 例子是:Northwind数据库的Products表 页面代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi

asp cookie 创建,取值,删除 教程

asp教程 cookie 创建,取值,删除 教程 功能:cookie 常用来对用户进行识别. 原理:  cookie 是一种服务器留在用户电脑中的小文件.每当同一台电脑通过浏览器请求页面时,这台电脑就会发送 cookie;   asp 如果创建cookie  Response.Cookies("aa")'就这一句就己经创建了cookie了.  Response.Cookies("cookies")="111cn.net"  Response.Co

实用ExtJS教程100例-011:ExtJS Form 使用JSON数据赋值和取值

上一节中我们演示了ExtJS Form的异步加载和提交数据,本节中我们将演示如何使用JSON数据为ExtJS Form中的字段赋值和取值. 系列ExtJS教程持续更新中,点击查看>>最新ExtJS教程目录 使用JSON数据为字段赋值 var formCmp = this.up("form"); var form = formCmp.getForm(); var userValues = { UserName: "Qi Fei", Email: "

js实现hashtable的赋值、取值、遍历的教程

本文实例讲述了js实现hashtable的赋值.取值.遍历操作.分享给大家供大家参考,具体如下: 哈希表(Hashtable)这个概率应该是#c里面的概念,用来赋值.取值.遍历.排序操作提高效率.想起这个东西其实使我们以前经常遇到这样的面试题,一个很大的数组可能有100000个,如何快速知道它里面的出现最多的次数,那么这里我们可能就要用Hashtable的相关知识了.Javascript中,object的实现就是hash表,因此只要在object上封装点方法,再利用原生的hasOwnProper

一起谈.NET技术,晚绑定场景下对象属性赋值和取值可以不需要PropertyInfo

在<一句代码实现批量数据绑定>中,我通过界面控件ID与作为数据源的实体属性名之间的映射实现了批量数据绑定.由于里面频繁涉及对属性的反射--通过反射从实体对象中获取某个属性值:通过反射为控件的某个属性赋值,所以这不是一种高效的操作方式.为了提升性能,我通过IL Emit的方式创建了一个PropertyAccessor组件,以实现高效的属性操作.如果你看了我在文中给出的三种属性操作性能的测试结果,相信会对PropertyAccessor的作用有深刻的印象.[源代码从这里下载] 目录: 一.Prop

晚绑定场景下对象属性赋值和取值可以不需要Pro“.NET技术”pertyInfo

在<一句代码实现批量数据绑定>中,我通过界面控件ID与作为数据源的实体属性名之间的映射实现了批量数据绑定.由于里面频繁涉及对属性的反射--通过反射从实体对象中获取某个属性值:通过反射为控件的某个属性赋值,所以这不是一种高效的操作方式.为了提升性能,我通过IL Emit的方式创建了一个PropertyAccessor组件,以实现高效的属性操作.如果你看了我在文中给出的三种属性操作性能的测试结果,相信会对PropertyAccessor的作用有深刻的印象.[源代码从这里下载] 目录: 一.Prop

JavaScript实现在页面间传值的方法_javascript技巧

本文实例讲述了JavaScript实现在页面间传值的方法.分享给大家供大家参考.具体如下: 问题如下: 在 a.html 页面中,<form> 的 onsubmit 事件调用一个方法 foo( ),打开 b.html 页面的同时给 b.html 传递参数.方法 foo( ) 中需要传递变量参数到 b.html 页面,在 b.html 页面接受参数值,但不能使用服务器端技术. 解决代码如下: a.html页面如下: <html> <head> <title>

CYQ.Data 快速开发之UI(赋值、取值、绑定)原理

昨夜园子猴子问了几个我CYQ.Data使用的小问题,经过简单解答后,他表示"妈妈再也不用担心我的学习",并于事后以资鼓励,希望这框架越走越好. 除了技术上的交流,双方在生活,S上面的问题上也进行了双边友好交流,最后猴子给发了一个国外的Sex网站,对此分享行为,我表示高度赞赏.   好了,言归正题,讲点技术问题: CYQ.Data 的使用操作方式,已经有相关文章介绍了,就不再介绍了. 本节就讲一下实现原理,具体源码,可直接下载开源的V4.0可以学习. 下载地址:http://www.cy

jQuery给div,Span, a ,button, radio 赋值与取值_jquery

jquery给div的innerHTML赋值 $("#id").html()="test"; //或者 $("#id").html("test"); jquery 获取<a>的链接内容 $().innerHTML jquery 给span 赋值 $('#hiddenNote').text('getSpanValues'); span取值 $('#hiddenNote').text(); jquery 给标签butt