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.
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.
Disadvantages of CGI
There are many problems in CGI technology:
If number of clients increases, it takes more time for sending response.
For each request, it starts a process and Web server is limited to start processes.
It uses platform dependent language e.g. C, C++, perl.
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:
better performance: because it creates a thread for each request not process.
Portability: because it uses java language.
Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection etc.
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:
HTTP
HTTP Request Types
Difference between Get and Post method
Container
Server
Difference between web server and application server
Content Type
Introduction of XML
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 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 Method
Description
GET
Asks to get the resource at the requested URL.
POST
Asks the server to accept the body info attached. It like a GET with extra info sent with the request.
HEAD
Asks for only the header part of whatever a GET would return. Just like GET but with no body.
TRACE
Asks for the loopback of the request message, for testing or troubleshooting.
PUT
Says to put the enclosed info (the body) at the requested URL.
DELETE
Says to delete the resource at the requested URL.
OPTIONS
Asks 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:
GET
POST
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 bookmarked
Post request cannot be bookmarked
4) Get request is idempotent
Post request is non-idempotent
5) Get request is more efficient and used than Post
Post request is less efficient and used.
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.
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:
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
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.
Method
Description
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
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.
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.
By implementing the Servlet interface
By inheriting the GenericServlet class
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.
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:
Jar file
Server
1) servlet-api.jar
Apache Tomacat
2) weblogic.jar
Weblogic
3) javaee.jar
Glassfish
4) javaee.jar
JBoss
Two ways to load the jar file
set classpath
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
<web-app>
<servlet>
<servlet-name>poosan</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</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:
Apache tomcat that needs to extract only (no need to install)
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
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
0 comments:
Post a Comment