1.1 - 1.2 Servlet
1.1 - 1.2 Servlet
he Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is
currently known as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard
Edition). The Java EE provides a platform for developers with enterprise features such as
distributed computing and web services. Java EE applications are usually run on reference run
times such as micro servers or application servers. Examples of some contexts where Java EE
is used are e-commerce, accounting, banking information systems.
In general, enterprise applications refer to software hosted on servers that provide the
applications that support the enterprise.
The Java EE architecture provides services that simplify the most common challenges facing
developers when building modern applications, in many cases through APIs, thus making it
easier to use popular design patterns and industry-accepted best practices.
For example, one common challenge enterprise developers face is how to handle requests
coming in from web-based clients. To simplify this challenge, Java EE provides
the Servlet and JavaServer Pages (JSP) APIs, which provide methods for activities like finding
out what a user typed into a text field in an online form or storing a cookie on a user's browser.
Another common task is how to store and retrieve information in a database. To address this
goal, Java EE provides the Java Persistence API (JPA,) which makes it easy to map data used
within a program to information stored in the tables and rows of a database. Also, creating web
services or highly scalable logic components is simplified through the use of the Enterprise
JavaBeans (EJB) specification. All of these APIs are well tested, relatively easy for Java
developers to learn and can greatly simplify some of the hardest parts of enterprise development.
Database and resource access technologies. For interacting with external and back-end
systems, Java EE includes JavaMail, a standard connector architecture, a Java Message
Service (JMS) API and a Java Transaction API (JTA) for enforcing two-phase commits.
REST and web service technologies: To help with the development and deployment of
REST-, SOAP-, XML- and JSON-based web services, the Java APIs for RESTful Web
Services (JAX-RS) and XML-based web services (JAX-WS) are included, along with APIs
for XML messaging and XML registries (JAXR).
Java EE security and container management: For implementing custom Java EE security
and managing Java EE containers, software developers have access to the Java Authorization
Contract for Containers and the Java Authentication Service Provider Interface for
Containers.
JAVA EE Evolution
Java EE initially evolved as an enterprise application deployment platform that focused on
robustness, Web services, and ease of deployment.
Continually shaped by feedback through the Java Community Process (JCP), Java EE represents
a universal standard in enterprise IT, facilitating the development, deployment, and management
of multi-tier, server-centric applications. Beginning with Java EE 5, focus shifted to increasing
developer efficiency with the introduction of annotations, the Enterprise JavaBeans (EJB) 3.0
business component development model, new and updated Web services, and improvements to
the persistence model.
Java EE 6 further streamlined the development process and increased the flexibility of the
platform, thus enabling it to better address lightweight Web applications.
This is in part due to the introduction of the Web Profile as a subset of the Java EE specification
targeted to Web applications. In addition, Java EE 6 embraced open source frameworks with
hooks for more seamless integration, and began the process of pruning less relevant
technologies.
• As of May 2013, there have been over 50 million downloads of Java EE components, from
Oracle and other industry vendors.
• It has had the fastest adoption of any Java EE release with 18 compliant application server
vendors.
Java EE 7 extends the benefits of Java EE 6 by leveraging the more transparent JCP process and
community participation to deliver new and updated features, excelling in the areas expressed in
Figure
• Java EE 7 enables developers to deliver HTML5 dynamic scalable applications. New to the
platform, WebSockets reduce response time with low latency bi-directional data exchange while
standard JSON support simplifies data parsing for portable applications. JAX-RS has been
improved to deliver asynchronous, scalable, high performance RESTful Services. And much
more.
• Java EE 7 meets the most demanding enterprise requirements by breaking down batch jobs into
manageable chunks for uninterrupted OLTP performance; easily defines multithreaded
concurrent tasks for improved scalability; and delivers transactional applications with choice and
flexibility.
GlassFish Server
GlassFish is an open-source Jakarta EE platform application server project started by Sun
Microsystems, then sponsored by Oracle Corporation, and now living at the Eclipse
Foundation and supported by Payara, Oracle and Red Hat. [2] The supported version under Oracle
was called Oracle GlassFish Server. GlassFish is free software and was initially dual-
licensed under two free software licences: the Common Development and Distribution
License (CDDL) and the GNU General Public License (GPL) with the Classpath exception.
After having been transferred to Eclipse, GlassFish remained dual-licensed, but the CDDL
license was replaced by the Eclipse Public License (EPL).
GlassFish is the reference implementation of Jakarta EE and as such
supports EJB, JPA, JSF, JMS, RMI, JSP, servlets, etc. This allows developers to create enterprise
applications that are portable and scalable, and that integrate with legacy technologies. Optional
components can also be installed for additional services.
Built on a modular kernel powered by OSGi, GlassFish runs straight on top of the Apache
Felix implementation. It also runs with Equinox OSGi or Knopflerfish OSGi
runtimes. HK2 abstracts the OSGi module system to provide components, which can also be
viewed as services. Such services can be discovered and injected at runtime.
GlassFish is based on source code released by Sun and Oracle
Corporation's TopLink persistence system. It uses a derivative of Apache Tomcat as
the servlet container for serving Web content, with an added component called Grizzly which
uses Java New I/O (NIO) for scalability and speed.
Java EE Servers
A Java EE server is a server application that the implements the Java EE platform APIs and
provides the standard Java EE services. Java EE servers are sometimes called application
servers, because they allow you to serve application data to clients, much like web servers serve
web pages to web browsers.
Java EE servers host several application component types that correspond to the tiers in a multi-
tiered application. The Java EE server provides services to these components in the form of
a container.
Java EE Containers
Java EE containers are the interface between the component and the lower-level functionality
provided by the platform to support that component. The functionality of the container is defined
by the platform, and is different for each component type. Nonetheless, the server allows the
different component types to work together to provide functionality in an enterprise application.
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to 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 API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
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
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Types of Servlet
Servlet Interface
Servlet interface provides commonbehaviorto all the servlets.Servlet interface defines methods
that all servlets must implement.
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.
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 provides response for the incoming
request,ServletResponse response) 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.
Example :- (with Annotation)
Input.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action=" servlet_an" method="get">
Enter 1st No :<input type="text" name="t1"><br>
Enter 2nd No :<input type="text" name="t2"><br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mult" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>
servlet_an.java
package p3;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@WebServlet(name = "servlet_an", urlPatterns = {"/servlet_an"})
@Override
public void init(ServletConfig config) throws ServletException
{
@Override
public ServletConfig getServletConfig()
{
return getServletConfig();
}
@Override
public String getServletInfo()
{
return "";
}
@Override
public void destroy()
{
}
}
Example :- (with Deployment Discriptor)
Input.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="dd" method="get">
Enter 1st No :<input type="text" name="t1"><br>
Enter 2nd No :<input type="text" name="t2"><br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mult" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>
servlet_dd.java
package p3;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@Override
public void init(ServletConfig config) throws ServletException
{
@Override
public ServletConfig getServletConfig()
{
return getServletConfig();
}
@Override
public String getServletInfo()
{
return "";
}
@Override
public void destroy()
{
}
}
web.xml
<servlet>
<servlet-name>servlet_dd</servlet-name>
<servlet-class>p3.servlet_dd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet_dd</servlet-name>
<url-pattern>/dd</url-pattern>
</servlet-mapping>
</web-app>
GenericServlet class
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Input.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="generic_an" method="get">
Enter 1st No :<input type="text" name="t1"><br>
Enter 2nd No :<input type="text" name="t2"><br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mult" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>
generic_an.java
package p2;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
Input.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="dd" method="get">
Enter 1st No :<input type="text" name="t1"><br>
Enter 2nd No :<input type="text" name="t2"><br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mult" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>
package p2;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<servlet-mapping>
<servlet-name>generic_dd</servlet-name>
<url-pattern>/dd</url-pattern>
</servlet-mapping>
</web-app>
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface.
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Input.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="calculator" method="post">
Enter 1st No :<input type="text" name="t1"><br>
Enter 2nd No :<input type="text" name="t2"><br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mult" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>
calculator.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
if(request.getParameter("add")!=null)
{
int e=c+d;
out.println("Addition="+e);
}
if(request.getParameter("sub")!=null)
{
int f=c-d;
out.println("Subtraction="+f);
}
if(request.getParameter("mult")!=null)
{
int g=c*d;
out.println("Multiplication="+g);
}
if(request.getParameter("div")!=null)
{
int h=c/d;
out.println("Division="+h);
}
}catch(Exception e)
{}
}
}
Input.Html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="dd" method="post">
Enter 1st No :<input type="text" name="t1"><br>
Enter 2nd No :<input type="text" name="t2"><br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mult" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>
calculator_dd.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
if(request.getParameter("add")!=null)
{
int e=c+d;
out.println("Addition="+e);
}
if(request.getParameter("sub")!=null)
{
int f=c-d;
out.println("Subtraction="+f);
}
if(request.getParameter("mult")!=null)
{
int g=c*d;
out.println("Multiplication="+g);
}
if(request.getParameter("div")!=null)
{
int h=c/d;
out.println("Division="+h);
}
}catch(Exception e)
{}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<servlet>
<servlet-name>calculator_dd</servlet-name>
<servlet-class>p1.calculator_dd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>calculator_dd</servlet-name>
<url-pattern>/dd</url-pattern>
</servlet-mapping>
</web-app>