0% found this document useful (0 votes)
6 views21 pages

Understanding Java Servlets and CGI

Servlet technology is a server-side solution for creating dynamic web applications, offering advantages over the older CGI method, such as better performance, portability, and security. Servlets utilize Java's robust features and provide a variety of classes and interfaces for handling requests and responses. The document also discusses cookies, their types, and how they are used to maintain user state across sessions.

Uploaded by

misbhanmcc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Understanding Java Servlets and CGI

Servlet technology is a server-side solution for creating dynamic web applications, offering advantages over the older CGI method, such as better performance, portability, and security. Servlets utilize Java's robust features and provide a variety of classes and interfaces for handling requests and responses. The document also discusses cookies, their types, and how they are used to maintain user state across sessions.

Uploaded by

misbhanmcc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Servlets

Servlet technology is used to create a web application


(resides at server side and generates a dynamic web
page).

Servlet technology is robust and scalable because of


java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was common as a server-
side programming language. However, there were
many disadvantages to this technology.

There are many interfaces and classes in the Servlet


API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc

Servlet can be described in many ways, depending on


the context.

o Servlet is a technology which is used to create a


web application.
o Servlet is an API that provides many interfaces and
classes including documentation.
o Servlet is an interface that must be implemented
for creating any Servlet.
o Servlet is a class that extends the capabilities of
the servers and responds to the incoming requests.
It can respond to any requests.
o Servlet is a web component that is deployed on the
server to create a dynamic web page
What is a web application?

A web application is an application accessible from the


web. A web application is composed of web
components like Servlet, JSP, Filter, etc. and other
elements such as HTML, CSS, and JavaScript. The web
components typically execute in Web Server and
respond to the HTTP request.

CGI (Common Gateway Interface)

CGI is actually an external application that is written by using


any of the programming languages like C or C++ and this is
responsible for processing client requests and generating
dynamic content.
In CGI application, when a client makes a request to access
dynamic Web pages, the Web server performs the following
operations:
 It first locates the requested web page i.e the required CGI
application using URL.
 It then creates a new process to service the client’s request.
 Invokes the CGI application within the process and passes
the request information to the application.
 Collects the response from the CGI application.
 Destroys the process, prepares the HTTP response, and
sends it to the client.

So, in CGI server has to create and destroy the process for
every request. It’s easy to understand that this approach is
applicable for handling few clients but as the number of clients
increases, the workload on the server increases and so the
time is taken to process requests increases.

Difference between Servlet and CGI

CGI (Common Gateway


Servlet Interface)

Servlets are portable and


CGI is not portable.
efficient.

In Servlets, sharing data is In CGI, sharing data is not


possible. possible.

Servlets can directly CGI cannot directly


CGI (Common Gateway
Servlet Interface)

communicate with the communicate with the


webserver. webserver.

Servlets are less expensive CGI is more expensive than


than CGI. Servlets.

Servlets can handle the CGI cannot handle the


cookies. cookies.

Servlets are built from two packages:


 [Link](Basic)
 [Link](Advance)

Disadvantages of CGI

There are many problems in CGI technology:

1. If the number of clients increases, it takes more


time for sending the response.
2. For each request, it starts a process, and the web
server is limited to start processes.
3. It uses platform dependent language e.g. C, C+
+, perl.

Advantages of Servlet

There are many advantages of Servlet over CGI. The


web container creates threads for handling the multiple
requests to the Servlet. Threads have many benefits
over the Processes such as they share a common
memory area, lightweight, cost of communication
between the threads are low.
The advantages of Servlet are

1. Better performance: because it creates a thread


for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need
to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.

A simple java Servlet

import [Link].*;
import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class firstservlet extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
[Link]("text/html");
// Actual logic goes here.
PrintWriter out = [Link]();
[Link]("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
Servlet
API Released Specification Platform Important Changes
version

Jakarta
May 31, Jakarta EE remove deprecated features and implement
Servlet 6.0
2022 10 requested enhancements
6.0

Jakarta
Oct 9, Jakarta EE API moved from
Servlet 5.0
2020 9 package [Link] to [Link]
5.0

Jakarta
Sep 10, Jakarta EE
Servlet 4.0 Renamed from "Java" trademark
2019 8
4.0.3

Java
Servlet Sep 2017 JSR 369 Java EE 8 HTTP/2
4.0

Java
Non-blocking I/O, HTTP protocol upgrade
Servlet May 2013 JSR 340 Java EE 7
mechanism (WebSocket)[19]
3.1

Java
December Java EE 6, Pluggability, Ease of development, Async Servlet,
Servlet JSR 315
2009 Java SE 6 Security, File Uploading
3.0

Java
September Java EE 5,
Servlet JSR 154 Requires Java SE 5, supports annotation
2005 Java SE 5
2.5

Java
November J2EE 1.4,
Servlet JSR 154 [Link] uses XML Schema
2003 J2SE 1.3
2.4

Java
August J2EE 1.3,
Servlet JSR 53 Addition of Filter
2001 J2SE 1.2
2.3

Java
August JSR 902, JSR J2EE 1.2, Becomes part of J2EE, introduced independent web
Servlet
1999 903 J2SE 1.2 applications in .war files
2.2
Java
November First official specification,
Servlet 2.1a Unspecified
1998 added RequestDispatcher, ServletContext
2.1

Java
December Part of April 1998 Java Servlet Development Kit
Servlet — JDK 1.1
1997 2.0[20]
2.0

Java
December Part of June 1997 Java Servlet Development Kit
Servlet —
1996 (JSDK) 1.0[14]
1.0

Annotations
Annotations in Java provide additional information to the compiler
and JVM. An annotation is a tag representing metadata about
classes, interfaces, variables, methods, or fields. Annotations do not
impact the execution of the code that they annotate.

An annotation is preceded by the @ symbol. Some common


examples of annotations are @Override and @SuppressWarnings .
These are built-in annotations provided by Java through the java.
lang package.

Annotations provide information to a program at compile time or at


runtime based on which the program can take further action. An
annotation processor processes these annotations at compile time or
runtime to provide functionality such as code generation, error
checking, etc.

import [Link];
import [Link];

import [Link];
//import [Link];
import [Link];
import [Link];
import [Link];

//@WebServlet("/Simple")
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out=[Link]();

[Link]("<html><body>");
[Link]("<h3>Hello Servlet</h3>");
[Link]("</body></html>");
}
}
Let’s look at the @Override annotation as an example:

public class ParentClass {

public String getName() {...}

public class ChildClass extends ParentClass {

@Override

public String getname() {...}

We use the @Override annotation to mark a method that exists in a


parent class, but that we want to override in a child class. The above
program throws an error during compile time because the getname()
method in ChildClass is annotated with @Override even though it
doesn’t override a method from ParentClass

By adding the @Override annotation in ChildClass, the compiler can


enforce the rule that the overriding method in the child class should
have the same case-sensitive name as that in the parent class, and so
the program would throw an error at compile time, thereby catching
an error which could have gone undetected even at runtime.

Reading a request header

Usually, we'll know the name of the request header that we want to
read. In this case, it is a simple matter of calling getHeader() on the
HttpServletRequest object that was passed to our doGet()/doPost()
method. Request headers are untrusted data. It is trivial to program
a client to set any old string it likes in any request header. You should
interpret request headers as a statement about "how the client
would like its data", and not as the basis for security-related
decisions.

For example, here is how to read the user-agent header, which


essentially tells us which browser (IE, Mozilla, Safari etc) and
operating system is making the request:

[Link]

<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

[Link]
import [Link].*;
import [Link].*;
import [Link].*;

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Set response content type


[Link]("text/html");

PrintWriter out = [Link]();


String title = "Using GET Method to Read Form Data";
String agent = [Link]("user-agent");
if (agent != null && [Link]("MSIE") > -1) {
[Link]("Internet Explorer mode");
} else {
[Link]("Non-Internet Explorer mode");
}
[Link]( "<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ [Link]("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ [Link]("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
}
Some useful headers

[Link]-agent

As mentioned above, the user-agent can give us the browser (or


robot) and version, plus some information about plugins installed. A
big problem with this header is the wide variety of formats that
different agents use in practice.

[Link]

The referer header indicates the link that caused the current item to
be requested.

HTTP Request Header

HTTP Request Header is used to pass the additional information


about the requestor itself to the server. It can be used by the client
to pass the useful information. getHeaderNames() and getHeader()
methods of the [Link] interface can
be used to get the header information. Following are the important
header information which comes from the browser side and can be
frequently used while programming:
Accept: This specifies the certain media types that are acceptable in
the response

Accept-Charset: This indicates the character sets that are acceptable


in the response. For e.g.: ISO-8859-1

Accept-Encoding: This restricts the content-coding values that are


acceptable in the response

Accept-Language: This restricts the set of language that is preferred


in the response

Authorization: This type indicates that user agent is attempting to


authenticate itself with a server

From: This type contains the internet email address for the user who
controls the requesting user agent

Host: This type indicates the internet host and port number of the
resource being requested

If-Modified-Since: This header indicates that the client wants the


page only if it has been changed after the specified date. The server
sends a 304 code (i.e. a Not Modified header) if no newer result is
available

Range: This type requests one or more sub-ranges of the entity,


instead of the entire entity

Referrer: This type enables the client to specify for the servers
benefit, the address (URL) of the resources from which the request
url was obtained

User-Agent: This type contains the information about the user agent
originating the request
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HttpRequestHeaderExample extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String host = [Link]("Host");
String userAgent = [Link]("User-Agent");
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<b>Host: </b>" + host + "<br>");
[Link]("<b>User Agent: </b>" + userAgent);
[Link]("</body></html>");
}
}

Working with cookies


A cookie is a small piece of data that is sent from a website and
stored in your computer. Cookies are mostly used to recognize the
user and load the stored information.

A cookie is a small piece of information that is persisted


between the multiple client requests.

A cookie has a name, a single value, and optional


attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new


request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the
cache of the browser. After that if request is sent by the
user, cookie is added with request by default. Thus, we
recognize the user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.


1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each


time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed


each time when user closes the browser. It is removed
only if user logout or signout.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the


browser.
2. Only textual information can be set in Cookie
object.

Cookie class

[Link] class provides the


functionality of using cookies. It provides a lot of useful
methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.


Cookie(String name, constructs a cookie with a specifi
String value) name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the


Cookie class.

Method Description

public void Sets the maximum age of the cookie


setMaxAge(int expiry) seconds.
public String Returns the name of the cookie. The nam
getName() cannot be changed after creation.
public String Returns the value of the cookie.
getValue()
public void changes the name of the cookie.
setName(String name)
public void changes the value of the cookie.
setValue(String value)

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we ne


some methods provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of

HttpServletResponse interface is used to add cookie in respo


object.

2. public Cookie[] getCookies():method of HttpServletRequ


interface is used to return all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//


creating cookie object
2. [Link](ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly


used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of co


okie
2. [Link](0);//changing the maximum age to 0 sec
onds
3. [Link](ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

Cookie ck[]=[Link]();
for(int i=0;i<[Link];i++){
[Link]("<br>"+ck[i].getName()+"
"+ck[i].getValue());//printing name and value of cookie
}
Simple example of Servlet Cookies

In this example, we are storing the name of the user in


the cookie object and accessing it in another servlet. As
we know well that session corresponds to the particular
user. So if you access it from too many browsers with
different values, you will get the different value.

[Link]

<form action="servlet1" method="post">


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

[Link]

import [Link].*;
import [Link].*;
import [Link].*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpSer


vletResponse response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

String n=[Link]("userName");
[Link]("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie o


bject
[Link](ck);//adding cookie in the respons
e

//creating submit button


[Link]("<form action='servlet2'>");
[Link]("<input type='submit' value='go'>");
[Link]("</form>");

[Link]();

}catch(Exception e){[Link](e);}
}
}

[Link]

import [Link].*;
import [Link].*;
import [Link].*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServ


letResponse response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

Cookie ck[]=[Link]();
[Link]("Hello "+ck[0].getValue());

[Link]();

}catch(Exception e){[Link](e);}
}

[Link]

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

You might also like