servlet

Servlet Tutorial

java servlet tutorial
         Servlet technology is used to create web application (resides at server side and generates dynamic web page).
         Servet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology. We have discussed these disadvantages below.
       There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.

What is a Servlet?

Servlet can be described in many ways, depending on the context.
  • Servlet is a technology i.e. used to create web application.
  • Servlet is an API that provides many interfaces and classes including documentations.
  • Servlet is an interface that must be implemented for creating any servlet.
  • Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.
  • Servlet is a web component that is deployed on the server to create dynamic web page.
servlet 


Do You Know ?

  • What is the web application and what is the difference between Get and Post request ?
  • What information is received by the web server if we request for a servlet ?
  • How to run servlet in Eclipse, MyEclipse and Netbeans IDE ?
  • What are the ways for servlet collaboration and what is the difference between RequestDispatcher and sendRedirect() method ?
  • What is the difference between ServletConfig and ServletContext interface?
  • How many ways we can maintain state of an user ? Which approach is mostly used in web development ?
  • How to count total number of visitors and total response time for a request using Filter ?
  • How to run servlet with annotation ?
  • How to create registration form using Servlet and Oracle database ?
  • How can we upload and download file from the server ?

What is 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 components such as HTML. The web components typically execute in Web Server and respond to HTTP request.

CGI(Commmon Gateway Interface)

CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.
problem in cgi and how servlet is better

Disadvantages of CGI

There are many problems in CGI technology:
  1. If number of clients increases, it takes more time for sending response.
  2. For each request, it starts a process and Web server is limited to start processes.
  3. It uses platform dependent language e.g. C, C++, perl.

Advantage of Servlet

advantage 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 a lot of benefits over the Processes such as they share a common memory area, lighweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:
  1. better performance: because it creates a thread for each request not process.
  2. Portability: because it uses java language.
  3. Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection etc.
  4. Secure: because it uses java language..

Basics of Web

There are some key points that must be known by the servlet programmer. Let's first briefly discuss these points before starting the servlet. These are:
  1. HTTP
  2. HTTP Request Types
  3. Difference between Get and Post method
  4. Container
  5. Server
  6. Difference between web server and application server
  7. Content Type
  8. Introduction of XML
  9. Deployment

HTTP (Hyper Text Transfer Protocol)

Http is the protocol that allows web servers and browsers to exchange data over the web.It is a request response protocol.Http uses reliable TCP connections bydefault on TCP port 80.
http protocol used in servlet

Http Request Methods

Every request has a header that tells the status of the client. There are many request methods. Get and Post requests are mostly used. The http request methods are:
  • GET
  • POST
  • HEAD
  • PUT
  • DELETE
  • OPTIONS
  • TRACE
HTTP Request MethodDescription
GETAsks to get the resource at the requested URL.
POSTAsks the server to accept the body info attached. It like a GET with extra info sent with the request.
HEADAsks for only the header part of whatever a GET would return. Just like GET but with no body.
TRACEAsks for the loopback of the request message, for testing or troubleshooting.
PUTSays to put the enclosed info (the body) at the requested URL.
DELETESays to delete the resource at the requested URL.
OPTIONSAsks for a list of the HTTP methods to which the thing at the request URL can respond

What is the difference between Get and Post Requests?

There are many differences between the Get and Post request. Let's see these differences:

GETPOST
1) In case of Get request, only limited amount of data can be sent because data is sent in header.In case of post request, large amount of data can be sent because data is sent in body.
2) Get request is not secured because data is exposed in URL bar.Post request is secured because data is not exposed in URL bar.
3) Get request can be bookmarkedPost request cannot be bookmarked
4) Get request is idempotentPost request is non-idempotent
5) Get request is more efficient and used than PostPost request is less efficient and used.

anatomy of Get Request


Anatomy of Post Request

As we know, in case of post request original data is sent in message body. Let's see how informations are passed to the server in case of post request. anatomy of Post Request


Content Type

Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.It is a HTTP header that provides the description about what are you sending to the browser.There are many content types:
  • text/html
  • text/plain
  • application/msword
  • application/vnd.ms-excel
  • application/jar
  • application/pdf
  • application/octet-stream
  • application/x-zip
  • images/jpeg
  • vedio/quicktime etc.

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. Let's see what are the interfaces of javax.servlet package.

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 (deprecated now)

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 (deprecated now)

Servlet Interface

Servlet interface provides common behaviour to all the servlets.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.
MethodDescription
public void init(ServletConfig config)initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.
public void service(ServletRequest request,ServletResponse response)provides response for the incoming request. It is invoked at each request by the web container.
public void destroy()is invoked only once and indicates that servlet is being destroyed.
public ServletConfig getServletConfig()returns the object of ServletConfig.
public String getServletInfo()returns information about servlet such as writer, copyright, version etc.

Steps to create the servlet using Tomcat server

There are five steps to create a servlet. These stepse are required for all the servers. We are using 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 application

1)Create a directory structures

The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client. The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the directory structure that must be followed to create the servlet.
directory structure of servlet
As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the WEB-INF folder.

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
The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default request.

DemoServlet.java
  1. package com.poosan.servletexample;
  2. import javax.servlet.http.*;  
  3. import javax.servlet.*;  
  4. import java.io.*;  
  5. public class DemoServlet extends HttpServlet{  
  6. public void doGet(HttpServletRequest req,HttpServletResponse res)  
  7. throws ServletException,IOException  
  8.    {  
  9.           res.setContentType("text/html");
  10.           PrintWriter pw=res.getWriter(); 
  11.   

  12.           pw.println("<html><body>");  
  13.           pw.println("Welcome to servlet");  
  14.           pw.println("</body></html>");  
  15.   
  16.           pw.close();
  17.    }
  18. }  

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:
Jar fileServer
1) servlet-api.jarApache Tomacat
2) weblogic.jarWeblogic
3) javaee.jarGlassfish
4) javaee.jarJBoss

Two ways to load the jar file

  1. set classpath
  2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file paste the class file of servlet in WEB-INF/classes folder.

4)Create the deployment descriptor:

The deployment descriptor is an xml file, from which Web Container gets the information about the servet 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.

web.xml file
  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>poosan</servlet-name>  
  5. <servlet-class>DemoServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>sonoojaiswal</servlet-name>  
  10. <url-pattern>/welcome</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. </web-app>  

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is used in the above web.xml file. The elements are as follows:

<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

To start Apache Tomcat server, double click on the startup.bat file under apachetomcat/bin folder.

What to do if I start the tomcat server first time?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables.
Go to My Computer properties->Click on advanced tab then environment variables->Click on the new tab of user variable->Write JAVA_HOME in variable name and paste the path of jdk folder in variable value->ok->ok->ok
After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.
Note: There are two types of tomcat available:
  1. Apache tomcat that needs to extract only (no need to install)
  2. Apache tomcat that needs to install
It is the example of apache tomcat that needs to extract only.

How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with same port number.Suppose you have installed oracle, you need to change the port number of apache tomcat because both have the default port number 8080.
Open server.xml file in notepad under apache-tomcat/conf folder . Change the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by 8888 and save this file.

How to deploy the your project

Copy the project and paste it in the webapps folder under apache tomcat.

There are several ways to deploy the project. The are:
  • By copying the context(project) folder into the webapps directory
  • By copying the war folder into the webapps directory
  • By selecting the folder path from the server
  • By selecting the war file from the server
  1. projectfolder><strong> jar cvf myproject.war *</strong>  
Creating war file has an advantage that moving the project from one location to another takes less time.

How to access the servlet

open broser and write http://hostname:portno/contextroot/urlpattern
how to access the servlet



SHARE

Unknown

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment