Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Department of Applied Computational Science and Engineering

Course Code: KCS-602


Course Name: Web Technology
Faculty Name: Anuj Gupta
Email: anuj.gupta_acse@glbitm.ac.in
Course Outcome

KCS 602 WEB TECHNOLOGY


Course Outcome ( CO) Bloom’s Knowledge Level (KL)
At the end of course , the student will be able to
CO 1 Explain web development Strategies and Protocols governing Web. K1, K2

CO 2 Develop Java programs for window/web-based applications. K2, K3


CO 3 Design web pages using HTML, XML, CSS and JavaScript. K2, K3

CO 4 Creation of client-server environment using socket programming K1, K2,

CO 5 Building enterprise level applications and manipulate web databases using JDBC K3, K4
CO6 Design interactive web applications using Servlets and JSP K2, K3

Subject:Web
Subject: Web Technology
Technology
Syllabus

Unit-5
Servlets: Servlet Overview and Architecture, Interface Servlet and the
Servlet Life Cycle, Handling HTTP get Requests, Handling HTTP post
Requests, Redirecting Requests to Other Resources, Session Tracking,
Cookies, Session Tracking with Http Session

Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First
Java Server Page Example, Implicit Objects, Scripting, Standard Actions,
Directives, Custom Tag Libraries.

Subject:Web
Subject: Web Technology
Technology
Static Web Page Processing

Subject: Web Technology


Dynamic Web Page Processing

Subject: Web Technology


Servlet

Subject: Web Technology


Limitations of CGI

Subject: Web Technology


How Servlet is better than CGI

Subject: Web Technology


Advantages of Servlet

Subject: Web Technology


Servlet

Subject: Web Technology


How Servlet Works

Subject: Web Technology


Servlets Architecture

Subject: Web Technology


Servlets Tasks

Subject: Web Technology


HelloServlet.java
import javax.servlet.http.*
import javax.servlet.*; Lines indicate the packages we need to load, so you can use method and procedures
import java.io.*;
Declare the servlet class.
This servlet extends javax.servlet.http.HttpServlet, the
public class HelloClientServlet extends HttpServlet standard base class for HTTP Servlets.
{
protected void doGet( HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

Throws:
HttpServlet's doGet req - res - java.io.IOException - if an input or
method is getting an HttpServletRequest obje an HttpServletResponse output error is detected when the
overridden. ct that contains the object that contains servlet handles the GET request.
request of the client the response the servlet ServletException - if the request for the
sends back GET could not be handled. It Defines a
general exception a servlet can throw
when it encounters difficulty.

Subject: Web Technology


{
setContentType is HttpServletResponse method, object to set the content type
res.setContentType("text/html");
of the response that we are going to send.
We must set all response headers before you request a PrintWriter or
ServletOutputStream to send body data to the response.

PrintWriter object is requested to write a response content type


PrintWriter out = res.getWriter();
[API 2.0] ServletResponse.getWriter() is a new feature of JSDK version 2.0.
Servlet engine does not support JSDK 2.0 you can replace the above line by
"ServletOutputStream out = res.getOutputStream();".

out.println("<HTML><HEAD>
<TITLE>Hello World!</TITLE>"+ In these lines we use the PrintWriter to write the text of type
"</HEAD><BODY>Hello World!</BODY> text/html (as specified through the content type).
</HTML>");

out.close(); PrintWriter is closed, when the writing to it is finished.


}
} NOTE: This line is included for completeness. It is not strictly necessary. The Web Server closes the PrintWriter or
ServletOutputStream automatically when a service call returns. An explicit call to close() is useful when you want
to do some post processing after the response to the client has been fully written. Calling close() tells the Web
Subject: Web
ServerTechnology
that the response is finished and the connection to the client may be closed as well.
Servlet Life Cycle

Servlet life cycle contains five steps:

1. Loading of Servlet
2. Creating instance of Servlet
3. Invoke init() once
4. Invoke service() repeatedly for each
client request
5. Invoke destroy()

Subject: Web Technology


Servlet Life Cycle

Subject: Web Technology


Servlet Life Cycle

Subject: Web Technology


Servlet Life Cycle

Note: Unlike init() and destroy() that are called


only once, the service() method can be called any
number of times during servlet life cycle. As long
as servlet is not destroyed, for each client request
the service() method is invoked.
Out of all the 5 steps in life cycle, this is the only
Subject: Web Technology step that executes multiple times.
Servlet Life Cycle

Subject: Web Technology


Handling HTTP get Requests

Subject: Web Technology


Packet format of GET request

Subject: Web Technology


Packet format of POST request

Subject: Web Technology


Difference between GET and Post

GET POST
In GET method, values are visible in the URL. In POST method, values are not visible in the URL.
GET has a limitation on the length of the values,
POST has no limitation on the length of the values
generally 255 characters. since they are submitted via the body of HTTP.
GET performs are better compared to POST It has lower performance as compared to GET
because of the simple nature of appending the method because of time spent in including POST
values in the URL. values in the HTTP body.
This method supports different data types, such
This method supports only string data types.
as string, numeric, binary, etc.
GET results can be bookmarked. POST results cannot be bookmarked.
GET request is often cacheable. The POST request is hardly cacheable.
GET Parameters remain in web browser history. Parameters are not saved in web browser history.

Subject: Web Technology


Servlet for handling HTTP GET request

Subject: Web Technology


Servlet for handling HTTP GET request
• In this code observe the line <form action = 'add'>.
The action attribute defines where the data gets
sent.
• On submitting this form, form-data will be sent to a
servlet whose url is mapped with it.
• Also note that one text field has a name of first and
the other has a name of second.
• Now, suppose that we enter 10 in the first textfield
and 15 in the second textfield, and click the
"Submit" button, we will get a "404 page not
found" error (because we have yet to write the
servlet).
• BUT observe the destination URL:
http://localhost:8080/chapter2/add?first=10&second=15

Observe that:
• The URL http://localhost:8080/6_HttpRequest/add is retrieved from the attribute action="add" of the <form> start-tag.
• A '?' follows the URL, which separates the URL and called query string. Notice the "query string" ?first=10&second=15.
• This part contains two parameters with parameter values:
first=10
Subject:
second=15Web Technology
Servlet for handling HTTP GET request
Writing a Servlet to Process Form Data

• When user submits an HTML form that does not


specify method parameter for the form tag or
explicitly specifies the GET method, the doGet()
method is invoked.
• To process HTTP GET requests that are sent to
the servlet, override the doGet( ) method.

The form-data will be sent to the servelet and


output will look like this

Subject: Web Technology


Servlet for handling HTTP Post request

Subject: Web Technology


Servlet for handling HTTP Post request

Subject: Web Technology


Servlet for handling HTTP Post request

Subject: Web Technology


Servlet for handling HTTP Post request

Subject: Web Technology


Servlets - Page Redirection

Subject: Web Technology


RequestDispatcher
• The RequestDispatcher interface provides the facility of dispatching the request to another resource it
may be html, servlet or jsp. This interface can also be used to include the content of another resource
also. It is one of the way of servlet collaboration.
• There are two methods defined in the RequestDispatcher interface.
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:

1. public void forward (ServletRequest request, ServletResponse response) throws


ServletException, java.io.IOException:
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the
server.

2. public void include(ServletRequest request, ServletResponse response) throws


ServletException, java.io.IOException
Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

Subject: Web Technology


Subject: Web Technology
Subject: Web Technology
Forward() method sendRedirect() method
The forward() method works at server side. The sendRedirect() method works at client side.
It sends the same request and response It always sends a new request.
objects to another servlet.
It can work within the server only. It can be used within and outside the server.
Example: Example:
request.getRequestDispacher("servlet2").fo response.sendRedirect("servlet2");
rward(request,response);

Subject: Web Technology


3)URL Rewriting
• In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.
• We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??

• A name and a value is separated using an equal = sign, a parameter name/value pair is separated
from another parameter using the ampersand(&).
• When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server.
From a Servlet, we can use getParameter() method to obtain a parameter value.

Subject: Web Technology


Advantage of URL Rewriting
It will always work whether cookie is disabled or not (browser independent).
Extra form submission is not required on each pages.

Disadvantage of URL Rewriting


It will work only with links.
It can send Only textual information.

Subject: Web Technology


Example of using URL Rewriting
In this example, we are maintaning the state of the user using link. For this purpose, we are appending the
name of the user in the query string and getting the value from the query string in another page.

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

Subject: Web Technology


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

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}
catch(Exception e) {System.out.println(e);}
} }

Subject: Web Technology


HttpSession interface
• In this, container creates a session id for each user.
• The container uses this id to identify the particular user.
• An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.

Subject: Web Technology


Subject: Web Technology
Subject: Web Technology
Subject: Web Technology
Subject: Web Technology
Sr. No. Method & Description
public Object getAttribute(String name)
1
This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
public Enumeration getAttributeNames()
2
This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
public long getCreationTime()
3
This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
public String getId()
4
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
5
This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT
public int getMaxInactiveInterval()
6 This method returns the maximum time interval (seconds), that the servlet container will keep the session open between
client accesses.
public void invalidate()
7
This method invalidates this session and unbinds any objects bound to it.
public boolean isNew()
8
This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
public void removeAttribute(String name)
9
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
10
This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
Subject:
11 Web Technology
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
/ Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Create a session object if it is already not created.


HttpSession session = request.getSession(true);

// Get session creation time.


Date createTime = new Date(session.getCreationTime());

Subject: Web Technology


// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew()) {
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

Subject: Web Technology


// Set response content type "<tr>\n" +
response.setContentType("text/html"); " <td>id</td>\n" +
PrintWriter out = response.getWriter(); " <td>" + session.getId() + "</td>
</tr>\n" +
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "<tr>\n" +
"transitional//en\">\n"; " <td>Creation Time</td>\n" +
" <td>" + createTime + " </td>
out.println(docType + </tr>\n" +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" + "<tr>\n" +
" <td>Time of Last Access</td>\n" +
"<body bgcolor = \"#f0f0f0\">\n" + " <td>" + lastAccessTime + " </td>
"<h1 align = \"center\">" + title + "</h1>\n" + </tr>\n" +
"<h2 align = \"center\">Session Infomation</h2>\n" +
"<table border = \"1\" align = \"center\">\n" + "<tr>\n" +
" <td>User ID</td>\n" +
"<tr bgcolor = \"#949494\">\n" + " <td>" + userID + " </td>
" <th>Session info</th><th>value</th> </tr>\n" +
</tr>\n" +

Subject: Web Technology


"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td>
</tr>\n" + Output
"</table>\n" +
"</body>
</html>"
);
}
}

Subject: Web Technology

You might also like