一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2022-06-29 02:39:58 编辑:袖梨 来源:一聚教程网

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("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("");
    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("");
        out.println("");
        out.println("Cookie info"); 
        out.println("");
        out.println("");
       
        out.println("

Information about the cookie named "mycookie"

");
       
        out.println("Cookie value: "+cookie.getValue()+"
");
        if (newCookie){
        out.println("Cookie Max-Age: "+cookie.getMaxAge()+"
");
        out.println("Cookie Path: "+cookie.getPath()+"
");
        }
       
        out.println("");
        out.println("");
   
        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);
    }
}
 

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


    MyServletName
             MyServlet
       
           
                go
           

           
                weather
           

       

            
   

   
    MyServletName
        /index.html