Monday, 14 September 2015

Cookies

Cookies


Cookies are small text files that are stored by an application server in the client browser to keep track of all the users.
A cookie has values in the form of name/value pairs.
They are created by the server and are sent to the client with the HTTP response headers.
The client saves the cookies in the local hard disk and sends them along with the HTTP request headers to the server.

A Web browser is expected to support 20 cookies per host and the size of each cookies can be a maximum of 4 bytes each.

Various characteristics of cookies are:
 
1. Cookies can only be read by the application server that had written them in the client browser.
2. Cookies can be used by the server to find out the computer name , IP address or any other details of the client computer by retrieving the remote host address of the client where the cookies are stored.
3. An application server can store cookies in the client machine only when the cookie are enabled in the client browser.

Cookies Description:


The Cookie class of javax.servlet.http package represents a cookie.
The Cookie class provides a constructor that accepts the name and value to create a cookie.
The following code snippet shows the constructor for creating a cookie with name and value.
public Cookie(String cname, String cvalue);
The HttpServletResponse interface provides the addCookie() method to add a cookie to the response object, for sending it to the client.
The following code snippet shows how to add a cookie:
req.addCookie(Cookie cookie);

Retrive the Cookies

The HttpServletRequest provides the getCookies() method that returns an array of cookies that the request object contains.
The following code snippet shows how to retrieve cookies:

Cookie cookie [ ] = req.getCookies();

The Cookie class provides several methods to set and retrieve various properties of a cookie.

The various methods of the Cookie class:1. public String getName()
Returns the name of the cookie.

2. public void setMaxAge(int expiry)
Sets the maximum time for which the client browser retains the cookie value.

3. public int getMaxAge() 
Returns the maximum age of the cookie in seconds.

4. public void setValue(String value)
Sets a new value to the cookie

5. public String getValue()
Returns the value of the cookie

Creating a Simple Program in Servlet using Cookies: In this we receive data from index.jsp and Store it in Cookies after that call it inwelcome.jsp

Steps to create Cookies: 

Step 1 : Create index.jsp with two fields and form action.

1
<%@page contentType="text/html" pageEncoding="UTF-8"%>
2
<!DOCTYPE html>
3
<html>
4
    <head>
5
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6
        <title>JSP Page</title>
7
    </head>
8
    <body>
9
        
10
        <form action="javat">
11
            <pre>
12
                       <h>LOGIN PAGE</h>
13
            USERNAME : <input type="text" name="name">
14
15
            PASSWORD : <input type="password" name="pass">
16
17
            <input type="submit" value="submit">
18
            </pre>
19
       </form>
20
        
21
   </body>
22
</html>
23
24
25
26
27
    


Step 2 : Create a new file web.xml under WebContent/WEB-INF folder and write the code given below:

1
2
3
<?xml version="1.0" encoding="UTF-8"?>
4
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
5
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
6
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
7
    <servlet>
8
        <servlet-name>InterServ</servlet-name>
9
        <servlet-class>com.javat.demo.InterServ</servlet-class>
10
    </servlet>
11
    <servlet>
12
        <servlet-name>Log</servlet-name>
13
        <servlet-class>com.javat.demo.Log</servlet-class>
14
    </servlet>
15
    <servlet-mapping>
16
        <servlet-name>InterServ</servlet-name>
17
        <url-pattern>/javat</url-pattern>
18
    </servlet-mapping>
19
    <servlet-mapping>
20
        <servlet-name>Log</servlet-name>
21
        <url-pattern>/log</url-pattern>
22
    </servlet-mapping>
23
    <session-config>
24
        <session-timeout>
25
            30
26
        </session-timeout>
27
    </session-config>
28
</web-app>
29
30
    


Step 3 : Create a package com.javat.CookiesDemo under Java resources-> src folder and then create the servlet class Login.java. Once you are ready then write the code given below:

1
/*
2
 * To change this template, choose Tools | Templates
3
 * and open the template in the editor.
4
 */
5
package com.javat.demo;
6
7
import java.io.IOException;
8
import java.io.PrintWriter;
9
import javax.servlet.RequestDispatcher;
10
import javax.servlet.ServletException;
11
import javax.servlet.http.HttpServlet;
12
import javax.servlet.http.HttpServletRequest;
13
import javax.servlet.http.HttpServletResponse;
14
15
/**
16
 *
17
 * @author ORANITIN
18
 */
19
public class InterServ extends HttpServlet {
20
21
    /**
22
     * Processes requests for both HTTP
23
     * <code>GET</code> and
24
     * <code>POST</code> methods.
25
     *
26
     * @param request servlet request
27
     * @param response servlet response
28
     * @throws ServletException if a servlet-specific error occurs
29
     * @throws IOException if an I/O error occurs
30
     */
31
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
32
            throws ServletException, IOException {
33
        response.setContentType("text/html;charset=UTF-8");
34
        PrintWriter out = response.getWriter();
35
        
36
        String name=request.getParameter("name");
37
        String pass=request.getParameter("pass");
38
        
39
        if(name.equalsIgnoreCase("admin") && pass.equalsIgnoreCase("123"))
40
        {
41
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
42
            rd.forward(request, response);
43
            //rd.include(request, response);
44
        }
45
        else
46
        {
47
              response.sendRedirect("index.jsp");
48
             //rd.include(request, response);
49
        }
50
        
51
        
52
        
53
        
54
        
55
        try {
56
            /* TODO output your page here. You may use following sample code. */
57
            out.println("<html>");
58
            out.println("<head>");
59
            out.println("<title>Servlet InterServ</title>");            
60
            out.println("</head>");
61
            out.println("<body>");
62
            out.println("<h1>Servlet InterServ at " + request.getContextPath() + "</h1>");
63
            out.println("</body>");
64
            out.println("</html>");
65
        } finally {            
66
            out.close();
67
        }
68
    }
69
70
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
71
    /**
72
     * Handles the HTTP
73
     * <code>GET</code> method.
74
     *
75
     * @param request servlet request
76
     * @param response servlet response
77
     * @throws ServletException if a servlet-specific error occurs
78
     * @throws IOException if an I/O error occurs
79
     */
80
    @Override
81
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
82
            throws ServletException, IOException {
83
        processRequest(request, response);
84
    }
85
86
    /**
87
     * Handles the HTTP
88
     * <code>POST</code> method.
89
     *
90
     * @param request servlet request
91
     * @param response servlet response
92
     * @throws ServletException if a servlet-specific error occurs
93
     * @throws IOException if an I/O error occurs
94
     */
95
    @Override
96
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
97
            throws ServletException, IOException {
98
        processRequest(request, response);
99
    }
100
101
    /**
102
     * Returns a short description of the servlet.
103
     *
104
     * @return a String containing servlet description
105
     */
106
    @Override
107
    public String getServletInfo() {
108
        return "Short description";
109
    }// </editor-fold>
110
}
111
112
113
114
    


Step 4: Create a new file welcome.jsp under Webpages and write the code given below.
Call data that Store we have stored in Session.

1
2
3
<%@page contentType="text/html" pageEncoding="UTF-8"%>
4
<!DOCTYPE html>
5
<html>
6
    <head>
7
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8
        <title>JSP Page</title>
9
        <script>
10
          
11
            </script>
12
    </head>
13
    <body>
14
       
15
      <h>welcome login successfull..........</h>
16
            
17
    </body>
18
</html>
19
20
21
22
    

No comments:

Post a Comment