Servlet
JAVA 2 ENTERPRISE EDITION
J2EE is a platform-independent, Java-centric environment from Sun for developing, building, and deploying Web-based enterprise applications online. The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-based applications.
Some of the key features and services of J2EE:
- At the client tier, J2EE supports pure HTML, as well as Java applets or applications. It relies on Java Server Pages and servlet code to create HTML or other formatted data for the client.
- Enterprise Java Beans (EJBs) provide another layer where the platform’s logic is stored. An EJB server provides functions such as threading, concurrency, security, and memory management. These services are transparent to the author.
- Java Database Connectivity (JDBC), which is the Java equivalent to ODBC, is the standard interface for Java databases.
- The Java servlet API enhances consistency for developers without requiring a graphical user interface.
What is Servlet?
- Servlets can receive and respond to requests from web clients (browsers) working on any client–server protocol, but HTTP is predominantly used.
- Servlet is a server-side script technology which can process client request and give back the response.
- A web application will be made of one or more servlets.
How Servlet Works?
- Login Servlet for processing users login request
- Registration Servlet for users to register in the web application.
- A servlet container is a container for servlets that is responsible for managing the servlets.
- The main functions are load, initialize and execute servlets to serve client requests.
- When a request is received, the container decides what servlet to call based on a configuration file.
- Servlet container comes installed with the web servers.
- Tomcat
- Glassfish
- Jboss
Older methods of Server Side Scripting
- A Servlet does not run in a separate process. This removes the overhead of creating a new process like CGI for each request.
- A Servlet stays in memory between requests. A CGI program needs to be loaded and started for each CGI request. This way the servlet executes faster than CGI.
- There is only a single instance of the servlet which caters to all the HTTP requests concurrently. This saves memory and allows a Servlet to easily manage persistent data. On the contrary,, separate process and memory are allocated for each CGI/HTTP requests.
Servlet Life Cycle
1. javax.servlet: The classes and interfaces in javax.servlet are protocol independent. Eg: It can support different protocols like HTTP, FTP.
2. javax.servlet.http: The classes and interface in this package are specific for requests using the HTTP protocol. Some of the classes and interfaces in this package extend those specified in javax.servlet package
Interface | Class | Exceptions |
Servlet | GenericServlet | ServletException |
ServletRequest | ServletInputStream | UnavailableException |
ServletResponse | ServletOutputStream | |
ServletContext | ServletRequestWrapper | |
ServletConfig | ServletResponseWrapper | |
Filter | ServletRequestEvent | |
FilterChain | ServletResponseEvent |
Interface | Class | Exceptions |
HttpServletRequest | HttpServlet | ServletException |
HttpServletResponse | Cookie | UnavailableException |
HttpSessionContext | HttpRequestWrapper | |
HttpSession | HttpResponseWrapper | |
Servlet Class Hierarchy
Servlet Interface
The Servlet Interface is the abstraction of the Java Servlet API.
It declares the life cycle methods of a servlet.
All the servlet implementations must implement it either directly or indirectly by extending a class that implements the Servlet interface.
Example of Servlet implementations: HTTPServlet, GenericServlet.
Important methods of Servlet Interface
Method | Description |
void destroy() | Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. |
void init(ServletConfig config) | Called by the servlet container to indicate to a servlet that the servlet is being placed into service. |
String getServletInfo() | Called by the servlet container to allow the servlet to respond to a request. |
ServletConfig getServletConfig() | Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. |
void service(ServletRequest req, ServletResponse res) | Called by the servlet container to allow the servlet to respond to a request. |
HTTPServlet
HttpServlet is an abstract class.
Any servlet which works on the HTTP should extend the HTTPServlet class.
This class contains the implementation of methods that are specific to HTTP.
Also contains the implementation of the methods declared in the servlet interface.
Contains the doXXXX methods which are known as the service methods.
All the servlets extending this class should implement any one of the doXXXX() methods.
Method | Description |
void doGet( HttpServletRequest req, HttpServletResponse resp) | Called by the server (via the service method) to allow a servlet to handle a GET request. Will be called when a URL is requested or the form method is GET. |
void doPost( HttpServletRequest req, HttpServletResponse resp) | Called by the server (via the service method) to allow a servlet to handle a POST request. Will be called when the form method is POST. |
void doHead( HttpServletRequest req, HttpServletResponse resp) | Receives an HTTP HEAD request from the protected service method and handles the request. Head request returns only the header information. |
Method | Description |
void doOptions( HttpServletRequest req, HttpServletResponse resp) | Called by the server (via the service method) to allow a servlet to handle an OPTIONS request. OPTIONS method is used by a client to determine the HTTP methods supported by a Web server. |
void doPut( HttpServletRequest req, HttpServletResponse resp) | Called by the server (via the service method) to allow a servlet to handle a PUT request. Used to store an entity in the specified URI. |
void doTrace( HttpServletRequest req, HttpServletResponse resp) | Called by the server (via the service method) to allow a servlet to handle a TRACE request. |
void doDelete( HttpServletRequest req, HttpServletResponse resp) | Called by the server (via the service method) to allow a servlet to handle a DELETE request. Delete request is used to delete the information corresponding to that URI. |
NOTE: In projects, the doGet & doPost are commonly used.
Important Interfaces in Servlet API
HTTPServletRequest
HTTPServletResponse
ServletConfig
ServletContext
RequestDispatcher
NOTE: You will learn more about this in the subsequent slides.
HTTPServletRequest Interface
This interface extends the ServletRequest interface contains methods to access request information by the HTTP servlets.
This interface is used by servlets to access,
The parameters are sent by the client as part of an HTTP request from the browser.
Client Information like port number, client protocol, the form field values.
The servlet container creates a request object and passes it to the service methods(doGet, doPost, etc) as an argument. This object contains the entire user request information sent from the browser.
Important Methods in ServletRequest
Method | Description |
String getParamter(String parameterName) | Returns the value of a request parameter as a String or null if the parameter does not exist. |
Enumeration getParamterNames() | Returns an Enumeration of String objects containing the names of the parameters contained in this request. |
Map getParameterMap() | Returns a java.util.Map of the parameters of this request. |
String [ ] getParameterValues(String paramterName) | Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. |
String setAttribute(String attributeName,Object attributeValue) | Stores an attribute in this request. |
Method | Description |
void removeAttribute(String attributeName) | Removes an attribute from this request. |
String getAttribute(String attributeName) | Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. |
Enumeration getAttributeNames() | Returns an Enumeration containing the names of the attributes available to this request. |
RequestDispatcher getRequestDispatcher(String path) | Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. |
Locale getLocale() | Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. |
getCharacterEncoding()
getInputStream ()
getContentLength ()
getContentType ()
getProtocol ()
getRemoteAddress ()
getRemoteHost ()
getScheme()
getserverName ()
getServerPort ()
isSecure()
Important Methods in HTTPServletRequest
Method | Description |
Cookie [ ] getCookies() | Returns an array containing all of the Cookie objects the client sent with this request. |
String getQueryString() | Used to get the query string from the URL. Always better to use the getParameter method for reading the query arguments since the string returned using the getQueryString method needs to be parsed to get the values. |
HTTPSession getSession() | Returns the current session associated with this request, or if the request does not have a session, creates one. |
HTTPServletResponse Interface
HTTPServletResponse is an interface that contains methods for managing the response sent by an HTTP servlet to the client.
It also contains a set of status codes for sending the request status to the client.
Extends the ServletResponse and contains methods specific to HTTP.
The container creates a HttpServletResponse object and passes it as the argument to the service methods for handling the response. The servlet can use this response object for managing the response.
Important Methods in ServletResponse
Method | Description |
PrintWriter getWriter() | Returns a PrintWriter object that can send character text to the client. |
void setContentType(String type) | Sets the content type of the response being sent to the client. |
void setLocale(Locale locale) | Sets the locale of the response |
Locale getLocale | Returns the locale specified for this response set by the setLocale method. |
Important Methods in HTTPServletResponse interface
Method | Description |
void sendRedirect(String location) | Returns a PrintWriter object that can send character text to the client. |
void sendError(int sc, String msg) | Sends a temporary redirect response to the client using the specified redirect location URL |
void addCookie(Cookie cookie) | Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie. |
void setStatus(int satusCode) | This method is used to set the return status code when there is no error. |
Lend a Hand : Exercise # 1- Your First Servlet
You have successfully completed the basics of Servlets. Now it is time for creating the first servlet.
Software Prerequisites
Eclipse IDE (SDE)
Tomcat installation.
You will complete this in two phases
Phase I – Configuring web server and IDE.
- Step 1 :Open SDE
- Step 2:Go to File -> Switch Workspace -> Other
Go to Windows -> preferences -> Server -> Runtime Environments
Phase II – Develop the first servlet.
Go to the Server View
Windows -> Show View -> Servers
Add a New Server
Right -> click on the Server View -> new -> server-> Select the server and add a Tomcat server.
Creating a Web project
Create a dynamic web project in SDE
File -> New -> Project -> Web -> Dynamic Web Project
Enter the project Name and select the target runtime as shown below.
Right-Click Project -> Click New -> Web -> Servlet
Phase II - Step 2: Adding Servlet
Enter the servlet name
Phase II - Step 3: Adding Servlet
The screen shows the option for setting initialization parameters and URL mapping. For the time being will not alter the values.
Phase II – Step 4: Adding Servlet
Select the doXXXX methods to be overridden . At present we will select only the doGet method.
Select the doXXXX methods to be overridden . At present we will select only the doGet method.
Phase II - Step 5: Configuring WEB.XML
What is web.xml file ?
Web.xml is a configuration file which captures the application configuration and deployment details of a web application.
Some important configurations in Web.xml file:
context-param
servlet
servlet-mapping
welcome-file-list
Lets Look at the servlet C
Open the servlet source file and look at the doGet method generated automatically
ode
Step 1: The servlet extends HTTPServlet
Step 2: The doGet method should be overridden by the developers.
Deploy and Run the application
Right Click The Application -> Run As -> Run on Server
When the application gets loaded call the servlet as shown below
http://localhost:8000/MyFirstWebApp/FirstServlet where FirstServlet is the URL mapping provided in the web.xml file.
Lend a Hand : Exercise # 2- Demo on Servlet Life Cycle Methods
In this demo we will be familiarizing the life cycle methods of a servlet
The three life cycle methods demonstrated are:
init
Service ( we will use the doGet method)
destroy
Servlet code for demo
Create the demo servlet as illustrated below.
Step 1: The servlet extends HTTPServlet
Step 2: Create the init method.
Step 3: Develop the doget method
Step 4: Develop the destroy method
How to Run The Demo
Step 1 : Deploy the application and call the servlet from browser
For the first call (Request) we can see the message “Servlet Initialized ....value of count is :0” printed on the console. This phase is the initialization phase of the servlet and hence the init() method will be called.
Step 2: Refresh the browser
You can see the message “Request Number :1 is received” printed in the console.This is the service phase and hence the doGet() method will be called.
Step 3: On each subsequent refresh the Request number can be seen incremented. Again the doGet() method will be called.
Step 4: Stop the server
We can see the message “Servlet removed from service....Total visitor count is <countValue>” printed in the console. This is the destruction phase of the servlet and hence the destroy() method will be called.
Lend a Hand : Exercise # 3-Form Handling with Servlets
Now lets develop a HTML form and servlet to demonstrate how form parameters are handled in server using servlets.
Step 1 : Create a login.html with a user name and password
Step 2 : Create a LoginServlet to handle the request
Step 3 : Create a SuccessServlet to display the success message
Step 1: Lets create a login.html
Create an HTML page named login.html under the webcontent directory.
Action Servlet for the login page. This should be the same as the URL mapping created for the servlet
Create the form text fields and submit buttons as mentioned.
Step 2: Lets create the LoginServlet
Create an LoginServlet to handle the HTTP request from the form as mentioned below.
Reads the Request Parameters
Redirects the client to a new URL. Sets a value as query string to the next servlet
Step 3: Lets create the SuccessServlet
Create an SuccessServlet to handle the success request as mentioned below.
Reads the Query String parameter value
How to Run The Demo
Step 1 : Deploy the application
Step 2 : Call the login html from the browser
http://localhost:8000/MyFirstWebApp/login.html
Step 3 : Enter the username and password as “admin” and press login button you will be redirected to SuccessServlet
Step 4: Enter some other value for username and password and press login button. You will get the error message printed using LoginServlet.
Comments
Post a Comment