SlideShare a Scribd company logo
1 of 17
Download to read offline
1
Server Side Programming
BT0083 part -1
By Milan K Antony
2
1. What is J2EE? Explain.
Java Enterprise Edition (Java EE) is a technology from Sun Microsystems to
build distributed applications which simplifies complexity, allows faster design,
development and deployment of Web applications. It also reduces cost, manages multi-tier
Web application developments.
The capabilities and functionality of each release of J2EE is agreed
on through the Java Community Process (JCP). The platform is then implemented by
application server vendors and producers,such as BEA, IBM, iPlanet, ATG, SilverStream,
and JBOSS. This means that J2EE developers have a choice of product vendors fromwhom
to select, based on quality, support, or ease of use. The ability tosubmit technologies through
the JCP, and the two-way flow that exists between the main Java vendors and the open-
source community ensures
that a constant stream of new ideas helps to move J2EE forward.In this unit, we are going to
study the concepts of Java 2 Enterprise Edition (J2EE), its applications, and architecture. In
addition, we have a look at the standard HTTP protocol used for communication either on a
network or on the Web, and the usage of Web Servers in application development. Java EE
uses multi-tiered, distributed architecture. It provides a standard for developing and
deploying multi-layered and distributed Web applications. Normally, thin-client multi-tiered
applications are hard to write because they involve many lines of intricate code to handle
transaction and state
management, multi-threading, resource pooling, and other complex low-level details
The component-based and platform-independent Java EE architecture makes Java EE
applications easy to write because business logic is organized into reusable components and
3
the Java EE server provides underlying services in the form of a container for every
component type. Web - Tier Architecture Web - Tier allows to divide application in different
layers so that the applications becomes more readable, easy to trouble shoot, improves
performance and interdependency on view, business logic and database.
HTTP
Hyper Text Transfer Protocol (HTTP) is a client-server protocol used for data exchange on
Internet. Http request can be handled by GET, POST, and HEADER etc methods. GET is a
default method.
WebServer
Web server handles only Http protocol whereas Application server provides exposes business
logic for client applications through various protocols.
Every request of application server goes through Web server only. It handles static pages,
images like, GIG, JPG, etc. Web servers are: Apache Tomcat, Microsoft IIS, lighttpd, and
Google GWS etc.
Application Server Application Server serves business logic. It can handle any kinds of
protocol.
Examples: BEA Weblogic, IBM Webshpere, JonAS (Java Open Application
Server), Sun Java System Application Server (Sun Microsystems), Sun GlassFish Enterprise
Server, (Red Hat) JBoss, JRun(Adobe), Apache Geronimo (Apache Software Foundation)
etc.
2. What is Servlet Life Cycle? Explain in detail.
The lifecycle of a Servlet begins when it is loaded into Server memory and ends when the
Servlet is terminated or reloaded. The Servlet interface
4
defines the following three lifecycle methods, called by the Servlet container:
a) public void init(ServletConfig config) throws ServletException
b) public abstract void service (ServletRequest req, ServletResponse
res) throws ServletException, IOException
c) public void destroy()
When we start up a Servlet container, it searches for a set of configuration files, i.e. web.xml
called as Deployment Descriptors (DD) that describes all the web applications. Deployment
Descriptor is one per web application that includes an entry for each of the Servlets it uses.
First of all the Servlet
container creates an instance of the given Servlet class using the method
Class.forName(className).newInstance() and then loads the Servlet in the memory.
The init () method - Servlet Initialization
After instantiation of Servlet, many times, a Servlet needs to perform some kind of initialization
before handling the request, Servlet calls init() method. It
is responsible for performing initialization required by the Servlet, which can include setting up
resources that the Servlet will require to process requests, such as database connections. The
init() will be called only once per Servlet.
Syntax:
public void init(ServletConfig config) throws ServletException The container passes the
object of ServletConfig interface, which contains
all the initialization parameters, declared in deployment descriptor. This is quite important in
order to ensure the reusability of aServlet. For example, if you are going to make a database
connection in the Servlet instead of hard-
coding the username/password and the database URL in the Servlet, you can use the init()
5
method that allows you to specify them in the deployment
descriptor. These values can be changed as needed without affecting the Servlet code.
web.xml having initialized parameter
<init-param>
<param-name>driver</param-name>
<param-value>org.gjt.mm.mysql.Driver</param-value>
</init -param>
<init -param>
<param-name>user</param-name>
<param-value>root</param-value>
</init -param>
<init -param>
<param-name>password</param-name>
<param-value>root</param-value>
</ init -param>
The service() method:
Each incoming service request to the Servlet is handled by service()
method. It accepts two parameters:
ServletRequest: The incoming request stream encapsulated in a ServletRequest object, and
ServletResponse: The outgoing response stream encapsulated in a ServletResponse object.
It is the heart of any Servlet. It may be called simultaneously by the container in different
threads to process many different requests. This method is the only method that a Servlet is
actually required to implement.
Syntax:
6
public void service(ServletRequest request, ServletResponse response) throws
java.io.IOException
The destroy () method The Servlet engine stops a Servlet by invoking the Servlet's destroy()
method. The purpose of the destroy() method is to make sure that any finalization of data,
releasing of resources, closing of database connections,
open files, and network connections and so on, is to be carried out before the Servlet instance is
lost.
3. What are the various methods of HttpServletResponse interface?
The HttpServletResponse provides a number of methods to assist Servlets in setting
HTTP response head ers. This interface allows a Servlet's service
method to manipulate HTTP – protocol specified header information and return data to its
client. When a client sends a request either by Get or Post
method, the Servlet sends a number of header information like accept, accept language,
encoding, content length, host, user agents, cookies, etc
addCookie(Cookie) Adds the specified cookie to the
response. encodeRedirectURL(String) Encodes the specified URL for use in the sendRedirect
method or, if encoding is not needed, returns the
URL unchanged. sendError(int) Sends an error response to the client using the specified status
code and a
message.
sendRedirect(String) Sends a temporary redirect response
to the client using the specified
7
redirect location URL.
setDateHeader(String, long) Adds a field to the response header
with the given name and date-valued
field.
setHeader(String, String) Adds a field to the response header with the given name and value.
setIntHeader(String, int) Adds a field to the response header with the given name and integer
value. setStatus(int) Sets the status code for this response.
4. Explain Exception Handling using RequestDispatcher.
F A RequestDispatcher can be used to receive the requests from the client and forward the same
to any resource such as a servlet, HTML file, or JSP
file on the server. This mechanism can be made use to forward the request to a different
resource whenever an exception is encountered.
try {
result = n1 / n2 ; // might throw exception
} catch(ArithmeticException a)
{
RequestDispatcher rd =
request.getRequestDispatcher("/Arithmetic.html");
rd.forward(request,response);
}
5. What is a Session? What are the various techniques of Session Managements?
Session tracking is a technique that Servlets use to preserve state about a series of requests from
8
the same user, which originates from the same browser across some period of time. A
session is an uninterrupted series of request-response interactions
between a client and a server
There are various techniques of session tracking, they are as follows:
1. Using Cookies
2. Using URL-Rewriting
3. Using Hidden Form Fields
Cookies are pieces of data that web server adds in the client browser and later in the web
server for tracking. Cookies are useful for identifying clients as they return to the server.
Whenever the client requests a page, it sends along with the request any cookies that it was
previously asked to associate with that request. Each
cookie has a name and a value. In Cookies enabled browser each server domain allows to add
up to 20 cookies of upto 4k per cookie.
HttpSession session = request.getSession(true); //Creating session
String id = session.getId(); // getting session ID
// Cookie creation and passing session ID
Cookie cookies = new Cookie (“SessionID”, id);
response.addCookie(cookies); // adding cookie in the browser
Advantages of Cookies
1. Cookies are stored on the client computer & can be read by the server after a request for a
page is posted. Therefore, no server resource is
involved in maintaining the cookie.
2. The cookies are the best way to customize your navigation on Internet.
9
3. The best example of cookies is their usage by advertising companies. They can download a
cookie onto your computer to keep track of your
surfing habits and can then tell you about the products that will be in relevance to your taste.
4. Cookies are non-executable, so they will not spread viruses.
5. Cookies are light weighted, because they are simple text files storing key-value pairs and
consume less memory space.
URL Rewriting
URL Rewriting is a method in which the requested URL is modified to include a session ID.
This is another popular session tracking method used by many developers. URL Rewriting
can be one of the best and quickest ways to improve the usability and maintainability of
your site when user disables cookies from the browser. This method works only with GET
request.
There are 2 methods in the HttpServletResponse for URL rewriting:
1) encodeURL(String url)
The encodeURL() method of the HttpServletResponse interface returns
a URL by including the session ID in it. If the encoding is not required the URL is returned
unchanged. If cookies are supported by the browser, the encodeURL() method returns the
input RL unchanged since the session ID will be persisted as a cookie.
2) encodeRedirectURL(String url)
The encodeRedirectURL() method of the HttpServletResponse
interface, returns a URL by including a session ID in it for use in the sendRedirect()
method. If the encoding is not required, the URL is
returned unchanged. If browser supports cookies, the encodeRedirectURL()
method returns the input URL unchanged, since
10
the session ID will be persisted as a cookie. This method is different from the encodeURL
as this method redirects the request to a different
URL in the same session.
Advantages of URL Re-writing
1. URL Rewriting masks the dynamic URLs with static URLs.
2. Usability.
3. Security: It will make the site more secure as malicious user will not be able to get to know
the structure of the application.
4. Search Engine Visibility.
5. You can avoid Query String and use URL Re-writing to pass on data among various page
calls.
6. It works even if cookies are disabled.
Hidden Form Fields
This is the simplest and most easy way to implement session tracking. The
hidden fields rely upon a feature of HTML to provide session information.These are added to
an HTML form that is not displayed in the client's browser. They are sent back to the server
when the form that contains them is submitted.
1. Hidden fields have no UI representation, and so cannot be changed by the browser user.
2. They are easy to implement and are supported by most browsers.
6. What are the various J2EE technologies?
Java EE includes various technologies like:
 Java API for Web Services (JAX-WS)
 Java API for XML-Based RPC (JAX-RPC)
11
 Java Architecture for XML Binding (JAXB)
 SOAP with Attachments API for Java (SAAJ)
 Streaming API for XML (StAX)
 Web Service Metadata for the Java Platform, Enterprise JavaBeans
(EJB)
 Java EE Connector Architecture (JCA)
 Java Servlet
 Java Server Faces (JSF) etc.
7. What is Servlet? What are the features of 2.5 API? Explain.
various tools available for Server Side programming like CGI, PHP, and so on. This unit
also explains the concept of Servlets, a tool provided by Sun Microsystems to write Server
Side Programming in a client – server or Web based applications
This section will cover the scripting-languages which can run server side. Scripting languages
are interpreted, rather than compiled. They are easier
to write but slow in execution. example are Common Gateway Interface (CGI)Hypertext
Processor (PHP)ColdFusion Active Server Pages (ASP)
A Servlet is a Java application that runs in a Web server or an application server and provides
server-side processing such as accessing a database.
Servlets are protocol and platform independent server side components, written in Java, which
dynamically extend Java-enabled Web Servers. A Servlet, in simple terms, is a Java
program running under a Web server taking a 'request' object as an input and responding
back by a 'response' object. A Java Servlet is an application, which runs in a Servlet
container using a framework for servicing data requests. The javax.servlet and
12
javax.servlet.http packages provide interfaces and classes for writing Servlets. All Servlets
must implement the Servlet interface, which defines the life-cycle methods. When
implementing a generic service, you can use or extend the GenericServlet class provided
with the Java Servlet API. The HttpServlet
class provides methods, such as doGet and doPost, for handling HTTP-specific services.
Support Multi – threading
 Easy context switching between invocations
 Faster to run when loaded
 Share open DB connection using Connection Pooling with successive invocations
 Store state information in static variables
 Share access to state data each time the Servlet is run
 Control concurrent access to shared state
8. What are the differences between sendRedirect and RequestDispatcher?
a. sendRedirect is a client side redirection and RequestDispatcher is server side redirection.
b. sendRedirect uses absolute path and RequestDispatcher uses relative path.
c. sendRedirect is a method of HttpServletRequest and
RequestDispatcher can be implemented by HttpServletRequest as well as ServletContext
by these interfaces When building a new Web application or adding some new pages in the
existed Web application, it is always required to forward the processing of a request to
another servlet, or to include the output of another servlet in the
response. This can be achieved by various methods of servlet redirection
sendRedirect Method
This method redirects response back to the client's browser with status code. The container
13
decides whether it can handle the request; otherwise
the browser will normally interpret this response by initiating a new request to the redirect URL
given in the response. This method works in browser
only. The RequestDispatcher allows the dynamic inclusion of web components either by
including in the current component or by forwarding to another web
component. It takes request from the client and sends them to other resources available on the
se rver. Resources could be any Servlet, HTMl, JSP or other. A RequestDispatcher has two
primary methods:
A. Include: This is for including the response of another program in the current request.
B. Forward: This is forwarding the request of the current program to another one.
RequestDispatcher with ServletContext:
A RequestDispatcher object can be obtained by calling the getRequestDispatcher method of the
ServletContext object. An instance of ServletContext can be obtained by calling the
getServletContext method of the HttpServlet class. Following are the steps of getting
instance of RequestDispatcher.
1. Get a servlet context instance from the servlet instance:
ServletContext sc = this.getServletContext();
2. Get a request dispatcher from the servlet context instance, specifying the page-relative or
application-relative path of the target JSP page as
input to the getRequestDispatcher() method:
RequestDispatcher rd =sc.getRequestDispatcher
("/DemoRedirection");
3. Invoke the include() or forward() method of the request dispatcher, specifying the HTTP
request and response objects as arguments.
14
rd.include(request, response);
OR
rd.forward(request, response);
The ServletRequest.getRequestDispatcher method allows relative paths
javax.servlet.http.HttpServlet.service(HttpServlet.java: that are relative to the path of the
current request (not relative to the root the ServletContext). It is provided in the
ServletRequest interface. The behavior of this method is similar to the method of the same
name in the ServletContext.
ServletContext.getNamedDispatcher(String name)
The ServletContext.getNamedDispatcher method takes a String argument indicating the
NAME of a servlet known to the ServletContext. If a servlet is
found, it is wrapped with a RequestDispatcher object and the object is returned. If no servlet is
associated with the given name, the method must
return null.
9. What are the ways of handling exception? Explain any one in detail.
There are many ways of handling exceptions in a Servlet, which are:
1. Using the web.xml file
2.Using a RequestDispatcher
3. Using sendError() method of HttpServletResponse.
4. Using the Web Application Log
Handling errors can be defined declaratively using the sub tag of <error-page> in web.xml file.
There are two ways in this declaration. A. <error-code> tag of <error-page> If the servlet
chooses to handle the error codes, <error-code> tag that is within <error-page> tag is used
to identify the value.
15
Following is a code snippet that demonstrates handling of Forbidden error 403 in a servlet.
Whenever this exception is encountered, the JSP, Servlet
or HTML mapped in <location> tag is displayed.
A RequestDispatcher can be used to receive the requests from the client and forward the same
to any resource such as a servlet, HTML file, or JSP
file on the server. This mechanism can be made use to forward the request to a different
resource whenever an exception is encountered.
When sendError method is called, the servlet container sends an error page to the browser. .
The string message that can be set in sendError() is ignored if the error code has a mapping file
configured in web.xml. Otherwise it will be displayed in the browser.
The status codes fall into five general categories:
 100-199 Informational.
 200-299 Successful.
 300-399 Redirection.
 400-499 Incomplete.
 500-599 Server Error.
Using the Web Application Log
Servlets can also write their actions and their errors to a log file using the
log() method.
10. What are Cookies? Explain with an example.
Cookies are pieces of data that web server adds in the client browser and later in the
web server for tracking. Cookies are useful for identifying clients as they return to the
server.
16
Whenever the client requests a page, it sends along with the request any cookies that it was
previously asked to associate with that request. Each
cookie has a name and a value. In Cookies enabled browser each server domain allows to add
up to 20 cookies of upto 4k per cookie. To create cookie, first you need to create an instance
of Cookie class using its constructor This constructor allows the user to pass cookie data in
name/value pair. After that to add this cookie in the browser you need to call addCookie
(object-name) method of HttpServletResponse
HttpSession session = request.getSession(true); //Creating session
String id = session.getId(); // getting session ID
// Cookie creation and passing session ID
Cookie cookies = new Cookie (“SessionID”, id);
response.addCookie(cookies); // adding cookie in the browser
getId()
This method gives session id, which is unique for every instance of the browser.
setMaxAge() method
This method specifies the maximum age of cookie.
Setting and Getting Cookie Attributes Before adding the cookie in the response, you can set or
get attributes of the cookie using following methods:
getComment/setComment
Gets/sets a comment associated with this cookie.
getDomain/setDomain
Usually, cookies are returned only to the hostname, which sent them.
Gets/sets specifies the domain to which cookie applies. You can use this method to inform the
browser to return them to other hosts within the same
17
domain. The domain must begin with a dot and must contain at least two dots. A domain
matches only one entry beyond the initial dot. For example,
"abc.net" is valid and matches www.abc.net and upload.abc.net but not www.upload.abc.net.
getMaxAge/setMaxAge
These allows user to set/get maximum time cookies remain in the browser.
If you don't set the cookie will remain only for the current session i.e. Till browser is running.

More Related Content

What's hot

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18aminmesbahi
 
01 session tracking
01   session tracking01   session tracking
01 session trackingdhrubo kayal
 
Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.liKaran Parikh
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical filevarun arora
 
C# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityC# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityDarren Sim
 
Horizontal clustering configuration steps
Horizontal clustering configuration steps Horizontal clustering configuration steps
Horizontal clustering configuration steps TUSHAR VARSHNEY
 
quickguide-einnovator-5-springxd
quickguide-einnovator-5-springxdquickguide-einnovator-5-springxd
quickguide-einnovator-5-springxdjorgesimao71
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14aminmesbahi
 

What's hot (19)

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
 
Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
J2EE-assignment
 J2EE-assignment J2EE-assignment
J2EE-assignment
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
C# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityC# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access Security
 
Horizontal clustering configuration steps
Horizontal clustering configuration steps Horizontal clustering configuration steps
Horizontal clustering configuration steps
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
quickguide-einnovator-5-springxd
quickguide-einnovator-5-springxdquickguide-einnovator-5-springxd
quickguide-einnovator-5-springxd
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
 

Viewers also liked

Server-side Swift
Server-side SwiftServer-side Swift
Server-side SwiftDaijiro Abe
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2Techglyphs
 
Web Aplication Vulnerabilities
Web Aplication Vulnerabilities Web Aplication Vulnerabilities
Web Aplication Vulnerabilities Jbyte
 
Information Architecture - Tasks & Tools for Web Designers
Information Architecture - Tasks & Tools for Web DesignersInformation Architecture - Tasks & Tools for Web Designers
Information Architecture - Tasks & Tools for Web DesignersDennis Deacon
 
Server side development using Swift and Vapor
Server side development using Swift and VaporServer side development using Swift and Vapor
Server side development using Swift and VaporSantex Group
 

Viewers also liked (7)

Server-side Swift
Server-side SwiftServer-side Swift
Server-side Swift
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Web Aplication Vulnerabilities
Web Aplication Vulnerabilities Web Aplication Vulnerabilities
Web Aplication Vulnerabilities
 
Information Architecture - Tasks & Tools for Web Designers
Information Architecture - Tasks & Tools for Web DesignersInformation Architecture - Tasks & Tools for Web Designers
Information Architecture - Tasks & Tools for Web Designers
 
Sql injection
Sql injectionSql injection
Sql injection
 
Web Hacking
Web HackingWeb Hacking
Web Hacking
 
Server side development using Swift and Vapor
Server side development using Swift and VaporServer side development using Swift and Vapor
Server side development using Swift and Vapor
 

Similar to Server Side Programming and Java EE Concepts Explained

java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0megrhi haikel
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
Server side programming
Server side programming Server side programming
Server side programming javed ahmed
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.pptGAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.pptCUO VEERANAN VEERANAN
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01raviIITRoorkee
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletPayal Dungarwal
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 

Similar to Server Side Programming and Java EE Concepts Explained (20)

java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlets
ServletsServlets
Servlets
 
Servlet
ServletServlet
Servlet
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
Servlets
ServletsServlets
Servlets
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Server side programming
Server side programming Server side programming
Server side programming
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Advanced java+JDBC+Servlet
Advanced java+JDBC+ServletAdvanced java+JDBC+Servlet
Advanced java+JDBC+Servlet
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.pptGAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 
Servlet
Servlet Servlet
Servlet
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 

More from Techglyphs

Bt9002 Grid computing 2
Bt9002 Grid computing 2Bt9002 Grid computing 2
Bt9002 Grid computing 2Techglyphs
 
Bt9002 grid computing 1
Bt9002 grid computing 1Bt9002 grid computing 1
Bt9002 grid computing 1Techglyphs
 
Bt8901 objective oriented systems2
Bt8901 objective oriented systems2Bt8901 objective oriented systems2
Bt8901 objective oriented systems2Techglyphs
 
Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)Techglyphs
 
Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)Techglyphs
 
Bt0064 logic design1
Bt0064 logic design1Bt0064 logic design1
Bt0064 logic design1Techglyphs
 
Bt0064 logic design2
Bt0064 logic design2Bt0064 logic design2
Bt0064 logic design2Techglyphs
 
Bt0066 database management system1
Bt0066 database management system1Bt0066 database management system1
Bt0066 database management system1Techglyphs
 
Bt0066 database management system2
Bt0066 database management system2Bt0066 database management system2
Bt0066 database management system2Techglyphs
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Techglyphs
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Techglyphs
 
Bt0068 computer organization and architecture
Bt0068 computer organization and architecture Bt0068 computer organization and architecture
Bt0068 computer organization and architecture Techglyphs
 
Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2Techglyphs
 
Bt0070 operating systems 1
Bt0070 operating systems  1Bt0070 operating systems  1
Bt0070 operating systems 1Techglyphs
 
Bt0070 operating systems 2
Bt0070 operating systems  2Bt0070 operating systems  2
Bt0070 operating systems 2Techglyphs
 
Bt0072 computer networks 1
Bt0072 computer networks  1Bt0072 computer networks  1
Bt0072 computer networks 1Techglyphs
 
Bt0072 computer networks 2
Bt0072 computer networks  2Bt0072 computer networks  2
Bt0072 computer networks 2Techglyphs
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2Techglyphs
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with javaTechglyphs
 
Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Techglyphs
 

More from Techglyphs (20)

Bt9002 Grid computing 2
Bt9002 Grid computing 2Bt9002 Grid computing 2
Bt9002 Grid computing 2
 
Bt9002 grid computing 1
Bt9002 grid computing 1Bt9002 grid computing 1
Bt9002 grid computing 1
 
Bt8901 objective oriented systems2
Bt8901 objective oriented systems2Bt8901 objective oriented systems2
Bt8901 objective oriented systems2
 
Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)
 
Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)
 
Bt0064 logic design1
Bt0064 logic design1Bt0064 logic design1
Bt0064 logic design1
 
Bt0064 logic design2
Bt0064 logic design2Bt0064 logic design2
Bt0064 logic design2
 
Bt0066 database management system1
Bt0066 database management system1Bt0066 database management system1
Bt0066 database management system1
 
Bt0066 database management system2
Bt0066 database management system2Bt0066 database management system2
Bt0066 database management system2
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
Bt0068 computer organization and architecture
Bt0068 computer organization and architecture Bt0068 computer organization and architecture
Bt0068 computer organization and architecture
 
Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2
 
Bt0070 operating systems 1
Bt0070 operating systems  1Bt0070 operating systems  1
Bt0070 operating systems 1
 
Bt0070 operating systems 2
Bt0070 operating systems  2Bt0070 operating systems  2
Bt0070 operating systems 2
 
Bt0072 computer networks 1
Bt0072 computer networks  1Bt0072 computer networks  1
Bt0072 computer networks 1
 
Bt0072 computer networks 2
Bt0072 computer networks  2Bt0072 computer networks  2
Bt0072 computer networks 2
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with java
 
Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1
 

Recently uploaded

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 

Recently uploaded (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 

Server Side Programming and Java EE Concepts Explained

  • 1. 1 Server Side Programming BT0083 part -1 By Milan K Antony
  • 2. 2 1. What is J2EE? Explain. Java Enterprise Edition (Java EE) is a technology from Sun Microsystems to build distributed applications which simplifies complexity, allows faster design, development and deployment of Web applications. It also reduces cost, manages multi-tier Web application developments. The capabilities and functionality of each release of J2EE is agreed on through the Java Community Process (JCP). The platform is then implemented by application server vendors and producers,such as BEA, IBM, iPlanet, ATG, SilverStream, and JBOSS. This means that J2EE developers have a choice of product vendors fromwhom to select, based on quality, support, or ease of use. The ability tosubmit technologies through the JCP, and the two-way flow that exists between the main Java vendors and the open- source community ensures that a constant stream of new ideas helps to move J2EE forward.In this unit, we are going to study the concepts of Java 2 Enterprise Edition (J2EE), its applications, and architecture. In addition, we have a look at the standard HTTP protocol used for communication either on a network or on the Web, and the usage of Web Servers in application development. Java EE uses multi-tiered, distributed architecture. It provides a standard for developing and deploying multi-layered and distributed Web applications. Normally, thin-client multi-tiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multi-threading, resource pooling, and other complex low-level details The component-based and platform-independent Java EE architecture makes Java EE applications easy to write because business logic is organized into reusable components and
  • 3. 3 the Java EE server provides underlying services in the form of a container for every component type. Web - Tier Architecture Web - Tier allows to divide application in different layers so that the applications becomes more readable, easy to trouble shoot, improves performance and interdependency on view, business logic and database. HTTP Hyper Text Transfer Protocol (HTTP) is a client-server protocol used for data exchange on Internet. Http request can be handled by GET, POST, and HEADER etc methods. GET is a default method. WebServer Web server handles only Http protocol whereas Application server provides exposes business logic for client applications through various protocols. Every request of application server goes through Web server only. It handles static pages, images like, GIG, JPG, etc. Web servers are: Apache Tomcat, Microsoft IIS, lighttpd, and Google GWS etc. Application Server Application Server serves business logic. It can handle any kinds of protocol. Examples: BEA Weblogic, IBM Webshpere, JonAS (Java Open Application Server), Sun Java System Application Server (Sun Microsystems), Sun GlassFish Enterprise Server, (Red Hat) JBoss, JRun(Adobe), Apache Geronimo (Apache Software Foundation) etc. 2. What is Servlet Life Cycle? Explain in detail. The lifecycle of a Servlet begins when it is loaded into Server memory and ends when the Servlet is terminated or reloaded. The Servlet interface
  • 4. 4 defines the following three lifecycle methods, called by the Servlet container: a) public void init(ServletConfig config) throws ServletException b) public abstract void service (ServletRequest req, ServletResponse res) throws ServletException, IOException c) public void destroy() When we start up a Servlet container, it searches for a set of configuration files, i.e. web.xml called as Deployment Descriptors (DD) that describes all the web applications. Deployment Descriptor is one per web application that includes an entry for each of the Servlets it uses. First of all the Servlet container creates an instance of the given Servlet class using the method Class.forName(className).newInstance() and then loads the Servlet in the memory. The init () method - Servlet Initialization After instantiation of Servlet, many times, a Servlet needs to perform some kind of initialization before handling the request, Servlet calls init() method. It is responsible for performing initialization required by the Servlet, which can include setting up resources that the Servlet will require to process requests, such as database connections. The init() will be called only once per Servlet. Syntax: public void init(ServletConfig config) throws ServletException The container passes the object of ServletConfig interface, which contains all the initialization parameters, declared in deployment descriptor. This is quite important in order to ensure the reusability of aServlet. For example, if you are going to make a database connection in the Servlet instead of hard- coding the username/password and the database URL in the Servlet, you can use the init()
  • 5. 5 method that allows you to specify them in the deployment descriptor. These values can be changed as needed without affecting the Servlet code. web.xml having initialized parameter <init-param> <param-name>driver</param-name> <param-value>org.gjt.mm.mysql.Driver</param-value> </init -param> <init -param> <param-name>user</param-name> <param-value>root</param-value> </init -param> <init -param> <param-name>password</param-name> <param-value>root</param-value> </ init -param> The service() method: Each incoming service request to the Servlet is handled by service() method. It accepts two parameters: ServletRequest: The incoming request stream encapsulated in a ServletRequest object, and ServletResponse: The outgoing response stream encapsulated in a ServletResponse object. It is the heart of any Servlet. It may be called simultaneously by the container in different threads to process many different requests. This method is the only method that a Servlet is actually required to implement. Syntax:
  • 6. 6 public void service(ServletRequest request, ServletResponse response) throws java.io.IOException The destroy () method The Servlet engine stops a Servlet by invoking the Servlet's destroy() method. The purpose of the destroy() method is to make sure that any finalization of data, releasing of resources, closing of database connections, open files, and network connections and so on, is to be carried out before the Servlet instance is lost. 3. What are the various methods of HttpServletResponse interface? The HttpServletResponse provides a number of methods to assist Servlets in setting HTTP response head ers. This interface allows a Servlet's service method to manipulate HTTP – protocol specified header information and return data to its client. When a client sends a request either by Get or Post method, the Servlet sends a number of header information like accept, accept language, encoding, content length, host, user agents, cookies, etc addCookie(Cookie) Adds the specified cookie to the response. encodeRedirectURL(String) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. sendError(int) Sends an error response to the client using the specified status code and a message. sendRedirect(String) Sends a temporary redirect response to the client using the specified
  • 7. 7 redirect location URL. setDateHeader(String, long) Adds a field to the response header with the given name and date-valued field. setHeader(String, String) Adds a field to the response header with the given name and value. setIntHeader(String, int) Adds a field to the response header with the given name and integer value. setStatus(int) Sets the status code for this response. 4. Explain Exception Handling using RequestDispatcher. F A RequestDispatcher can be used to receive the requests from the client and forward the same to any resource such as a servlet, HTML file, or JSP file on the server. This mechanism can be made use to forward the request to a different resource whenever an exception is encountered. try { result = n1 / n2 ; // might throw exception } catch(ArithmeticException a) { RequestDispatcher rd = request.getRequestDispatcher("/Arithmetic.html"); rd.forward(request,response); } 5. What is a Session? What are the various techniques of Session Managements? Session tracking is a technique that Servlets use to preserve state about a series of requests from
  • 8. 8 the same user, which originates from the same browser across some period of time. A session is an uninterrupted series of request-response interactions between a client and a server There are various techniques of session tracking, they are as follows: 1. Using Cookies 2. Using URL-Rewriting 3. Using Hidden Form Fields Cookies are pieces of data that web server adds in the client browser and later in the web server for tracking. Cookies are useful for identifying clients as they return to the server. Whenever the client requests a page, it sends along with the request any cookies that it was previously asked to associate with that request. Each cookie has a name and a value. In Cookies enabled browser each server domain allows to add up to 20 cookies of upto 4k per cookie. HttpSession session = request.getSession(true); //Creating session String id = session.getId(); // getting session ID // Cookie creation and passing session ID Cookie cookies = new Cookie (“SessionID”, id); response.addCookie(cookies); // adding cookie in the browser Advantages of Cookies 1. Cookies are stored on the client computer & can be read by the server after a request for a page is posted. Therefore, no server resource is involved in maintaining the cookie. 2. The cookies are the best way to customize your navigation on Internet.
  • 9. 9 3. The best example of cookies is their usage by advertising companies. They can download a cookie onto your computer to keep track of your surfing habits and can then tell you about the products that will be in relevance to your taste. 4. Cookies are non-executable, so they will not spread viruses. 5. Cookies are light weighted, because they are simple text files storing key-value pairs and consume less memory space. URL Rewriting URL Rewriting is a method in which the requested URL is modified to include a session ID. This is another popular session tracking method used by many developers. URL Rewriting can be one of the best and quickest ways to improve the usability and maintainability of your site when user disables cookies from the browser. This method works only with GET request. There are 2 methods in the HttpServletResponse for URL rewriting: 1) encodeURL(String url) The encodeURL() method of the HttpServletResponse interface returns a URL by including the session ID in it. If the encoding is not required the URL is returned unchanged. If cookies are supported by the browser, the encodeURL() method returns the input RL unchanged since the session ID will be persisted as a cookie. 2) encodeRedirectURL(String url) The encodeRedirectURL() method of the HttpServletResponse interface, returns a URL by including a session ID in it for use in the sendRedirect() method. If the encoding is not required, the URL is returned unchanged. If browser supports cookies, the encodeRedirectURL() method returns the input URL unchanged, since
  • 10. 10 the session ID will be persisted as a cookie. This method is different from the encodeURL as this method redirects the request to a different URL in the same session. Advantages of URL Re-writing 1. URL Rewriting masks the dynamic URLs with static URLs. 2. Usability. 3. Security: It will make the site more secure as malicious user will not be able to get to know the structure of the application. 4. Search Engine Visibility. 5. You can avoid Query String and use URL Re-writing to pass on data among various page calls. 6. It works even if cookies are disabled. Hidden Form Fields This is the simplest and most easy way to implement session tracking. The hidden fields rely upon a feature of HTML to provide session information.These are added to an HTML form that is not displayed in the client's browser. They are sent back to the server when the form that contains them is submitted. 1. Hidden fields have no UI representation, and so cannot be changed by the browser user. 2. They are easy to implement and are supported by most browsers. 6. What are the various J2EE technologies? Java EE includes various technologies like:  Java API for Web Services (JAX-WS)  Java API for XML-Based RPC (JAX-RPC)
  • 11. 11  Java Architecture for XML Binding (JAXB)  SOAP with Attachments API for Java (SAAJ)  Streaming API for XML (StAX)  Web Service Metadata for the Java Platform, Enterprise JavaBeans (EJB)  Java EE Connector Architecture (JCA)  Java Servlet  Java Server Faces (JSF) etc. 7. What is Servlet? What are the features of 2.5 API? Explain. various tools available for Server Side programming like CGI, PHP, and so on. This unit also explains the concept of Servlets, a tool provided by Sun Microsystems to write Server Side Programming in a client – server or Web based applications This section will cover the scripting-languages which can run server side. Scripting languages are interpreted, rather than compiled. They are easier to write but slow in execution. example are Common Gateway Interface (CGI)Hypertext Processor (PHP)ColdFusion Active Server Pages (ASP) A Servlet is a Java application that runs in a Web server or an application server and provides server-side processing such as accessing a database. Servlets are protocol and platform independent server side components, written in Java, which dynamically extend Java-enabled Web Servers. A Servlet, in simple terms, is a Java program running under a Web server taking a 'request' object as an input and responding back by a 'response' object. A Java Servlet is an application, which runs in a Servlet container using a framework for servicing data requests. The javax.servlet and
  • 12. 12 javax.servlet.http packages provide interfaces and classes for writing Servlets. All Servlets must implement the Servlet interface, which defines the life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services. Support Multi – threading  Easy context switching between invocations  Faster to run when loaded  Share open DB connection using Connection Pooling with successive invocations  Store state information in static variables  Share access to state data each time the Servlet is run  Control concurrent access to shared state 8. What are the differences between sendRedirect and RequestDispatcher? a. sendRedirect is a client side redirection and RequestDispatcher is server side redirection. b. sendRedirect uses absolute path and RequestDispatcher uses relative path. c. sendRedirect is a method of HttpServletRequest and RequestDispatcher can be implemented by HttpServletRequest as well as ServletContext by these interfaces When building a new Web application or adding some new pages in the existed Web application, it is always required to forward the processing of a request to another servlet, or to include the output of another servlet in the response. This can be achieved by various methods of servlet redirection sendRedirect Method This method redirects response back to the client's browser with status code. The container
  • 13. 13 decides whether it can handle the request; otherwise the browser will normally interpret this response by initiating a new request to the redirect URL given in the response. This method works in browser only. The RequestDispatcher allows the dynamic inclusion of web components either by including in the current component or by forwarding to another web component. It takes request from the client and sends them to other resources available on the se rver. Resources could be any Servlet, HTMl, JSP or other. A RequestDispatcher has two primary methods: A. Include: This is for including the response of another program in the current request. B. Forward: This is forwarding the request of the current program to another one. RequestDispatcher with ServletContext: A RequestDispatcher object can be obtained by calling the getRequestDispatcher method of the ServletContext object. An instance of ServletContext can be obtained by calling the getServletContext method of the HttpServlet class. Following are the steps of getting instance of RequestDispatcher. 1. Get a servlet context instance from the servlet instance: ServletContext sc = this.getServletContext(); 2. Get a request dispatcher from the servlet context instance, specifying the page-relative or application-relative path of the target JSP page as input to the getRequestDispatcher() method: RequestDispatcher rd =sc.getRequestDispatcher ("/DemoRedirection"); 3. Invoke the include() or forward() method of the request dispatcher, specifying the HTTP request and response objects as arguments.
  • 14. 14 rd.include(request, response); OR rd.forward(request, response); The ServletRequest.getRequestDispatcher method allows relative paths javax.servlet.http.HttpServlet.service(HttpServlet.java: that are relative to the path of the current request (not relative to the root the ServletContext). It is provided in the ServletRequest interface. The behavior of this method is similar to the method of the same name in the ServletContext. ServletContext.getNamedDispatcher(String name) The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext. If a servlet is found, it is wrapped with a RequestDispatcher object and the object is returned. If no servlet is associated with the given name, the method must return null. 9. What are the ways of handling exception? Explain any one in detail. There are many ways of handling exceptions in a Servlet, which are: 1. Using the web.xml file 2.Using a RequestDispatcher 3. Using sendError() method of HttpServletResponse. 4. Using the Web Application Log Handling errors can be defined declaratively using the sub tag of <error-page> in web.xml file. There are two ways in this declaration. A. <error-code> tag of <error-page> If the servlet chooses to handle the error codes, <error-code> tag that is within <error-page> tag is used to identify the value.
  • 15. 15 Following is a code snippet that demonstrates handling of Forbidden error 403 in a servlet. Whenever this exception is encountered, the JSP, Servlet or HTML mapped in <location> tag is displayed. A RequestDispatcher can be used to receive the requests from the client and forward the same to any resource such as a servlet, HTML file, or JSP file on the server. This mechanism can be made use to forward the request to a different resource whenever an exception is encountered. When sendError method is called, the servlet container sends an error page to the browser. . The string message that can be set in sendError() is ignored if the error code has a mapping file configured in web.xml. Otherwise it will be displayed in the browser. The status codes fall into five general categories:  100-199 Informational.  200-299 Successful.  300-399 Redirection.  400-499 Incomplete.  500-599 Server Error. Using the Web Application Log Servlets can also write their actions and their errors to a log file using the log() method. 10. What are Cookies? Explain with an example. Cookies are pieces of data that web server adds in the client browser and later in the web server for tracking. Cookies are useful for identifying clients as they return to the server.
  • 16. 16 Whenever the client requests a page, it sends along with the request any cookies that it was previously asked to associate with that request. Each cookie has a name and a value. In Cookies enabled browser each server domain allows to add up to 20 cookies of upto 4k per cookie. To create cookie, first you need to create an instance of Cookie class using its constructor This constructor allows the user to pass cookie data in name/value pair. After that to add this cookie in the browser you need to call addCookie (object-name) method of HttpServletResponse HttpSession session = request.getSession(true); //Creating session String id = session.getId(); // getting session ID // Cookie creation and passing session ID Cookie cookies = new Cookie (“SessionID”, id); response.addCookie(cookies); // adding cookie in the browser getId() This method gives session id, which is unique for every instance of the browser. setMaxAge() method This method specifies the maximum age of cookie. Setting and Getting Cookie Attributes Before adding the cookie in the response, you can set or get attributes of the cookie using following methods: getComment/setComment Gets/sets a comment associated with this cookie. getDomain/setDomain Usually, cookies are returned only to the hostname, which sent them. Gets/sets specifies the domain to which cookie applies. You can use this method to inform the browser to return them to other hosts within the same
  • 17. 17 domain. The domain must begin with a dot and must contain at least two dots. A domain matches only one entry beyond the initial dot. For example, "abc.net" is valid and matches www.abc.net and upload.abc.net but not www.upload.abc.net. getMaxAge/setMaxAge These allows user to set/get maximum time cookies remain in the browser. If you don't set the cookie will remain only for the current session i.e. Till browser is running.