Background: Servlet’s Job - Adv Java

Servlet’s Job

  • Read explicit data sent by client(form data)
  • Read implicit data sent by client(request headers)
  • Generate the results
  • Send the explicit data back to client(HTML)
  • Send the implicit data to client (status codes and response headers)

Servlet’s Job

The Hypertext Transfer Protocol (HTTP)

HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a request and response protocol. The client requests a file and the server responds to the request. HTTP uses reliable TCP connections by default on TCP port 80. HTTP (currently at version 1.1 at the time of this writing) was first defined in RFC 2068. It was then refined in RFC 2616.In HTTP, it's always the client who initiates a transaction by establishing a connection and sending an HTTP request.

The server is in no position to contact a client or make a callback connection to the client. Either the client or the server can prematurely terminate a connection. For example, when using a web browser we can click the Stop button on our browser to stop the download process of a file, effectively closing the HTTP connection with the web server.

HTTP Requests

An HTTP transaction begins with a request from the client browser andends with a response from the server. An HTTP request consists of three components:

  • Method —URI—Protocol/Version
  • Request headers
  • Entity body

An example of an HTTP request is the following:

LastName=Franks&FirstName=Michael. The method—URI—protocol version appears as the first line of the request.

GET / servlet/ default.jsp HTTP/ 1.1 where GET is the request method, / servlet/ default.jsp represents the URI and HTTP/ 1.1 the Protocol/ Version section.

The request method will be explained in more details in the next section, "HTTP request Methods."

The URI specifies an Internet resource completely. A URI is usually interpreted as being relative to the server's root directory. Thus, it should always begin with a forward slash /. A URL is actually a type of URI. The Protocol version represents the version of the HTTP protocol being used.

The request header contains useful information about the client environment and the entity body of the request. For example, it could contain the language the browser is set for, the length of the entity body, and so on.

Each header is separated by a carriage return/linefeed (CRLF) sequence. Between the headers and the entity body, there is a blank line (CRLF) that is important to the HTTP request format. The CRLF tells the HTTP server where the entity body begins. In some Internet programming books, this CRLF is considered the fourth component of an HTTP request. In the previous HTTP request, the entity body is simply the following line:

LastName=Franks&FirstName=Michael

The entity body could easily become much longer in a typical HTTP request.

HTTP Requests

Of the seven methods, only GET and POST are commonly used in an Internet application.

HTTP Responses

Similar to requests, an HTTP response also consists of three parts:

  • Protocol—Status code—Description
  • Response headers
  • Entity body

The following is an example of an HTTP response:


The first line of the response header is similar to the first line of the request header. The first line tells you that the protocol used is HTTP version 1.1, the request succeeded (200 = success), and that everything went okay.

The response headers contain useful information similar to the headers in the request. The entity body of the response is the HTML content of the response itself. The headers and the entity body are separated by a sequence of CRLFs.

Where are servlets?

Where are servlets?

Servlet Application Architecture

Servlet Application Architecture

Applications of Java Servlets

  • Building e-commerce store fronts
    • Servlet builds an online catalog based on the contents of a database
    • Customer places an order, which is processed by another servlet
  • Servlets as wrappers for legacy systems
  • Servlets interacting with EJB applications

Java Servlet alternatives

ColdFusion.

Allaire's ColdFusion provides HTML -like custom tags that can be used to perform a number of operations, especially querying a database. This technology had its glamorous time in the history of the World Wide Web as the main technology for web application programming. Its glorious time has since gone with the invention of other technologies.

Server -side JavaScript (SSJS).

SSJS is an extension of the JavaScript language, the scripting language that still rules client -side web programming. SSJS can access Java classes deployed at the server side using the LiveWire technology from Netscape.

PHP.

PHP is an exciting open -source technology that has matured in recent years. The technology provides easy web application development with its session management and includes some built-in functionality, such as file upload. The number of programmers embracing PHP as their technology of choice has risen sharply in recent years.

Servlet.

The servlet technology was introduced by Sun Microsystems in 1996.

JavaServer Pages (JSP).

JSP is an extension of the servlet technology.

Active Server Pages (ASP).

Microsoft's ASP employs scripting technologies that work in Windows platforms, even though there have been efforts to port this technology to other operating systems. Windows ASP works with the Internet Information Server web server. This technology will soon be replaced by Active Server Pages.NET.

Active Server Pages.NET (ASP.NET).

This technology is part of Microsoft's .NET initiative. Interestingly, the .NET Framework employs a runtime called the Common Language Runtime that is very similar to Java Virtual Machine and provides a vast class library available to all .NET languages and from ASP.NET pages. ASP.NET is an exciting technology. It introduced several new technologies including state management that does not depend on cookies or URL rewriting.

The Benefits of Servlets

  • Efficiency: More efficient – uses lightweight java threads as opposed to individual processes.
  • Persistency: Servlets remain in memory. They can maintain state between requests.
  • Portability: Since servlets are written in Java, they are platform independent.
  • Robustness: Error handling, Garbage collector to prevent problems with memory leaks. Large class library – network, file, database, distributed object components, security, etc.
  • Extensibility: Creating new subclasses that suite your needs Inheritance,
    polymorphism, etc.
  • Security: Security provided by the server as well as the Java Security Manager. It eliminates problems associated with executing cgi scripts using operating system “shells”.
  • Powerful: Servlets can directly talk to web server and facilitates database connection pooling, session tracking etc.
  • Convenient: Parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, etc.
  • Rapid development cycle: As a Java technology, servlets have access to the rich Java library, which helps speed up the development process.
  • Widespread acceptance: Java is a widely accepted technology. This means that numerous vendors work on Java -based technologies. One of the advantages of this widespread acceptance is that we can easily find and purchase components that suit our needs, which saves precious development time.

How a Servlet Works

A servlet is loaded by the servlet container the first time the servlet is requested. The servlet then is forwarded the user request, processes it, and returns the response to the servlet container, which in turn sends the response back to the user. After that, the servlet stays in memory waiting for other requests —it will not be unloaded from the memory unless the servlet container sees a shortage of memory.

Each time the servlet is requested, however, the servlet container compares the timestamp of the loaded servlet with the servlet class file. If the class file timestamp is more recent, the servlet is reloaded into memory. This way, we don't need to restart the servlet container every time we update our servlet.

How servlet works?

How servlet works?

The Tomcat Servlet Container

A number of servlet containers are available today these are listed below:

  • Apache Tomcat
  • Allaire/Macromedia JRun
  • New Atlanta ServletExec
  • Gefion Software LiteWebServer
  • Caucho's Resin

The most popular one—and the one recognized as the official servlet/ JSP container —is Apache Tomcat. Originally designed by Sun Microsystems, Tomcat source code was handed over to the Apache Software Foundation in October 1999. In this new home, Tomcat was included as part of the Jakarta Project, one of the projects of the Apache Software Foundation.

Working through the Apache process, Apache, Sun, and other companies —with the help of volunteer programmers worldwide —turned Tomcat into a world -class servlet reference implementation. Currently we are using Apache Tomcat version 6.0.18.

Tomcat by itself is a web server. This means that you can use Tomcat to service HTTP requests for servlets, as well as static files (HTML, image files, and so on). In practice, however, since it is faster for non -servlet, non-JSP requests, Tomcat normally is used as a module with another more robust web server, such as Apache web server or Microsoft Internet Information Server.

Only requests for servlets or JSP pages are passed to Tomcat. For writing a servlet, we need at Java Development Kit installed on our computer. Tomcat is written purely in Java.

Steps to Running Your First Servlet

After we have installed and configured Tomcat, we can put it into service. Basically, we need to follow steps to go from writing our servlet to running it. These steps are summarized as follows:

  • Write the servlet source code. We need to import the javax.servlet package and the javax.servlet.http package in your source file.
  • Compile your source code.
  • Create a deployment descriptor.
  • Run Tomcat.
  • Call your servlet from a web browser.
  1. Write the Servlet Source Code

    In this step, we prepare our source code. We can write the source code ourself using any text editor. The following program shows a simple servlet called Testing Servlet. The file is named Testing Servlet.java. The servlet sends a few HTML tags and some text to the browser.

  2. //TestingServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class TestingServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Servlet Testing</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("Welcome to the Servlet Testing Center"); out.println("</BODY>"); out.println("</HTML>"); } }
  3. Compiling the source code

    For our servlet source code to compile, we need to include the path to the servlet-api.jar file in our CLASSPATH environment variable. The servlet -api.jar is located in the C: Program Files Apache Software Foundation Tomcat 6.0 directory. Here, the drive name depends upon our selection while installation of Tomcat 6.0 on computer. So, compile the file using following way:

    javac TestingServlet.java -classpath "G:Program Files Apache Software FoundationTomcat 6.0libservlet-api.jar"
    After successful compilation, we will get a class file named Testing Servlet.class. Now, copy that class file into directory classes under web -inf as shown in the following figure. All the servlet classes resides in this directory.
  4. Create the Deployment Descriptor

    A deployment descriptor is an optional component in a servlet application. The descriptor takes the form of an XML document called web.xml and must be located in the WEB -INF directory of the servlet application. When present, the deployment descriptor contains configuration settings specific to that application. In order to create the deployment descriptor, we now need to create or edit a web.xml file and place it under the WEB -INF directory. The web.xml for this example application must have the following content.

    The web.xml file has one element —web-app. We should write all our servlets under <web -app>. For each servlet, we have a <servlet> element and we need the <servlet-name> and <servlet-class> elements. The <servletname> is the name for our servlet, by which it is known Tomcat. The <servletclass> is the compiled file of your servlet without the .class extension.

    Apache Tomcat 6.0 Directory Structure.

    Apache Tomcat 6.0 Directory Structure.
  5. We can also add multiple servlet names in our file using multiple servlet tags. The url -pattern suggests the url by which we are going to class our servlet in the web browser. Instead of doing this we can just modify the contents of web.xml by adding the names and mapping of our servlet code.

  6. Run Tomcat

    If Tomcat is not already running, we need to start it by selecting the option “monitor tomcat” from srart menu. We will find the icon of Apache Tomcat on the taskbar when it is running.

  7. Call Your Servlet from a Web Browser

    Now, we can call our servlet from a web browser. By default, Tomcat runs on port 8080. The URL for that servlet has the following format:

    http://domain-name/virtual-directory/servlet/servlet-name

    If we run the web browser from the same computer as Tomcat, you can replace the domain -name part with "localhost". In that case, the URL for your servlet is:

    http:// localhost:8080/ examples/ servlets/ servlet/ TestingServlet

    Typing the URL in the Address or Location box of our web browser will give you the string "Welcome to the Servlet Testing Center," as shown below

    Welcome to the Servlet Testing Center

The javax.servlet package

The javax.servlet package contains seven interfaces, three classes, and two exceptions. The seven interfaces are as follows:

  • RequestDispatcher
  • Servlet
  • ServletConfig
  • ServletContext
  • ServletRequest
  • ServletResponse
  • SingleThreadModel

The three classes are as follows:

  • GenericServlet
  • ServletInputStream
  • ServletOutputStream

And, finally, the exception classes are these:

  • ServletException
  • UnavailableException

The object model of the javax.servlet package is shown in figure below:

javax.servlet package

  • Read explicit data sent by client(form data)
  • Read implicit data sent by client(request headers)
  • Generate the results
  • Send the explicit data back to client(HTML)
  • Send the implicit data to client (status codes and response headers)

status codes and response headers

The Hypertext Transfer Protocol (HTTP)

HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a request and response protocol. The client requests a file and the server responds to the request. HTTP uses reliable TCP connections by default on TCP port 80. HTTP (currently at version 1.1 at the time of this writing) was first defined in RFC 2068. It was then refined in RFC 2616.In HTTP, it's always the client who initiates a transaction by establishing a connection and sending an HTTP request.

The server is in no position to contact a client or make a callback connection to the client. Either the client or the server can prematurely terminate a connection. For example, when using a web browser we can click the Stop button on our browser to stop the download process of a file, effectively closing the HTTP connection with the web server.

HTTP Requests

An HTTP transaction begins with a request from the client browser andends with a response from the server. An HTTP request consists of three components:

  • Method —URI—Protocol/Version
  • Request headers
  • Entity body

An example of an HTTP request is the following:

LastName=Franks&FirstName=Michael. The method—URI—protocol version appears as the first line of the request.

GET / servlet/ default.jsp HTTP/ 1.1 where GET is the request method, / servlet/ default.jsp represents the URI and HTTP/ 1.1 the Protocol/ Version section.

The request method will be explained in more details in the next section, "HTTP request Methods."

The URI specifies an Internet resource completely. A URI is usually interpreted as being relative to the server's root directory. Thus, it should always begin with a forward slash /. A URL is actually a type of URI. The Protocol version represents the version of the HTTP protocol being used.

The request header contains useful information about the client environment and the entity body of the request. For example, it could contain the language the browser is set for, the length of the entity body, and so on.

Each header is separated by a carriage return/linefeed (CRLF) sequence. Between the headers and the entity body, there is a blank line (CRLF) that is important to the HTTP request format. The CRLF tells the HTTP server where the entity body begins. In some Internet programming books, this CRLF is considered the fourth component of an HTTP request. In the previous HTTP request, the entity body is simply the following line:

LastName=Franks&FirstName=Michael

The entity body could easily become much longer in a typical HTTP request.

 HTTP request

Of the seven methods, only GET and POST are commonly used in an Internet application.

HTTP Responses

Similar to requests, an HTTP response also consists of three parts:

  • Protocol—Status code—Description
  • Response headers
  • Entity body

The following is an example of an HTTP response:

The first line of the response header is similar to the first line of the request header. The first line tells you that the protocol used is HTTP version 1.1, the request succeeded (200 = success), and that everything went okay.

The response headers contain useful information similar to the headers in the request. The entity body of the response is the HTML content of the response itself. The headers and the entity body are separated by a sequence of CRLFs.

Where are servlets?

Where are servlets?

Servlet Application Architecture

Servlet Application Architecture

Applications of Java Servlets

  • Building e-commerce store fronts
    • Servlet builds an online catalog based on the contents of a database
    • Customer places an order, which is processed by another servlet
  • Servlets as wrappers for legacy systems
  • Servlets interacting with EJB applications

Java Servlet alternatives

ColdFusion.

Allaire's ColdFusion provides HTML -like custom tags that can be used to perform a number of operations, especially querying a database. This technology had its glamorous time in the history of the World Wide Web as the main technology for web application programming. Its glorious time has since gone with the invention of other technologies.

Server -side JavaScript (SSJS).

SSJS is an extension of the JavaScript language, the scripting language that still rules client -side web programming. SSJS can access Java classes deployed at the server side using the LiveWire technology from Netscape.

PHP.

PHP is an exciting open -source technology that has matured in recent years. The technology provides easy web application development with its session management and includes some built-in functionality, such as file upload. The number of programmers embracing PHP as their technology of choice has risen sharply in recent years.

Servlet.

The servlet technology was introduced by Sun Microsystems in 1996.

JavaServer Pages (JSP).

JSP is an extension of the servlet technology.

Active Server Pages (ASP).

Microsoft's ASP employs scripting technologies that work in Windows platforms, even though there have been efforts to port this technology to other operating systems. Windows ASP works with the Internet Information Server web server. This technology will soon be replaced by Active Server Pages.NET.

Active Server Pages.NET (ASP.NET).

This technology is part of Microsoft's .NET initiative. Interestingly, the .NET Framework employs a runtime called the Common Language Runtime that is very similar to Java Virtual Machine and provides a vast class library available to all .NET languages and from ASP.NET pages. ASP.NET is an exciting technology. It introduced several new technologies including state management that does not depend on cookies or URL rewriting.

The Benefits of Servlets

  • Efficiency: More efficient – uses lightweight java threads as opposed to individual processes.
  • Persistency: Servlets remain in memory. They can maintain state between requests.
  • Portability: Since servlets are written in Java, they are platform independent.
  • Robustness: Error handling, Garbage collector to prevent problems with memory leaks. Large class library – network, file, database, distributed object components, security, etc.
  • Extensibility: Creating new subclasses that suite your needs Inheritance,
    polymorphism, etc.
  • Security: Security provided by the server as well as the Java Security Manager. It eliminates problems associated with executing cgi scripts using operating system “shells”.
  • Powerful: Servlets can directly talk to web server and facilitates database connection pooling, session tracking etc.
  • Convenient: Parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, etc.
  • Rapid development cycle: As a Java technology, servlets have access to the rich Java library, which helps speed up the development process.
  • Widespread acceptance: Java is a widely accepted technology. This means that numerous vendors work on Java -based technologies. One of the advantages of this widespread acceptance is that we can easily find and purchase components that suit our needs, which saves precious development time.

How a Servlet Works

A servlet is loaded by the servlet container the first time the servlet is requested. The servlet then is forwarded the user request, processes it, and returns the response to the servlet container, which in turn sends the response back to the user. After that, the servlet stays in memory waiting for other requests —it will not be unloaded from the memory unless the servlet container sees a shortage of memory.

Each time the servlet is requested, however, the servlet container compares the timestamp of the loaded servlet with the servlet class file. If the class file timestamp is more recent, the servlet is reloaded into memory. This way, we don't need to restart the servlet container every time we update our servlet.

How servlet works?

How servlet works?

The Tomcat Servlet Container

A number of servlet containers are available today these are listed below:

  • Apache Tomcat
  • Allaire/Macromedia JRun
  • New Atlanta ServletExec
  • Gefion Software LiteWebServer
  • Caucho's Resin

The most popular one—and the one recognized as the official servlet/ JSP container —is Apache Tomcat. Originally designed by Sun Microsystems, Tomcat source code was handed over to the Apache Software Foundation in October 1999. In this new home, Tomcat was included as part of the Jakarta Project, one of the projects of the Apache Software Foundation.

Working through the Apache process, Apache, Sun, and other companies —with the help of volunteer programmers worldwide —turned Tomcat into a world -class servlet reference implementation. Currently we are using Apache Tomcat version 6.0.18.

Tomcat by itself is a web server. This means that you can use Tomcat to service HTTP requests for servlets, as well as static files (HTML, image files, and so on). In practice, however, since it is faster for non -servlet, non-JSP requests, Tomcat normally is used as a module with another more robust web server, such as Apache web server or Microsoft Internet Information Server.

Only requests for servlets or JSP pages are passed to Tomcat. For writing a servlet, we need at Java Development Kit installed on our computer. Tomcat is written purely in Java.

Steps to Running Your First Servlet

After we have installed and configured Tomcat, we can put it into service. Basically, we need to follow steps to go from writing our servlet to running it. These steps are summarized as follows:

  • Write the servlet source code. We need to import the javax.servlet package and the javax.servlet.http package in your source file.
  • Compile your source code.
  • Create a deployment descriptor.
  • Run Tomcat.
  • Call your servlet from a web browser.
  1. Write the Servlet Source Code

In this step, we prepare our source code. We can write the source code ourself using any text editor. The following program shows a simple servlet called Testing Servlet. The file is named Testing Servlet.java. The servlet sends a few HTML tags and some text to the browser.

Compiling the source code

For our servlet source code to compile, we need to include the path to the servlet-api.jar file in our CLASSPATH environment variable. The servlet -api.jar is located in the C: Program Files Apache Software Foundation Tomcat 6.0 directory. Here, the drive name depends upon our selection while installation of Tomcat 6.0 on computer. So, compile the file using following way:

After successful compilation, we will get a class file named Testing Servlet.class. Now, copy that class file into directory classes under web -inf as shown in the following figure. All the servlet classes resides in this directory.

  1. Create the Deployment Descriptor

    A deployment descriptor is an optional component in a servlet application. The descriptor takes the form of an XML document called web.xml and must be located in the WEB -INF directory of the servlet application. When present, the deployment descriptor contains configuration settings specific to that application. In order to create the deployment descriptor, we now need to create or edit a web.xml file and place it under the WEB -INF directory. The web.xml for this example application must have the following content.

    The web.xml file has one element —web-app. We should write all our servlets under <web -app>. For each servlet, we have a <servlet> element and we need the <servlet-name> and <servlet-class> elements. The <servletname> is the name for our servlet, by which it is known Tomcat. The <servletclass> is the compiled file of your servlet without the .class extension.

    Apache Tomcat 6.0 Directory Structure.

    Apache Tomcat 6.0 Directory Structure.
  2. We can also add multiple servlet names in our file using multiple servlet tags. The url -pattern suggests the url by which we are going to class our servlet in the web browser. Instead of doing this we can just modify the contents of web.xml by adding the names and mapping of our servlet code.

  3. Run Tomcat

    If Tomcat is not already running, we need to start it by selecting the option “monitor tomcat” from srart menu. We will find the icon of Apache Tomcat on the taskbar when it is running.

  4. Call Your Servlet from a Web Browser

    Now, we can call our servlet from a web browser. By default, Tomcat runs on port 8080. The URL for that servlet has the following format:

    http://domain-name/virtual-directory/servlet/servlet-name

    If we run the web browser from the same computer as Tomcat, you can replace the domain -name part with "localhost". In that case, the URL for your servlet is:

    http:// localhost:8080/ examples/ servlets/ servlet/ TestingServlet

    Typing the URL in the Address or Location box of our web browser will give you the string "Welcome to the Servlet Testing Center," as shown below

    Welcome to the Servlet Testing Center

The javax.servlet package

The javax.servlet package contains seven interfaces, three classes, and two exceptions. The seven interfaces are as follows:

  • RequestDispatcher
  • Servlet
  • ServletConfig
  • ServletContext
  • ServletRequest
  • ServletResponse
  • SingleThreadModel

The three classes are as follows:

  • GenericServlet
  • ServletInputStream
  • ServletOutputStream

And, finally, the exception classes are these:

  • ServletException
  • UnavailableException

The object model of the javax.servlet package is shown in figure below:

javax.servlet package

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Adv Java Topics