Nothing Special   »   [go: up one dir, main page]

Web Servers and Servlets

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Web Servers and Servlets

Web Server

Web Server may be a computer program, software or any remote computer system that respond on
client request via hypertext transfer protocol connection to share web resources such as web pages
over world wide web.

Every web server is given a unique domain name and IP address for its identity over the internet.

A web server respond to the end user either by sending http response to the client by invoking
script and communicating through database or by sending the requested web resource to the client
related to requested URL.

When the client sends an http request to web server for a web content, web server search for the
requested resource and send it to client as http response. If the requested web content is missing or
not available, “Error 404: content not found” will be displayed.

Web servers require continuous power supply and proper cooling for efficient and uninterrupted
smooth working.
Features of Web Server

 Web server program is operated by receiving http request from client and send relevant
document as http response to client. If web content related to client’s request is not found,
server sends an error message.

 Web Servers have the facility to handle not only static contents like file servers but also
support dynamic content handling via related interfaces like ASP, JSP, SGI, CGI, ASP.Net, PHP,
Server API etc.

 Web Servers plays a very important role in web hosting that makes faster loading of
websites when client request for it.

 Web servers have the feature of keeping log files for client requests and server responses
that helps to collect statistics by running log analyzer on log files.

 Web server support lower bandwidth usage and reduce the size of response.

 Web server has the feature of authorization through user credentials before allowing access
to some web resources.

 One of the primary features of web server is large data storage facility. That helps the web
server to store data of multiple websites.

 Web Server has the feature of providing secure and encrypted connections to clients in port
443 instead of port 80 with the help of https.

How do web servers work?

Web server software is accessed through the domain names of websites and ensures the delivery of
the site's content to the requesting user. The software side is also comprised of several
components, with at least an HTTP server. The HTTP server is able to understand HTTP and URLs.

As hardware, a web server is a computer that stores web server software and other files related to
a website, such as HTML documents, images and JavaScript files.
When a web browser, like Google Chrome or Firefox, needs a file that's hosted on a web server, the
browser will request the file by HTTP. When the request is received by the web server, the HTTP
server will accept the request, find the content and send it back to the browser through HTTP.

More specifically, when a browser requests a page from a web server, the process will follow a
series of steps.
1. First, a person will specify a URL in a web browser's address bar.

2. The web browser will then obtain the IP address of the domain name -- either translating
the URL through DNS (Domain Name System) or by searching in its cache. This will bring the
browser to a web server.

3. The browser will then request the specific file from the web server by an HTTP request. The
web server will respond, sending the browser the requested page, again, through HTTP.

4. If the requested page does not exist or if something goes wrong, the web server will respond
with an error message. The browser will then be able to display the webpage.

Examples of web servers

There are a number of common web servers available, some including:

 Apache HTTP Server. Developed by Apache Software Foundation, it is a free and open-source
web server for Windows, Mac OS X, Unix, Linux, Solaris and other operating systems; it needs
the Apache license.

 Microsoft Internet Information Services (IIS). Developed by Microsoft for Microsoft


platforms; it is not open sourced, but widely used.

 Nginx. A popular open-source web server for administrators because of its light resource
utilization and scalability. It can handle many concurrent sessions due to its event-driven
architecture. Nginx also can be used as a proxy server and load balancer.

 Lighttpd. A free web server that comes with the FreeBSD operating system. It is seen as fast
and secure, while consuming less CPU power.

 Sun Java System Web Server. A free web server from Sun Microsystems that can run on
Windows, Linux and Unix. It is well-equipped to handle medium to large websites.

Introduction to Servlets

Creating dynamic web pages i.e., the ones which have the capability to change the site contents
according to the time or are able to generate the contents according to the request received by the
client.
Using Java, we can generate dynamic web pages and that way is Java Servlet.

Servlets are the Java programs that run on the Java-enabled web server or application server. They
are used to handle the request obtained from the web server, process the request, produce the
response, and then send response back to the web server.

Properties of Servlets:

 Servlets work on the server-side.


 Servlets are capable of handling complex requests obtained from web server.

Execution of Servlets:

Execution of Servlets involves six basic steps:

1. The clients send the request to the web server.


2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client browser displays it on the
screen.

Servlet Architecture

Advantages of a Java Servlet

 Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new
request received.

 Servlets as written in Java are platform independent.

 Removes the overhead of creating a new process for each request as Servlet doesn’t run in a
separate process. There is only a single instance which handles all requests concurrently. This
also saves the memory and allows a Servlet to easily manage client state.

 It is a server-side component, so Servlet inherits the security provided by the Web server.
 The API designed for Java Servlet automatically acquires the advantages of Java platform such
as platform independent and portability. In addition, it obviously can use the wide range of
APIs created on Java platform such as JDBC to access the database.

Life Cycle of a Servlet

The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it.

Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,

 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.

1. Loading a Servlet:

The first stage of the Servlet lifecycle involves loading and initializing the Servlet by the Servlet
container.

The Web container or Servlet Container can load the Servlet at either of the following two stages:

 Initializing the context, on configuring the Servlet with a zero or positive integer value.

 If the Servlet is not preceding stage, it may delay the loading process until the Web container
determines that this Servlet is needed to service a request.

The Servlet container performs two operations in this stage:

Loading: Loads the Servlet class.

Instantiation: Creates an instance of the Servlet. To create a new instance of the Servlet, the
container uses the no-argument constructor.

2. Initializing a Servlet:
After the Servlet is instantiated successfully, the Servlet container initializes the instantiated Servlet
object.

The container initializes the Servlet object by invoking Servlet.init (ServletConfig) method which
accepts ServletConfig object reference as parameter.

The Servlet container invokes the Servlet.init (ServletConfig) method only once, immediately after
the Servlet.init (ServletConfig) object is instantiated successfully. This method is used to initialize
the resources, such as JDBC data source.

Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.

3. Handling request:

After initialization, the Servlet instance is ready to serve the client requests. The Servlet container
performs the following operations when the Servlet instance is located to service a request:

 It creates the ServletRequest and ServletResponse objects. In this case, if this is a HTTP
request, then the Web container creates HttpServletRequest and HttpServletResponse objects
which are subtypes of the ServletRequest and ServletResponse objects respectively.

 After creating the request and response objects it invokes the Servlet.service (ServletRequest,
ServletResponse) method by passing the request and response objects.

4. Destroying a Servlet:

When a Servlet container decides to destroy the Servlet, it performs the following operations.

 It allows all the threads currently running in the service method of the Servlet instance to
complete their jobs and get released.

 After currently running threads have completed their jobs, the Servlet container calls
the destroy () method on the Servlet instance.

After the destroy() method is executed, the Servlet container releases all the references of this
Servlet instance so that it becomes eligible for garbage collection.

Servlet Life Cycle Methods

There are three life cycle methods of a Servlet :

1. init()
2. service()
3. destroy()
1. init () method: The Servlet.init() method is called by the Servlet container to indicate that this
Servlet instance is instantiated successfully and is about to put into service.

//init() method

public class MyServlet implements Servlet{

public void init(ServletConfig config) throws ServletException {

//initialization code

//rest of code

2. service () method: The service() method of the Servlet is invoked to inform the Servlet about
the client requests.
 This method uses ServletRequest object to collect the data requested by the client.
 This method uses ServletResponse object to generate the output content.

// service() method

public class MyServlet implements Servlet{

public void service(ServletRequest req, ServletResponse res)

throws ServletException, IOException {

// request handling code

// rest of code

3. destroy () method: The destroy() method runs only once during the lifetime of a Servlet and
signals the end of the Servlet instance.
//destroy() method

public void destroy()

As soon as the destroy() method is activated, the Servlet container releases the Servlet instance.

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.

Let's see what the interfaces of javax.servlet package are.

Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils

Steps to create a servlet

There are given 6 steps to create a servlet example. These steps are required for all the servers.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1) Create a directory structures

2) Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class
Servlet Interface

Servlet interface provides common behavior to all the servlets. Servlet interface defines methods
that all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It
provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to
destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of
servlet. These are invoked by the web container.

 public void init(ServletConfig config)


 public void service(ServletRequest request,ServletResponse response)
 public void destroy()
 public ServletConfig getServletConfig()
 public String getServletInfo()

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

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

In servlets the output can be either character or byte. For character data (i.e text) you can
use PrintWriter for others use ServletOutputStream.
PrintWriter: prints text data to a character stream.

getWriter: Returns a PrintWriter object that can send character text to the client.

GenericServlet class

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

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException
{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}

HttpServlet class

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("<h1>Welcome to servlet</h1>");
pw.println("</body></html>");

pw.close();//closing the stream


}
}

3) Compile the servlet

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.
4) Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information about the
servlet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.

<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

<web-app> represents the whole application.


<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5) Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.

Paste your folder in webapps which is under tomcat.

6) How to access the servlet

Open browser and write http://hostname:portno/contextroot/urlpatternofservlet.

Session Management

Session Management is a mechanism used by the Web container to store session information for a
particular user. There are four different techniques used by Servlet application for session
management. They are as follows:

1. Cookies
2. Hidden form field
3. URL Rewriting
4. HttpSession

Cookies in Servlet

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.

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.

HttpSession

HttpSession object is used to store entire session with a specific client. We can store, retrieve and
remove attribute from HttpSession object. Any servlet can have access to HttpSession object
throughout the getSession() method of the HttpServletRequest object.

1. On client's first request, the Web Container generates a unique session ID and gives it back
to the client with response. This is a temporary session created by web container.
2. The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.
3. The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.

URL Rewriting
If the client has disabled cookies in the browser then session management using cookie won’t work.
In that case URL Rewriting can be used as a backup. URL rewriting will always work.
In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of
name/value pair seperated by an equal(=) sign.
For Example:
When the User clicks on the URL having parameters, the request goes to the Web Container with
extra bit of information at the end of URL.
The Web Container will fetch the extra part of the requested URL and use it for session
management.
The getParameter() method is used to get the parameter value at the server side.

Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of a
user.

In such case, we store the information in the hidden field and get it from another servlet. This
approach is better if we have to submit form in all the pages and we don't want to depend on the
browser.

Security Issues

Security has become one of the most important topics in web programming. Security is the science
of keeping sensitive information in the hands of authorized users. On the web, this boils down to
three important issues:

Authentication: Being able to verify the identities of the parties involved


Confidentiality: Ensuring that only the parties involved can understand the communication
Integrity: Being able to verify that the content of the communication is not changed during
transmission.

A client wants to be sure that it is talking to a legitimate server (authentication), and it also want to
be sure that any information it transmits, such as credit card numbers, is not subject to
eavesdropping (confidentiality). The server is also concerned with authentication and
confidentiality. If a company is selling a service or providing sensitive information to its own
employees, it has a vested interest in making sure that nobody but an authorized user can access it.
And both sides need integrity to make sure that whatever information they send gets to the other
party unaltered.

Authentication, confidentiality, and integrity are all linked by digital certificate technology. Digital
certificates allow web servers and clients to use advanced cryptographic techniques to handle
identification and encryption in a secure manner. Thanks to Java's built-in support for digital
certificates, servlets are an excellent platform for deploying secure web applications that use digital
certificate technology. We'll be taking a closer look at them later.

Security is also about making sure that crackers can't gain access to the sensitive data on your web
server. Because Java was designed from the ground up as a secure, network-oriented language, it is
possible to leverage the built-in security features and make sure that server add-ons from third
parties are almost as safe as the ones you write yourself.

You might also like