What is Servlet ?
Servlet is a java programming language class used request response programming model.
Used to create server side web application and generate dynamic web page.
Servlet language is Robust and scalable because of java language.Before Servlet we used CGI (Comman Gateway Interface) for server side programming.
The javax.servlet and javax.servlet.http packages provide the servlet interfaces and classes to implement the servlet.
All servlet must implement the servlet interface.
Advantage of Servlet :
The
servlet contain the many advantages over the 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, lightweight, cost of communication between the
treads are low.The following benefits for Servlets are ,
1. Better Performance --> Because it create threads for every client requests.
2. Portability --> It use java so its portability
3. Robust --> Servlet use the JVM so no need to take care about memory leak and GC(garbage collection)
4. Secure --> It use Java language.
Servlet Interface :
This provide the common behavior to all the servlets. Need to implemented this servlet for all creating any servlet.
Methods of Servlet Interface:
1. init() --> This used to initialize the servlet. This is one of the servlet life cycle method.
2. service() --> This is used to processing the incoming request and send response to that request.
3. destroy() --> It is used to destroy the servlet. this can be invoked only once.
4. getServletConfig() --> This method return the object for servlet configuration
5. getServletInfo() --> It return the information about the servlet.
Exmaple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | package com.shinnedhawks; /** * @author Ramachandran */ import java.io.*; import javax.servlet.*; public class ServletExample 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(" out.print("hello simple servlet"); out.print(" "); } public void destroy() { System.out.println("servlet is destroyed"); } public ServletConfig getServletConfig() { return config; } public String getServletInfo() { return "copyright @Ramakavanan 2015"; } } |
Servlet LifeCycle:
1. Web container loads the Servlet classes
2. Web container creates an instance of the servlet classes
3. Initialize the servlet using init() method
4. Invoke the service() method
5. Invoke the destroy() method
Steps for creating Servlet Example:
The servlet example can be created by three ways:
- By implementing Servlet interface,
- By inheriting GenericServlet class, (or)
- By inheriting HttpServlet class
The
mostly used approach is by extending HttpServlet because it provides
http request specific method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
- Create a directory structure
- Create a Servlet
- Compile the Servlet
- Create a deployment descriptor
- Start the server and deploy the project
- Access the servlet
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.
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.
|
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. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package com.shinnedhawks; /** * @author Ramachandran */ import java.io.*; import javax.servlet.http.*; import javax.servlet.*; 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(" pw.println("Welcome to servlet"); pw.println(" "); pw.close(); //closing the stream } } |
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded.
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 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 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 program.
web.xml file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <web-app> <servlet> <servlet-name>ramakavanan</servlet-name> <servlet-class>DemoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ramakavanan</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app> |
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:
represents the whole application. |
is sub element of and represents the servlet. |
is sub element of represents the name of the servlet. |
is sub element of represents the class of the servlet. |
is sub element of . It is used to map the servlet. |
is sub element of . 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.
One Time Configuration for Apache Tomcat Server
You need to perform 2 tasks:
- set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).
- Change the port number of tomcat (optional). It is required if another server is running on same port (8080).
After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin. |
Note: There are two types of tomcat available:
|
It is the example of apache tomcat that needs to extract only. |
Now server is started successfully.
2) 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. It is located inside the apache-tomcat/conf directory
. Change the Connector port = 8080 and replace 8080 by any four digit
number instead of 8080. Let us replace it by 9999 and save this file.
5) How to deploy the servlet project
Copy the project and paste it in the webapps folder under apache tomcat.
But there are several ways to deploy the project. They are as follows:
- 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
Here, we are using the first approach.
You can also create war file, and paste it inside the webapps directory.
To do so, you need to use jar tool to create the war file. Go inside
the project directory (before the WEB-INF), then write:
projectfolder> jar cvf myproject.war *
Creating war file has an advantage that moving the project from one location to another takes less time.
6) How to access the servlet
Open broser and write https://hostname:portno/contextroot/urlpatternofservlet. For example:
How Servlet Works
It
is important to learn how servlet works for understanding the servlet
well. Here, we are going to get the internal detail about the first
servlet program.
The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
- loads the servlet class.
- instantiates the servlet class.
- calls the init method passing the ServletConfig object
else
- calls the service method passing request and response objects
The
web container calls the destroy method when it needs to remove the
servlet such as at time of stopping server or undeploying the project.
How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it handles the request.
- maps the request with the servlet in the web.xml file.
- creates request and response objects for this request
- calls the service method on the thread
- The public service method internally calls the protected service method
- The protected service method calls the doGet method depending on the type of request.
- The doGet method generates the response and it is passed to the client.
- After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.
No comments:
Post a Comment