SlideShare a Scribd company logo
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

PPTX
Session And Cookies In Servlets - Java
PPT
Servlet ppt by vikas jagtap
PPT
Java servlet life cycle - methods ppt
PPT
Programming Server side with Sevlet
PDF
Servlets
PPT
Web Technologies -- Servlets 4 unit slides
PDF
.NET Core, ASP.NET Core Course, Session 19
PDF
Java Web Programming [9/9] : Web Application Security
Session And Cookies In Servlets - Java
Servlet ppt by vikas jagtap
Java servlet life cycle - methods ppt
Programming Server side with Sevlet
Servlets
Web Technologies -- Servlets 4 unit slides
.NET Core, ASP.NET Core Course, Session 19
Java Web Programming [9/9] : Web Application Security

What's hot (19)

PDF
Lecture 3: Servlets - Session Management
DOCX
Server side programming bt0083
PDF
.NET Core, ASP.NET Core Course, Session 18
PPTX
01 session tracking
PDF
Csajsp Chapter5
ODP
Spring 4 final xtr_presentation
PPTX
Rest with Java EE 6 , Security , Backbone.js
PPTX
Async servers and clients in Rest.li
DOCX
J2EE-assignment
PDF
Advance Java Practical file
PPTX
C# and ASP.NET Code and Data-Access Security
DOCX
Horizontal clustering configuration steps
DOCX
TY.BSc.IT Java QB U4
PDF
11-DWR-and-JQuery
PPS
JSP Error handling
PPT
JEE5 New Features
PDF
quickguide-einnovator-5-springxd
PDF
Java Web Programming [8/9] : JSF and AJAX
PDF
.NET Core, ASP.NET Core Course, Session 14
Lecture 3: Servlets - Session Management
Server side programming bt0083
.NET Core, ASP.NET Core Course, Session 18
01 session tracking
Csajsp Chapter5
Spring 4 final xtr_presentation
Rest with Java EE 6 , Security , Backbone.js
Async servers and clients in Rest.li
J2EE-assignment
Advance Java Practical file
C# and ASP.NET Code and Data-Access Security
Horizontal clustering configuration steps
TY.BSc.IT Java QB U4
11-DWR-and-JQuery
JSP Error handling
JEE5 New Features
quickguide-einnovator-5-springxd
Java Web Programming [8/9] : JSF and AJAX
.NET Core, ASP.NET Core Course, Session 14
Ad

Viewers also liked (7)

PDF
Server-side Swift
PDF
Bt0083 server side programing 2
PPT
Web Aplication Vulnerabilities
PPT
Information Architecture - Tasks & Tools for Web Designers
PPT
Sql injection
PPT
PDF
Server side development using Swift and Vapor
Server-side Swift
Bt0083 server side programing 2
Web Aplication Vulnerabilities
Information Architecture - Tasks & Tools for Web Designers
Sql injection
Server side development using Swift and Vapor
Ad

Similar to Bt0083 server side programing (20)

PPTX
java Servlet technology
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
PPTX
PPT
Servlet
ODP
servlet 2.5 & JSP 2.0
PPTX
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
DOC
Unit5 servlets
PPTX
Server side programming
PPT
Java Servlets
PPTX
Advanced java+JDBC+Servlet
PDF
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
PPTX
AJppt.pptx
PPTX
UNIT-3 Servlet
PPTX
servlets sessions and cookies, jdbc connectivity
PPTX
UNIT - 5.pptx Servlets And Database Connectivity
PPT
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
PPT
Anintroductiontojavawebtechnology 090324184240-phpapp01
java Servlet technology
SERVLETS (2).pptxintroduction to servlet with all servlets
Servlet
servlet 2.5 & JSP 2.0
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Unit5 servlets
Server side programming
Java Servlets
Advanced java+JDBC+Servlet
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
AJppt.pptx
UNIT-3 Servlet
servlets sessions and cookies, jdbc connectivity
UNIT - 5.pptx Servlets And Database Connectivity
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Anintroductiontojavawebtechnology 090324184240-phpapp01

More from Techglyphs (20)

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

Recently uploaded (20)

PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Cell Types and Its function , kingdom of life
PPTX
Cell Structure & Organelles in detailed.
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Business Ethics Teaching Materials for college
PPTX
master seminar digital applications in india
PPTX
Pharma ospi slides which help in ospi learning
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Final Presentation General Medicine 03-08-2024.pptx
Microbial diseases, their pathogenesis and prophylaxis
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Pre independence Education in Inndia.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Cell Types and Its function , kingdom of life
Cell Structure & Organelles in detailed.
Module 4: Burden of Disease Tutorial Slides S2 2025
Business Ethics Teaching Materials for college
master seminar digital applications in india
Pharma ospi slides which help in ospi learning
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Complications of Minimal Access Surgery at WLH
human mycosis Human fungal infections are called human mycosis..pptx

Bt0083 server side programing

  • 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.