Java Servlet Programming and application of cookies using the method

Source: Internet
Author: User
Tags http request integer

A Cookie is a small piece of data that can be embedded in an HTTP request and response and is generated on the server and returned to the user as part of the response header domain. When the browser receives a response that contains a cookie, it writes the contents of the cookie as a "keyword/value" pair to a client-specific text file that stores cookies. The browser sends the cookie and subsequent requests to the same server, and the server can read the cookie again in a valid period setting, and the expired cookie is not sent to the server.

The Servlet API provides a cookie class that encapsulates some of the operations on cookies. The Servlet can create a new cookie, set its keywords, values, and expiration attributes, and then send the cookie settings back to the browser in the HttpServletResponse object, as well as from the HttpServletRequest object to get the cookie.

Programming idea: Cookies are widely used in real-world servlet programming, and here's an example of getting cookie information from a servlet.

Showcookies.java's source code is as follows:

import javax.servlet.*;


import javax.servlet.http.*;


/**


* <p> This is a simple servlet-displays all of the


* Cookies present in the request


*/


public class Showcookies extends HttpServlet


{


public void Doget (HttpServletRequest req, HttpServletResponse resp)


throws Servletexception, Java.io.IOException


{


//Set The content type of the response


Resp.setcontenttype ("text/html;charset=gb2312");


//Get the PrintWriter to write the response


Java.io.PrintWriter out = Resp.getwriter ();


//Get a array containing all of the cookies


Cookie cookies[] = req.getcookies ();


//Write the page header


out.println ("

out.println ("

out.println ("<title> Servlet Cookie Information </title>");


out.println ("

out.println ("<body>");


if ((cookies = null) | | (cookies.length = 0)) {


out.println ("No cookies");


}


else {


out.println ("<center> cookie information in response message");


//Display a table with all of the info


out.println ("<table border>");


Out.println ("<tr> <th> Name </th> <th> Value </th>" + "<th> Comment </th> <th> Max age </th> </tr>");


for (int i = 0; I cookies.length i++) {


Cookie C = cookies[i];


out.println ("<tr> <td>" + c.getname () + "</td> <td>" +


C.getvalue () + "</td> <td>" + c.getcomment () + "</td> <td>" + c.getmaxage () + "</td> </tr>");


}


out.println ("</table> </center>");


}


//Wrap up


out.println ("</body>");


out.println ("

Out.flush ();


}


/**


* <p> Initialize the servlet. This is called once when the


* servlet is loaded. It is guaranteed to complete before any


* Requests are made to the servlet


* @param cfg Servlet configuration information


*/


public void init (servletconfig cfg)


throws Servletexception


{


Super.init (CFG);


}


/**


* <p> Destroy the servlet. This is called once the servlet


* is unloaded.


*/


public void Destroy ()


{


Super.destroy ();


}


}


Note: Cookies are two-way communication between the server side and the client, so it involves security issues.

Session management Using the Java Servlet API

The Javax.servlet.http.HttpSession interface encapsulates the details of an HTTP session that is related to multiple requests for a Web server by a specific Web customer over a period of time. The management session data mainly involves 3 aspects: Session Exchange, session relocation and conversation persistence, only the data object that implements the Java.io.Serializable interface can be exchanged, relocated and maintained. This interface is primarily to enable the object to have the ability to serialize, it can write the state information of the object to any output stream such as: file, network connection and so on.

Programming Ideas: The following is a simple example of shopping in the mall, when users buy goods (candy, radio and exercise books) into the shopping bag, save the purchase of merchandise information.

Showbuy.java's source code is as follows:

Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;
public class Showbuy extends HttpServlet
{
public void doget (HttpServletRequest req, httpservletresponse Res)
throws Servletexception, Java.io.IOException
{
string[] item={"Candy", "Radio", "Workbook"};
//Get Session Object
HttpSession session=req.getsession (TRUE);
//Get the number of items selected
Integer itemcount= (interger) session.getvalue ("ItemCount");
//If no merchandise is placed, the number is 0
if (itemCount ==null) {
Itemcount=new Integer (0);
}
//Set The content type of the response
Res.setcontenttype ("text/html;charset=gb2312");
PrintWriter Out=res.getwriter ();
//Get the form information on Post
string[] itemsselected
String ItemName;
Itemsselected=req.getparametervalues ("item");
//Put the selected item in the Session object
if (itemsselected!=null) {
for (int i=0;i Itemname= Itemsselected[i];
Itemcount=new Integer (Itemcount.intvalue () +1);
Session.putvalue ("Item" + Itemcount,itemname);
//define the product name as Itemx
Session.putvalue ("ItemCount", ItemCount),
///Put the number of items in Session object
}

//Write the page Header
Out.println ("");
Out.println ("");
Out.println (" Shopping bag contents ");
Out.println ("");
Out.println ("");
Out.println ("

the product you put in the shopping bag is: ");
//write the contents of the shopping bag to the page
for (int i = 1; i itemcount.intvalue (); i++) {
String item = (String) session.getvalue ("item" + i);
//Remove Product name
Out.println (Items[integer.parseint (item));
Out.println ("
");
}
//Wrap up
Out.println ("");
Out.println ("");
Out.close ();
}
}

The source code for the client's showbuy.html is as follows:

<HTML>


<HEAD>


<TITLE> instances of shopping bags </TITLE>


</HEAD>


<BODY>


<CENTER> Department Store </CENTER>


<HR>


<form action= ' servlet/showbuy ' method= "POST" >


Purchase Goods


<p> <input type= "Checkbox" name= "item" value= "0" >


First: Candy </p>


<p> <input type= "Checkbox" name= "Item" value= "1" >


the second type: Radio </p>


<p> <input type= "Checkbox" name= "Item" value= "2" >


The third: exercise-books </p>


<HR>


<input type= "Submit" name= "Bt_submit" value= "Add shopping bag" >


</FORM>


</BODY>


</HTML>

Instructions for programming Tips:

When you are in a servlet for session management, you first get the session object. The Httpservletrequest.getsession () object returns the current HttpSession object associated with the request and creates a new object when the object does not exist; Httpservletrequest.getsession (true ) to achieve the same functionality. If the argument is false, a null value is returned when no Session object exists.

//Get Session Object


HttpSession Session=req.getsession (true);


//Get the number of items selected


Integer itemcount= (interger) session.getvalue ("ItemCount");

When the user selects the item, click the "Add Shopping Bag" button and the Servlet outputs the product selected by the user.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.