Java Servlet programming and application Cookie usage

Source: Internet
Author: User

A Cookie is a small piece of data that can be embedded in HTTP requests and responses. It is generated on the server and is returned as part of the response header domain. After the browser receives a response containing the Cookie, it will write the Cookie content into a client text file specially designed to store the Cookie in the form of a "keyword/value" pair. The browser sends the Cookie and subsequent requests to the same server. The server can read the Cookie again and set the Cookie's validity period. Expired cookies are not sent to the server.

Servlet API provides a Cookie class that encapsulates some operations on cookies. Servlet can create a new Cookie, set its attributes such as keyword, value, and validity period, and send the Cookie back to the browser in the HttpServletResponse object. It can also obtain the Cookie from the HttpServletRequest object.

Programming philosophy: Cookie is widely used in actual Servlet programming. The following is an example of getting Cookie information from Servlet.

The source code of ShowCookies. java is as follows:

Import javax. servlet .*;
Import javax. servlet. http .*;
/**
* <P> This is a simple servlet that displays all of
* 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 an 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> // 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
* 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 when the servlet
* Is unloaded.
*/
Public void destroy ()
{
Super. destroy ();
}
}

Note: Cookie is used for two-way communication between the server and the client, so it involves security issues.

Use Java Servlet API for session management

The javax. servlet. http. HttpSession interface encapsulates the details of an HTTP session, which is related to multiple requests of a specific Web client to the Web server over a period of time. Session data management involves session exchange, session relocation, and session persistence. Only data objects that implement the java. io. Serializable interface can be exchanged, relocated, and maintained. This interface allows an object to be serialized. It can write the object state information to any output stream, such as files and network connections.

Programming philosophy: The following is an example of a simple shopping in a mall. When a user buys a commodity (candy, radio, and exercise book), the user puts it into a shopping bag and stores the information of the purchased commodity.

The source code of ShowBuy. java 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", "exercise book "};
// Obtain the session object
HttpSession session = req. getSession (true );
// Obtain the number of selected items
Integer itemCount = (Interger) session. getValue ("itemCount ");
// If the item is not included, 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 ();
// Obtain the form information from POST
String [] itemsSelected;
String itemName;
ItemsSelected = req. getParameterValues ("item ");
// Put the selected item into the session object
If (itemsSelected! = Null ){
For (int I = 0; I <itemsSelected. length; 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 into the session object
}
}
// Write the page header
Out. println ("Out. println ("Out. println ("<title> contents of shopping bags </title> ");
Out. println ("Out. println ("<body> ");
Out. println ("<center> // Write the content of the shopping bag to the page
For (int I = 1; I <itemCount. intValue (); I ++ ){
String item = (String) session. getValue ("Item" + I );
// Retrieve the product name
Out. println (items [Integer. parseInt (item)]);
Out. println ("<BR> ");
}
// Wrap up
Out. println ("</body> ");
Out. println ("Out. close ();
}
}

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

 

<HTML>
<HEAD>
<TITLE> shopping bag instance </TITLE>
</HEAD>
<BODY>
<CENTER> <H1> department store </H1> </CENTER>
<HR>
<Form action = 'servlet/ShowBuy "METHOD =" POST ">
Purchase items
<P> <input type = "Checkbox" NAME = "item" VALUE = "0">
Type 1: Candy </p>
<P> <input type = "Checkbox" NAME = "item" VALUE = "1">
Type 2: Radio </p>
<P> <input type = "Checkbox" NAME = "item" VALUE = "2">
Category 3: exercise books </p>
<HR>
<Input type = "Submit" NAME = "bt_submit" VALUE = "add to shopping bag">
</FORM>
</BODY>
</HTML>

Programming Skills:

In Servlet session management, you must first obtain the session object. The HttpServletRequest. getSession () object returns the current HttpSession object related to the request, and creates a new object when the object does not exist. HttpServletRequest. getSession (true) implements the same function. If the parameter is false, a null value is returned if no session object exists.

// Obtain the session object
HttpSession session = req. getSession (true );
// Obtain the number of selected items
Integer itemCount = (Interger) session. getValue ("itemCount ");

When you select a product, click the "add Shopping Bag" button to output the product selected by the Servlet.

Related Article

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.