0% found this document useful (0 votes)
7 views138 pages

Web Application Development Guide

The document outlines the necessity and components of web applications, including the need for web servers and the development setup for Java web applications using Tomcat. It discusses various web technologies, the distinction between static and dynamic web pages, and the roles of client-side and server-side components. Additionally, it provides insights into servlet containers, application servers, and the lifecycle of web components.

Uploaded by

sg9576908
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views138 pages

Web Application Development Guide

The document outlines the necessity and components of web applications, including the need for web servers and the development setup for Java web applications using Tomcat. It discusses various web technologies, the distinction between static and dynamic web pages, and the roles of client-side and server-side components. Additionally, it provides insights into servlet containers, application servers, and the lifecycle of web components.

Uploaded by

sg9576908
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ByteCode(IT Soluction)

Servlet INDEX
1. Need of Web applications

2. Need of Web Server

3. Web application development setup

4. Tomcat Server Basics

5. Basics of web Server and Servlet Container

6. First Java web application development

7. Proving ServletComp is single instance multiple threads comp

8. Understanding flow of execution of the First App of web app

9. Second App development

10. Html to Servlet communication

11. Welcome page Configuration

12. Form validations

13. Different types of form components

14. Working with Eclipse IDE

15. Working with multiple Hyperlinks

16. Working with Multiple Submit Buttons

17. GET Vs POST

18. Sen/let Life cycle

19. Load-on~stanup

20. Two initil servicel-,-) and 7 doX.\ix (-.-) methods

21. 7 http methods

22. War file creation

23. Web logic

24. Servlet to DB software communication

ByteCode(IT Soluctions) Page 1


ByteCode(IT Soluction)

Need of web applications


The application that is specific to one computer and allows to 1 user at a time to
operate the is called standalone application.

Eg- core java applications.

The data, logic to standalone application are specific to one computer.

The application that contains two layer/component interacting with each other is called two-
tier application.

E.g. JDBC application networking applications.

The data, logics of server application in a two tier application are visible to known client
application of LAN to provide are visibility and accessibility to need to use interact network.
We can‘t run standalone, two tier applications directly in the Internet network. So we need to
develop web application to run in the internet network.

To provide global visibility accessibility to the data & logics of application we need to
develop web application/website and run in the internet.

Internet network look like spiders web so it is called web [Link] web application that
is placed on to the inter network having domain name(like [Link]) is called website.

There are 3 dominating environments to develop website:


a) Java-jee.

b) .Net

c) PHP (Personal Home Page for Hypertext Processing/Pre-process

Use java-jee environment (servlet, jsp technologies) to develop large scale and
complex web application (more then 30 pages).

 User .net environment ([Link] technologies) to develop medium scale website


(more then 10 pages).
 Use PHP to develop small scale websites (less then 10 pages).
 After arrival of jquery/angular js is the industry is preferring to use java-jee
environment in the medium/small scale websites development.
 ln Php/.net based on web application the java web services support will be taken
internally to add complex functionalities to the website.
 Web application is collection of web components having the capability to generate
web pages.

Based on the content there are two types of web gages:


1) Static web pages:
a) Display fixed content for all the requests.

eg: about us page, terms and conditions page, contact us page, and etc...

ByteCode(IT Soluctions) Page 2


ByteCode(IT Soluction)

Dynamic web pages:

The content of web page changes based on the time of request generation or

bases on the input values of request.

eg: live game scores page, Gmail inbox page and etc..

Based on the content of the web gage there are two types of web resource components.

a) Static web components (generates the static web pages)

eg: HTML pages

b) Dynamic web components (generate the dynamic web pages)

eg:. servlet, jsp, [Link], php componets.

 Every web application is collection of multiple web componets and other files like
images, audio/video files, java script files and etc...

Java web .Net web application Php web application


application
Servlet jsp html [Link] html Php html

Prg Prg Prg Prg Prg Prg Prg

Servlet img jsp

Prg img Prg Java script [Link] Java script Php


Prg Prg Prg Prg

Need of web server:


 The execution of standalone application takes place only when we intiate the
execution. .
 The web component of web application will be executed dynamically the moment
they are requested them client(browsers) so we can't think about human involvement
in the execution of web component.
 Web components should be executed automatically and dynamically in automated
environment the moment they are requested from browser. For this automation we
need special software called web server software.

Web server:

It is a special software that listens to client requests continuously ,takes the request from
client, passes the request to appropriate web component, executes the web component
dynamically and sends the output to browser as response in form of web page.

Eg: Tomcat,llS(lntemet information Server), Apache web server(AWS).

ByteCode(IT Soluctions) Page 3


ByteCode(IT Soluction)

Web Application Development SetUp

Machine1 Machine2 Machine3

N N
Web Server
Browser Window
E E
Web application
Dynamic T T
Webpage
W R1 W DB Software
………..
O O
R2
…………
R R

K K

(R1,R2,.... are web components)

With respect to diagram:

 Browser gives request to web application by typing URL in the browser‘ s address bar .
 Web server takes the request and passe the request to appropriate web component.
 Web component process the request and generates the output.
 If needed, web resource component interacts with database software while processing
then request.
 Output generated by the web component goes to web server.
 Web sewer sends the output to browser as response in the form of the web page.

 Based_on the place where the web component executes there are two types of web
components

a) Client side components :-


This web component goes to browser from the web application of web server for
execution when requested.
Eg. HTML components
b) Server side web components:
This web component executes in web server itself when requested.

Eg. Servlet, jsp, Php component and etc...

Note: Decide wheather web component is client side or server side based on the place where
it executes not based on the place where it resides.

Developing web server software is not the responsibility of programmers, vendor companies
will supply them ,but developing web application having web components is the
responsibility of programmers.

We can develop web application either as 2~ tier application (without DB software) or as


ByteCode(IT Soluctions) Page 4
ByteCode(IT Soluction)

3-tier-(With DB software) application. When it is taken as 2-tier application it can be called


as "Thin client- Fat sewer application”. The process of keeping developed web application
in web server is called deployment and removing web application from webserver is called
undeployment.

List of browser software or use| agents.


Internet Explorer  from Microsoft

Netscape navigator from Netscape

Firefox  from Mozilia

Hot java  from Red Hat

Chrome  from Google

Opera from opera soft

Safari from apple

List of client side web technologies (to develop to client-side web


components)
Html from w3c

Java scrip from Netscape/sun ms/oracle corp.

VB script from Microsoft

Jscript  from Microsoft

Ajax combination of multiple technologies.

List of web server software (to manage and execute web applications)
Tomcatfrom apache (java).

Jws sun ms (java)

Lis  from Microsoft

Pws from Microsoft

NFTS  from Netscape

Awsfrom apache (java)

Resin from Resin soft (java)

List of Application server software (to manage and execute web


applications)
Application server= web server + other facilities.

ByteCode(IT Soluctions) Page 5


ByteCode(IT Soluction)

 Web server can be used only for executing web applications. Application server can
be used to execute web applications and other JEE applications like EJB comps and
etc...

Web logic from BEA system[Oracle corp.) '-

Web sphere from IBM

Jboss from RedHat

Glassfish from sun ms/oracle corp.

Oracle l0gAs from oracle corp.

Sun One from sum ms

Note: all application server software are java based.

List of server side web technologies:


Servletfrom Sun ms/Oracle corp (java).

IJSP  from Sun ms/Oracle corp (java).

PHPfrom Apache

SSJS from Netscape

Aspfrom Microsoft

[Link]from Microsoft

Cold Fusion from Adobe.

List of DB software.
Oracle from Oracle corp.

Mysql  from Sun ms

PostgreSQLfrom EnterpriseDB

DB2  from IBM

SQL server  from Microsoft

Note : mangoDB, couchBase ,NOSQL, SqlLite and etc.. are light weight DB software

To develop and execute java web application :


a. Choose any browser software

b. Choose 1 or more client side web technologies to develop client side web components.

c. Choose any DB software‗

ByteCode(IT Soluctions) Page 6


ByteCode(IT Soluction)

d. Choose java based server side web technologies to develop sewer side web comps like

Servlet, jsp.

e. Choose java based web sewer to manage and execute web application like (tomcat)

Note - we must choose web server and server side technologies having the compatibility.

What is Container?

 To execute java application jvm is required


 To execute applet component applet viewer/container required
 To execute Servlet Component Servlet Container is required and similarly to execute
jsp component jsp container is required
 We can call servlet container together as web container.
 Servlet Container, jsp container internally uses IRE/JVM.

 All java based web servers and all application servers provide built-in Servlet
Container, jsp container.
 Container is a software application or software that takes care the whole life cycle of
given resource / component (birth to death] object creation to object destruction).it is
like an aquarium for fishes.

Servlet Container manages the whole life cycle of servlet comps, similarly jsp container
manages the whole life cycle of jsp pages/comps.

Java based web server high level architecture :


Web Server

Security Transaction Logging Others

Web application Web application2

servlet Jsp servlet Jsp

html image html image

Servlet contatiner JSP contatiner

Servlet Servlet Servlet JSP JSP JSP


comp comp comp

The additional services that are configurable or applicable on our application to make our
application more perfect and accurateJRE/JVM
are called middleware services. These are not
minimum logics of application development. These are optional and additional logics of

application.

eg. Security service, Transaction service and etc...

ByteCode(IT Soluctions) Page 7


ByteCode(IT Soluction)

More Information about web server & Servlet Container


Earlier in client- server computing, each application had its own client program and it worked
as a user interface and need to be installed on each user‘s personal computer. Most web
applications use HTML/XHTML that are mostly supported by all the browsers and web
pages are displayed to the client as static documents. A web page can merely displays static
content and it also lets the user navigate through the content, but a web application provides a
more interactive experience.
Any computer running Servlets or JSP needs to have a container. A container is nothing but
a piece of software responsible for loading, executing and unloading the Servlet and JSP.
While Servlet can be used to extend the functionality of any Java- enabled server. They are
mostly used to extend web servers, and are efficient replacement for CGI Scripts. CGI was
one of earliest and most prominent server side dynamic content solutions, so before going
forward it is very important to know the difference between CGI and the Servlets.

Common Gateway Interface (CGI)


The Common Gateway Interface, which is normally referred as CGI, was one of the practical
techniques developed for creating dynamic content. By using the CGI, a web server passes
requests to an external program and after executing the program the content IS sent to the
client as the output. In CGI when a server receives a request it creates a new process to run.

What is java ?
Servlets are server side components that provide a powerful mechanism for developing server
side programs. Servlets provide component-based, platform-independent methods forb
building Web-based applications, without the performance limitations of CGI programs.
Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache
modules), servlets are server as well as platform-independent. This leaves you free to select a
―best of breed‖ strategy for your sewers, platforms, and tools. Using servlets web developers
can create fast and efficient server side application which can run on any servlet enabled web
server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server
side so it does not checks the browser for compatibility. Servlets can access the entire family
of Java API, including the JDBC AP1 to access enterprise databases. Servlets can also access
a library of HTTP-specific calls, receive all the benefits of the mature java language including
portability, performance, reusability, and crash protection. Today servlets are the popular
choice for building interactive web applications. Third-party servlet containers are available
For Apache Web Server, Microsoft HS, and others. Servlet containers are usually the
components of web and application sewers, such as BEA WebLogic Application Server, IBM
WebSphere, Sun java system Web Server, Sun Java System Application Server and others.
Servlets are not designed for a specific protocols. it is different thing that they are most
commonly used with the HTTP protocols Servlets uses the classes in -the 1% packages Javax
servlet and [Link]. Servlets provides a way of creating the sophisticated server side
extensions in a server as they follow the standard framework and use the highly portable java
language.
HTTP Servlet typically Used to

 Provide dynamic content like getting the results of a database query and returning to the
client.
 Process and/or store the data submitted by the HTML
 Manage information about the state of a stateless Http. e.g. an online shopping car manages
request for multiple concurrent customers.

ByteCode(IT Soluctions) Page 8


ByteCode(IT Soluction)

Understanding the Tomcat Server :

Type  java based web server

VGFSIOH  (compatible with jdk1.8+)

Vendor Apache foundation Open source software

Default port no  8080

To download software[Link]

Servlet Container name  Catalina

Jsp container name: jasper

While installing tomcat software choose:

a) <JAVA_HOME>\Jre location

b) Tomcat installation folder

c) Default port no (3030)

d) Admin username, password (admin admin)

To start tomcat server:

a) User<tomcat_home>\bin\[Link] file

To see the home gage of tomcat;

[Link] (url in the browser address bar)

To charge http port number of tomcat after installing tomcat:

Go to <Tomcat__home>\conf\[Link]| file and rnodify port attribute value of first <connector>


tagrestart server

Tomcat installation drivetory structure:


D:\Tomcat9.0(<Tomcat_Home>)

|--->bin
|---->……exe([Link])
|--->conf
|------>*.xml([Link],[Link]…)
|----->logs
|------>*.txt
|------->lib
|------>*.jar(servlet-api jar,[Link], [Link] ,jasper jar..)
|---->webapps
|---->dir1,dir2…
|----->*.war

|------>Work

|------>

|------>temp

ByteCode(IT Soluctions) Page 9


ByteCode(IT Soluction)

We can deploy java web application either in the form of directories dri1, dir2) or in the form war
files in <Torncat_Home>\webapps folder.

ln<Tomcat_home>\lib folder

Servlet [Link]—-—--—-~-> representing servlet apl.

jsp-apl.]ar —----~-->representing jsp api

catalina.jar___..-_..>represents servlet Container

[Link] --——-~~-->represents Jsp Container.

->Since JEE module and its technologies are not installable we need to Use jar files given web server
software to work both the technologies apis (like [Link] ,[Link]).

Servlet API 3.1/4.x.: package are

Javax servlet, [Link], [Link], [Link] and etc...

JSP api 2.4 Package are:

[Link], [Link], [Link] and etc...

Servlet, jsp , ejb, jms and etc... jee module technologies.

Understanding different types of Containers:

Based on the technology that is used to create the containers there are different type of containers like
Servlet Container, jsp container, EJB container and etc...

 ServletContainer is developed based on rules and guidelines Servlet technology.

 JspContainer is developed based on rules and guidelines of jspTechnoiogy,Servlet technology.

EJBContainer is developed based on rules and guidelines of EIB Technology.

Based on the physical location Container there are 3 types of containers:

a) Standalone container:

Here container and web server together comes as single software service

b) In process Container:

=>Here container comes as separate software service inside the web server software -

eg: Servlet Container/jsp container to Tomcat server.

c) Out of process Container:

=>Here container resides outside server software but will be linked with web server software eg:
Servlet Container/jsp container that is linked with IIS server to execute java web applications in IIS.

Responsibilities of web server:


 Listens to client requests continuously by starting demon process.
 Takes the requests and passes the requests to container.
 Provides containers to execute sewer side web comps.
 Gives middleware services.
 Provides environment to deploy, manage and undeploy the web applications.
 Gathers output given by webcornps and sends those outputs to browser as response.

ByteCode(IT Soluctions) Page 10


ByteCode(IT Soluction)

Responsibilities of containers;
 Take the request from Server and passes to appropriate web component.
 Executes server side web component
 Enables the communication between multiple web components.
 Manages the whole life cycle of server-side web components.
 Passes the output of web component to web server.

ReCap on threads
 Thread is a light weight process or sub process.
 Transferring control between two processer two threads is called Control jumping
Context Switching.
 Control jumping between two processes take more time when compare to the control
jumping between two threads of a same process in scheduling.
Context switching between processes take more time, so we can say application gives bad
performance for more number of requests, this indicates application is non-scalable
application.
If application gives good performance irrespective of number of requests that are increased or
decreased then it is called scalable application. -

Understanding Servlet:
Every Servlet Component is a java classes that uses servlet API.
For multiple requests given to Servlet Component the Servlet Container creates 1 object of
Servlet Component class and starts multiple threads on that object.

Process Web Server


Req1
Servlet Container
Browser T1
Web Application

T2
Req2 Servlet
component

T3
Browser
Req3 Object of our
servlet component
class

Since the context switching between threads take less time so we can say these web
applications are scalable. i.e web applications give good performance in all conditions.

Definition of servlet:

ByteCode(IT Soluctions) Page 11


ByteCode(IT Soluction)

 Servlet is JEE module sewer side web technology that can be used to develop
Dynamic web component having the capability to generating Dynamic WebPages.
 Servlet is JEF technology which can be used to enhance the functionalities of web
server or http server or application servers |
 Servlet is jee technology that can be used to develop single instance multiple threads
based server side web components in java web application.
 Servlet is jee technology/specification that provides set of rules and guidelnes for
vendor companies to develop Servlet Container and also provides API for
programmers to develop lava server side web components of web application.

Advantages of Java Servlet


1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
6. Extensibility
7. Inexpensive

Portability:

As we know that the servlet are written in java and follow well known standardized APls so
they are highly portable across operating systems and server implementations. We can
develop a servlet on Windows machine running the tomcat server or any other sewer and
later we can deploy that servlet effortlessly on any other operating system like UNIX server
running on the iPlanet/Netscape application server. So servlet are write once anywhere
(WORA) component.

Powerful:
We can do several things with the servlets which were difficult or even impossible to do with
CGl, for example the servlets can talk directly to the web sewer while the CGI components
can't do. Servlets can share data among each other, they even make the database connection
pools easy to implement they can maintain the session by using the session tracking
mechanism which helps them to maintain information from request to request. it can do many
other things which are dlfflcult to implement in the CGI components.

Efficiency

As compared to CGI the servlets invocation is highly efficient. When the servlets get loaded
in the server, it remains in the sewer‗: memory as a single object instance. However with
servlets there are N threads but only a single copy of the servlets Class. Multiple concurrent
requests are handled by separate threads so we can say that the servlets are highly scalable.

Safety

As servlets are written in java, servlets inherit the strong type safety of java language. Java
automatic garbage collection and a lack of pointers means that servlets are generally safe

ByteCode(IT Soluctions) Page 12


ByteCode(IT Soluction)

from memory management problems. In servlets we can easily handle the errors due to Java's
exception handling mechanism. If any exception occurs then it will throw an exception.

Integration

Servlets are tightly integrated with the sewer. Servlet can use the sewer to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.

Extensibility

The servlets API is designed in such a way that it can be easily extensible. As it stands today,
the servlet APl support Http Servlets, but in later date it can be extended for another type of
servlets.

Inexpensive

There are number of free web sewers available for personal use or for commercial purpose.
Web servers are relatively expensive. So by using the free available web sewers you can add
servlets support to it.

Three Important Resource of Servlet API:


Void init(ServletConfig)
[Link]
Void destroy()
Void services (ServletRequest,ServletResponce)
Implements ServletConfig getServletConfig()
String getServletInfo()

[Link]
Init(ServletConfig)
(Abstract) Init()
…………………
Extends Does not implement service() method

[Link] doXxx(HttpRequest,HttpServletResponce)
protected service
(Abstract) (HttpServletRequest,HttpServletResponce)
public Service(ServletRequest,ServletResponce)
doGet (HttpServletRequest req)
doPost(HttpServletResponce res)

Points

 in java abstract class can not be designed having concrete methods or only abstract
method or mix of both.
 The method of interface will be implemented in the implementation classes.
 The abstract methods of abstract class will be implemented in the sub class and
concrete methods of abstract class will be overridden in the sub class.

ByteCode(IT Soluctions) Page 13


ByteCode(IT Soluction)

Every Servlet Component/components is a java class that uses servlet API. This must
implement

There are 3 approaches to develop servlet components:

Approaches 1

Take a class implements [Link](1) and provide definition for all 5 method.

public class implements [Link](……………)

Approach2 .

Take a class extending from [Link](AC) and provide implementation


for

Service(-,-) methods.

public class TestServIet extends GenericServIet{ l

public void service(ServletRequest req,ServIetResponse res)throws


ServleException,IOExceprion{………..
}}

Note. Not a recommended approach because it does not allow programming to work with
protocol htttp features like enabling auto refresh on webpage

Approach3:

Take a class extending from [Link] and override 1 of the 2 service(~,-)


methods or override 1 of the 7 doXXX(-,-)methods.

Note 4- Recommended approach to use because it allows programmers to use protocol http
features like auto refresh and etc...

 For every request given to our Servlet Component the Servlet Container automatically
calls service (-,-) method. So we place request processing logic and response
generation logic in this service method.
 Servlet Container calls service(-,-) method of our Servlet Component with two
argument called request ,response objects service(-,-) can use request object to take
the input values that are given along with request and it user response objects to
delivery output content to browser as response.

public void service(ServIetRequest req, ServIetResponse res) throws


ServletException,IOException{

--------------

-------

ByteCode(IT Soluctions) Page 14


ByteCode(IT Soluction)

First lava web application development as Servlet Component as the web component

Browser Web server/application server

1 request
Dynamic web page DateApp
2

DateServlet(Servlet)
Display date
5 response
and time
(3)
4

Step 1: create deployment directory structure:


E:\DateApp
WEB-INF
Classes
[Link]
[Link]
[Link] [Link]

 The above directory structure represents the web application that is depioyable in the
server, so it is called deployment directory structure.
 This directory structure is common for all severs. it is designed by sun rns and
followed by all vendor companies who creates web server software.
 This directory structure specifies the arrangement and packing of web comps into web
application.
 WEB-INF/classes folder given to place java classes like Servlet Component.
 We place html/jsp comps out side the WEB-INF folder and [Link] file contains
various configurations like Servlet Component configurations. home page
configurations and etc...
 Providing detail about certain file or webcomp to make underlying Sewer or
Container recognizing that file or component as special component ls called
configurations of file or Component. Such configuration in web application can be
done by using [Link] file. So webxml file is called web application configuration
ifile.Thi5 file contains Servlcl configiiragign, JSP configurations and etc...

Step2: Develop Servlet Component([Link]

E:\DateApp\ WEB-INF\classes\ [Link]


//[Link]

ByteCode(IT Soluctions) Page 15


ByteCode(IT Soluction)

package [Link];
[Link]. ;
Import java. io. *;
importjavautil. ;
public class DateServlet extends GenericServlet
{
Public void service(ServletRequest req,Sen/IetResponse res)throws
ServIetException,IOException
{
// set response content type -
res. setContentType( "text/html ");
//Get PrintWriter object
PrintWriter pw=[Link]();
// write response
Date d=new Dote();
[Link](“<b><i><center> Date and Time is “+d+”</b></i></center>”)
//close stream
[Link]();
}//service(~,-)
}//class
 To make Servlet Component classes visible to Servlet Container for_ instantiation we
need to take our Servlet Component class as public class. Similarly service(-,-)
method should be taken as public method to make that method losable from Servlet
Container.

[Link][”text[htmI");

 Gives instruction to browser through web server to display received output content as
html code bases text document (web page) on browser window.

PrintWriter pw = [Link];

 Response object contains built-in stream PrintWriter(pw).getWriter() method returns


that stream to Servlet Component. This stream points to response object as the
destination object to write the data.
 Stream is continuous flow of data which can have file or object or array as destination
to write data and also to read data.

ByteCode(IT Soluctions) Page 16


ByteCode(IT Soluction)

Response object

PrintWriter
Objectectect

[Link]("<b>heIlo</b>”);

This println(-) writes given message to response object. The response object writes given
message to web server through ServletContainer. Web server writes the given message to
browser window as the web page content.

[Link]();

Closes the stream that is associated with response obiect i.e. does not allow to write further
content‘ to response object usingthgat Stream (commits the resgnsg-3).

Note For every request coming to Servlet Component the % r automatically calls service
(-,-) having request, response object as arguments to process the request.

Step3: Add <Tomcat-Horne>\llb\[Link] file to the CLASSPATH environment


variable.

Variable name: CLASSPATH

Value: D:\Tomcat9.0\|ib\[Link];.

0k(3).

Note servlet-api is not part of jdk, but it is available in <Tomcat_Home>\lib folder . So we


need to add that jar file to CLASSPATH.

Step4: Compile the Servlet Component:

E:\DateApp\WEB-INF\classes>javac -d . [Link]

Step5: Configure component in [Link] file:[Link]:

<web-app>

<servIet>

<serviette-name>date</servlet-name> // (logica name)

<servIet~cIoss>[Link]</servlet-cIass> //(class name)

ByteCode(IT Soluctions) Page 17


ByteCode(IT Soluction)

</servlet>

<servlet-mapplng>

<servlet-name>date</servlet-name>

<urI-pattern>/test1</ urI-pattern > // (url pattern (recognized by url pattern))

</servlet-mapping„;

</web-app>

 Servlet Component configuration is nothing but placing the details of Servlet


Component in [Link] file to make Servlet Container _recognizing the given java
class as Servlet Component.
 Web server reads [Link] file the moment we deploy the web application. So
[Link] file can be called as Deployment Descriptor.
 [Link] contains lot of configuration reated to web application so this files is also
called as web application conflgtiratlon file.
 Servlet Component is identified with url pattern, not with is class name and logical
name

Note  To test whether [Link] file is correct file or not press ctrI+b in edit plus.

Step 1 to 5: development of java web application.

Step6: Start Tomcat server

Use< Tomcat_ Home>\bin\[Link] file

Step7: Deploy the web application

Copy E :\DataApp folder to <T0fl1COl‘_HO|1lE>\W2b¢7PPS folder.

Step8 : Test the web application:

Request URL in browser: [Link]

http: protocol

localhost : hostname and port number

DateApp: web application name or context path

/Test1 url-pattern

Modifying Source code of deployed Servlet Component

The modification done in the source code of deployment Servlct Component will be rellected
only after the recompilation of Servlet Component and reloading of the web application.

For recompilation

<Torncot_Home>\webapps\DataApp\WEB-INF\classes>javac -d . [Link]

ByteCode(IT Soluctions) Page 18


ByteCode(IT Soluction)

For Reloading:

Tomcat home page([Link]

I -----—~>Manager app------>

username; admin

Password; admin  DateApp  reload

Knowing username and password after installation In tomcat server:

 Goto <Tomcot_Home>/con//[Link] file and observe the first <user>tag.


 using URL pattern we can hide servlet Class name, technology name from the visitor
of the websites. This helps to improve the security of the application of the web
application towards getting protection from hacker.
 The modification Hone in [Link] will be recognized by underlying server
automatically because the server internally reloads the web app location.
 [Link] message placed in Servlet Component will be display on server
console(window representing servers demon process as debug message.
 [Link](-)sends the messages to Servlet Component but those messages will be
displayed on browser windows as the web page content.
 Servlet Container uses 0-param constructor while installing our Servlet Class (object
creation)
 So make sure that 0-param constructor is available in our Servlet Component class
directly or indirectly.
 For every request given to Servlet Components the Servlet Container creates 1 thread
and 1 set of request , response objects and these objects will be destroyed
automatically once the request related response goes browser window.

If we give 10 requests to our Servlet component;

a) Servlet _Container creates 1 object cl our Servlet Class.


b) Servlet Container creates 10 threads representing 10 request and all these
threads will act on 1 object of Servlet Cornponent class.
c) Servlet Container creates 10 sets of request, response object for 10 request.

To prove above concept partially the place the ‗following code in the service(-,-) give
multiple Simultaneous request multiple window of same browser of different browser
software.

try{

[Link](40000);

catch(Exception e){

ByteCode(IT Soluctions) Page 19


ByteCode(IT Soluction)

[Link]("<br>our servlet class(DateServlet) object hashcode "+this.


hashCode()) "

[Link]("<br>request object hashcode"+[Link]());

[Link]( "<br>response object hashcode”-[Link]());

[Link]("<br>current thread hashcode "+[Link]());

Note For every object JVM generates one unique identification number called
hashcode and to get that hashcode use hashcode() method of [Link] class.

Web server

Browser (b1) DateApp(Web application)

Req,res objectects
T1 dataServlet

Browser (b2) Servlet


Componet
T2
Req,res object

Req,res objectects
Browser (b3)
T3

Understating flow of execution:

From request arrival response generation with the support of an example application.

If xml documentation satisfied syntax and rules them it is called well-formed document.

If xml documentation satisfied dtx/xsd rules (about tags, attributes) then it is called valid
document

DTD Document Type Definition

XSD: Xrnl Schema Definition

->DTD and XSD are building blocks of XML Document

When web application deployed , the server/container locates web xml file and checks
whether it is well- formed Valid document or not and also reads [Link] file content to

ByteCode(IT Soluctions) Page 20


ByteCode(IT Soluction)

maintain that contain as in-memory meta-data, container uses this in- memory metadata to get
configuration details of [Link] file without opening that file [Link] multiple times.

Understanding flow of execution from request arrival to response generation

With the aid of Example App (partial)

D:\Tomcat 8.0 (e) (h)req,res

|----------->webapps (f)service(-,-){ }
|--------->DateApp (i)
|--------->WEB-INF (f)
|------->Classes (m)
(c) memory MetaDate |----->[Link] (p)
([Link]) [Link] (b) |------>[Link] (q)
date |------->[Link] (k)
|---->/test<-->[Link] (j)

Browser [Link] (d)


Dynamic web page (o)

a)Prograrnmers deploys DateApp web application in Tomcat server

b) Server or Container locates [Link] file and checks whether [Link] file is well-formed ,
valid document or not .

c) creates ln'Memory Meta data having [Link] file content in the memory where Server
runs.

d)End user type request url in browser window to generate request to Servlet Component.

http//localhost:2525/DataAppTest1

e) Based on localliost:i525 of request url the Tomcat web server takes the request.

f) Tomcat server passes the request to DateApp web application based on DateApp of
request url.

Servlet Component can give instructions to browser through web server to display web
page in different formats by specifying the MIME type as the response content type. ‗

MIME: MuItiPurpose Internet Mail Extension.


We can specify this MIME type in [Link](-) method.

Various MIME types are:

 Ms-word: application/msword, |
 ms-excel 2 application/[Link]-excel
 xml : text/xml And etc.. |
 To know MIME type in window operating system we can use regedit tool

ByteCode(IT Soluctions) Page 21


ByteCode(IT Soluction)

Start button—> regedit --> HKEY_CLASSES_ROOT-->chose extension-~~> get MIME


type.

App2: Develop web application having multiple servlet and generating different MIME
types based web pages.

Step1: create deployment directory structurer

E\ MIMEApp „
|----->WEB-INF ,
|----—-->classes
|------>Hlm|Servlet,java
|----->[Link] |----->[Link]
|----->[Link]
|----—>[Link]
|---->[Link]
|----->*class
Step2: Develop all the 4 servlet comps

----------------[Link]——-—----—---

//HtmIServlet java

package [Link];

import [Link].*;

import [Link]. *;

import [Link]. *;

public class HtmlServlet extends HtmlServlet{

public void servlet(HttpServIetRequest req,HttpServIeRsponse res )throws

Servletfxcepfion, IOExceprion

// getPrintWriter

Printwriter pw=[Link]();

// set response content type

[Link]{ "text/htmI");

//write logic to generate output(webpage)

[Link]("<tabIe border='1„>“);

[Link]( "<tr><th>Player</th><th>Role</th></tr>");

pw. printIn ( "<tr><td>Dhoni</td><td>Cuptain</td></tr> ");

[Link]{"<tr><td>$achin</td><td>AIl Raunder</td></tr>");

ByteCode(IT Soluctions) Page 22


ByteCode(IT Soluction)

[Link](”</tabIe>");

//close stream

[Link]();

}//service(-,-)

}//class

-----—--———----—-—-[Link]------------------

//[Link]

package [Link];

import [Link].*;

import ][Link].*;

import [Link]. *;

public class void Servlet extends Http Servlet

public void service(HttpServIetRequest req,HttpServIetResponse res) throws


ServletException,IOException

// gerPrintWriter object

PrintWriter pw=res. getWriter);

// set response content type

[Link]("application/msword");

//write logic to generate output(webpage)

[Link]("<tabIe border='0'>");

[Link]("<tr><th>Player</th><th>RoIe</th></tr>");

[Link]( "<tr><td>Dhoni</td>< td>Captain </td></tr> ");

[Link]"<tr><td>Sachin</td><td>AlI Rounder</td></tr>");

[Link]("</table>"); ;_

//close stream object

[Link]();

)//service(-,-)

ByteCode(IT Soluctions) Page 23


ByteCode(IT Soluction)

)//class

-------------[Link]-------------

package [Link];

import [Link].*;

import [Link].*;

import [Link].*;

public class XmIServlet extends HttpServlet

public void service(HtrpServletRequest req,HttpServIetResponse res)throws


ServletException,IOException

// getPrintWriter object

PrintWriter pw=[Link]();

// set response content type

[Link]("text/xml ");

//write logic to generate output(webpage)

[Link]("<table border ='0'>)";

[Link]("<tr><th>PIayer</m><th>RoIe</th></tr>");

[Link]( "<tr><td>Dhoni</td><td>Captain</td></tr>");

[Link]("<tr><td>Sachin</td><td>All Rounder</td></tr>");

[Link]("</tabIe>");

//close stream object

[Link]();

}//service(~,-)

)//class

--------------------- --[Link]----—------—-----~ ------------- --

//[Link]

package [Link];

import [Link].*;

import [Link].*;

import [Link]. *;

ByteCode(IT Soluctions) Page 24


ByteCode(IT Soluction)

public class ExcelServlet extends HttpServlet

public void service(HttpServletRequest req, HttpServletResponse res)throws

ServletException, IOException

// getPrintWriter object

Prinrwriter pw=[Link]();

// set response content type

[Link]("application/[Link]-excel");

//write Iogic to generate output(webpage)

[Link]("<table border=„0 >");

[Link]("<tr><th>Player<,/th><th>Role</th></tr>");

[Link]("<tr><td>Dhoni</td><td>Captain</td></tr>”;

[Link]("<tr><td>Sachin</td><td>All Rounder</td></tr>”;

[Link](“</table>”);

//close stream objects

[Link]();

}//service(-,-)

}//class

Note:

While developing GenericServlet based component we can ServletRequest, ServletRespons


objects which can't be used work with protocol http features.

Note: while developing HttpServlet based Servlet component we can get HttpServletRequest,
HttpServletResponse object which can be used to work with protocol Http features like ato
refresh of the web page.

Step3: Make sure that [Link] file is added to CLASSPATH environment


variable

Step4: Compile all the above four Servlet Components

E:/MIMEApp/WEB-INF/cIasses>javac –d * java

Step5: Configure all the servlet Components web.xm1

ByteCode(IT Soluctions) Page 25


ByteCode(IT Soluction)

<[Link]>
<web-app>
<servlet>
<servlet-name>htmI </servlet -name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>html</servlet-name>
<url-pattern>/hturl</url-pattern>
</servIer-mapping>

<servlet>
<servlet-name>word</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>word</servlet-name> <servlet>
<url-pattern>/wordurl</url-pattern> <servlet-
</servlet-mapping> name>xml</servlet-
name>
<servlet> <servlet-
<servlet-name>excel</servlet-name> class>[Link]
<servlet-class>[Link]</servlet-class> Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>excel</servlet-name>
<url-pattern>/xlsurl</url-pattern>
</servlet-mapping>
}//service(-,-)
}//class

Note --While developing GenericServlet based servlet component we can at SrvletRequest


ServletResponse objects which can't be used To work with protocol http fetures.

Note: whiIe developing HttpServlet based Servlet component we can get HttpServletRequest,
HttpServletResponse object which can be used to work with protocol features like auto
refresh of the web page.

Step3: Make sure that [Link] file is added to CLASSPATH environment


variable.

Step4: Compile all the above four Servlet Components

E:/MIMEApp/WEB-INF/cIasses>javac —d . *.java

,7 Step5: Configure all the 4 Servlet Components i_r1yveb.xml

<[Link]>
<web-app>

ByteCode(IT Soluctions) Page 26


ByteCode(IT Soluction)

<servlet>
<servlet-name>htmI </servlet -name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>html</servlet-name>
<url-pattern>/hturl</url-pattern>
</servIer-mapping>

<servlet>
<servlet-name>word</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>word</servlet-name>
<url-pattern>/wordurl</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>excel</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>excel</servlet-name>
<url-pattern>/xlsurl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>xml</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xml</servlet-name>
<url-pattern>/xmlurl</url-pattern>
</servlet-mapping>
</web-app>

Step6: Start tomcat server.


Step7: Deploy the web application. -
Step8: Test the application.
Request url: [Link]
[Link]
[Link]
[Link]
Generic Servlet Class give 1 servlet (-,-) method that is:
public void service(ServletRequest [Link] res) throws
ServIetException,IOException

ByteCode(IT Soluctions) Page 27


ByteCode(IT Soluction)

HttpServiet Class gives 2 service(-,-) methods they are:


public void service(ServletRequest [Link] res) throws
ServIetException,IOException
protected void service(ServletRequest [Link] res) throws
ServIetException,IOException
Note—
 While overriding super class method in sub class the method can have either same
Modifier or strong modifier.
 Super class protected method can be overridden in the sub class either with same
protected modifier or with strong public modifier
 When servlet component class extends from HttpServlet then we can override
protected servlet method of HttpServlet Class in a our servlet component ether with
same protected modifier or with strong public modifier.
 We can use html file component of web application to generate static web page Html
files configuration in [Link] not request Html files are placed outside WEB-INF
folder in the deployment directory structure of web application and they are identified
with their file name
 The html code of html file come browser window for executions through html
interpreter so.
Html to Servlet Communication:
Giving request to Servlet Component by directly typing request url in the browser address bar
is quiet complex process, non-technical end user may feel complex overcome this problem
we need to provide GUI to end user having hyperlink and submit for this we need to design
Web pages by using html file and should go for html to servlet communication.
Html files generate static web pages , Servlet comps generate dynamic webpages, So to make
static Webpages talking to Dynamic webpages we need to go for html to servlet
communication.
Html to servlet communication is possible in 3 ways.
1) Using hyperlinks
2) Using form submit buttons
3) Using Java Script.

ByteCode(IT Soluctions) Page 28


ByteCode(IT Soluction)

Html to Servlet communication using hyperlinks


For this use Servlet Component request URL as href attribute value of <a>tag.

Browser Web server


Window [Link]
WishApp

Get wish msg Wish servlet

Dynamic web page (3)

Good morning

WishApp (Create directlyin <Tomcat_Home>\webaaps folder)

|---------->WEB-INF
|-------->classes
|------->[Link]
|----->[Link] |------->[Link]
|------>[Link]
|------->[Link]

If servlet components is designed to servlet in puts from HTML page then we must not
give direct request to servlet component by typing url pattern of servlet comp directly in
the browser address bar.

Example Application: Note GET,POST are request method by or modes used


by browser (form page) to send request to servlet
[Link]
[Link] ,doPost are java methods of servlet
package [Link]; compos process GET,POST modes of request.

import [Link].*;

import [Link].*;

[Link].*;

import [Link]*;

public class WishServlet extends HttpServlet{

ByteCode(IT Soluctions) Page 29


ByteCode(IT Soluction)

public void service (HttpServletRequest req , HttpServletResponse res) throws


ServletException, IOException{

PrintWriter pw=null;

Calendar calendar=null;

int hour=0;

//Genaral Settings

pw = [Link]();

//set content type

[Link](“text/html”);

//Get System Date

calendar = [Link]();

'hour = [Link](Calendar.HOUR_OF_DAY);

//generate the wishmsg

if(n<=12)

[Link]("<h1 style='color:red'>Good Morning</center><hl> “);

else if(h<=17)

[Link](”<h1 style='colar:red'>GoodAfterNoon</center><h1 >" );

else if (h<=20)

[Link]("<h1 style='color:'orange‟>Good Evening</center><h1>");

else

[Link]("<h1 style='colorblack'>Good Night</center><h1>” );

//generate the hyperlink

[Link]("<br>><a href='[Link] );

//close the Stream

[Link]();

//service(-,-)

//class

wé[Link]
<servlet>

ByteCode(IT Soluctions) Page 30


ByteCode(IT Soluction)

<servlet-name>wish</servlet-name>

<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wish</servlet-name>
<url-pattern>/wishurl</url-pattern>
</servlet-mapping>
</web-app>

----------------[Link]-------------
<h1> <center>WishMessage </center> </h1> . ,

<a href = "[Link] wish mess>

Html to servlet communication using form page submit button;

 Hyperlink generated requested cannot carry end-users supplied data along with the
request.
 Form page submitted request can carry end users supplied data along with the request.
 The form page submitted request goes to that Servlet Component whose requested url
is placed in action attribute of <form> tag.
 The form page submitted request carries the values of form component as input values
along with the request. To read these values we can use [Link](-) in
Servlet Component.

Form page can submit request in two modes/methods/methodologies.

a) GET mode:

Can carry limited amount of data along with the request (12kb-8kb)

POST mode:

 Can carry unlimited amount of data along with the request.


 Use doXxx(-,-) in Servlet Component instead of service(-,-) to process different
modes/methods of request coming from client/browser. For example we can use
deGet(-.-) method to process GET mode request and we can use doPost(-,-) method to
process POST mode request coming from client (browser).
 [Link] Class is providing these 7 doXxx(-,-) methods. They are
doGet(-,-),doPost(-,-)doHead(-,-),diDelete(-,-),doTrace(-.-),doOptions(-,-),doPut(-,-).

signature of doXxx(-,-) methods

protected void doXxx(HttpServletRequest req,HttpServletResponse res)throws

ServletException,IOException

Html to servlet communication using submit button.

ByteCode(IT Soluctions) Page 31


ByteCode(IT Soluction)

Browser Window Web Server

[Link] VoterAp
p
Name
VoterServlet
(2)
Age

(3)
Check
(1) (4)
voting

Dynamic web page

...u eligible to
(5)

E:\VoterApp
|----->WEB-INF
|----->classes
|--->[Link] |------>[Link]
|----->[Link]
|------->[Link]
|------->[Link]
|------->[Link]

----------------------------------------[Link]----------------------------------------
<h1><center>checking voting eligibility</center></h1><br>
<form action=”http//localhost:3030/VoterApp/voterurl” method=”post”>
Person name :<input type=”text” name =”name”><br>
Person age : <input type =”number” name=”age”><br>
<input type = “submit” value=”check voting eligibility”>

</form>

Note :When form page is submitted form component names, values will go to Servlet
Component along with the request as request param names, values. To read these values in
Servlet Component we can use [Link](-) method.

[Link]
packuge [Link]
import [Link].*;
import [Link].*;

ByteCode(IT Soluctions) Page 32


ByteCode(IT Soluction)

import [Link].*;
public class VoterServlet extends HttpServlet {
public class Voter doPost(HttpServletRequest req,HttpServletResonce res) throws
ServletException,IOException
PrintWriter pw=null;
Stringr name=nuIl; tage=nuIl
int age=0;
//'general setting
pw= [Link]();
[Link] type(“text/html");
//get request parameter values (form data)
name = [Link]("name");
tage = [Link]("age");
„ age =[Link](age);
//writer request processing logic
if(age>=18)
[Link]("<hl style=„color:green‟> "+name" you are eligible for vote</h1>”);
}
else{
[Link]("<hl style=„color:green‟> "+name" you are not eligible for vote</h1>”);
}//add hyperlink
[Link] (“ <a herf = “[Link]”><img src =‟[Link]‟></a>;
//close stream
[Link]();
}
}//class
----------------------[Link]------------------------------
<servlet>
<servlet-name>voter</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>voter</servlet-name>
<url-pattern>/voterurl</url-pattern>
</servlet-mapping>
</web-app>

Requested url: [Link]

Assignment: Develop a web application that take person name, gender (radio button)
and age value to find weather given person is eligible for marriage for not according to
low?

Qus. What are absolute URL and relative URL?

Ans : if we place multiple details in url to locate resource then it is called absolute url, the
detail are like protocol, hostname , port no , web application name, web resource name and
etc...

eg: [Link]

lf we place any web resource name or its identification name in our application name then it
is called relative url
ByteCode(IT Soluctions) Page 33
ByteCode(IT Soluction)

eg: vote, [Link], VoterApp/voteurl, VoterApp/[Link]

Always prefer working with relative url instead of absolute url because they need not be
changed when web application is moved from one server to another server or one machine to
another machine.

Relative url allow us to develop java application as WODA application (write once deploy
anywhere application).
Eg; <a href =<‖[Link]
|------>relative URL

Eg : <a href =‖wishurl‖>go</a>


|------>relative URL

Q. How can we make Servlet Component as flexible Servlet Component having capability to
process both GET, POST modes /methods/methodologies request?

Approach: Place service(-,-) method in Servlet Component to process the request A public
class VoterServlet extends HttpServlet

public void service (-,-) throws SE,IOE{

-----------------

service (-,-) is can able of processing both GET POST modes of requests given by client, but
it is having the following limitations.

a) 1st service (-,-) gives ServletlRequest, ServletResponse objects which can be used to
WOFK with protocol http features.
b) Doesn‘t provide environment to write separate request processing logic for GET,
POST modes of request because it is a single method.
c) Not Designed based on protocol http standards to process 7 ways mode of request
(GET/POST/PUT/DELET/OPTIONS?TRACE/HEAD).

Note form page/Browser can send only GET and POST mode request.

Approac2:

Version1: when we want to execute same logic for both GET and POST modes of
request.

Override both doGet(-,-) doPost(-,-) and keep request processing logic in one method and call
that method from another method.

eg:
public class VoterServlet extends HttpServlet {
public void doGet(-,-)hrows SE,IOE{
........//request processing logic
}
public void doPost(-,-)throws SE,IOE{
doGet(req,res);
}

ByteCode(IT Soluctions) Page 34


ByteCode(IT Soluction)

}//class

Version2: when we want to execute two different logics for GET , POST modes of requests.
Override both doGet(-,-), doPost(-,-) methods having different request processing logics.

eg:

public class VoterServIet extends HrtpServIet{

public void doGet(-,-)throws SE, IOE{

//request processing logic for GET

public void doPost(-,-)throws SE,IOE{

..............// //request processing logic for GET

Approache3:

Version1: When we want to execute same logic for hath. GET and POST modes of request.
Place request processing logic in a user- defined 'method and call that method from both
doGet(-,-),doPost(-,-) method.

Eg;
public class VoterServlet extends HttpServlet{
public void process(-,-)throws SE,IOE{
…………….//request processing logic
}
public void doPost(-,-)throws SE, IOE {
processes, (req,res);
}
public void doPost(-,-)thr0ws SE,IOE(
processes, (req,res); }

Verson2: When we want to execute separate logics for GET,POST mode of requests.

Take two different user-defined methods having GET and POST modes of request processing

3 logics and call them from doGet(-,-), doPost(-,-) methods respectively.

Eg:

public class VoterServlet extends HttpServler{

public void processGet(-,-)throws SE,IOE{

…………….//GE T mode of request processing logic

ByteCode(IT Soluctions) Page 35


ByteCode(IT Soluction)

public void processPost(-,-)throws SE,IOE{

………..//Post mode of request processing logic

public void doGet(-,-lthrows SE,IOE{

processGet(req,res);

public void doPost(-,-)throws SE, IOE( ,

processPost(req,res);

Conclusion:

We can user either approach2. Approach 3 is more recommended to use

Advantages of working with doXxx(-,-) methods:

 doXxx(-,-) methods are given to process 7 modes of requests given by client


browser).
 These methods are designed based on protocol http standards.
 Gives HttpServletRequest,‗HttpServlelResponse as params to work with protocol http
features.
 We can write separate request processing logics for GET and POST modes of
requests.

Configuring Welcome page/home page:


The first page of the web application that comes autocratically when request is given to the
web application directly is called welcome page or home page of the web application.

We can configure Servlet Component /jsp component/html file as the welcome file in
[Link]

file as shown below


<web-app>
<weIcome-file-list>
<welcome~file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

important points:

When multiple welcome files are configured, the welcome tile will be picked up based on the
order of configuration and the availability in the web application

If no welcome file is configured then ServletContainerr looks to takes either [Link]


[Link] as the default welcome file, if both files are available [Link] gets high
priority.

If explicitly configured welcome files are available along with default welcome files in the
Web application then the explicitly configured welcome file will be taken as welcome file.
ByteCode(IT Soluctions) Page 36
ByteCode(IT Soluction)

If explicitly configured welcome files are not physically available in the web application, but
default welcome files are available in web application then wee application runs without
[Link]

We can Configure Servlet Component as the welcome fil by specifying its. url pattern as the
welcome file.

Eg; DateApp web application:

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
<weIcome-file-list>
<welcome-file>test1</welcome-file>
</welcome-file-list>
</web-app>

Note: Jsp component are recommended as welcome file. We generally take [Link] default
welcome page.

Html to Servlet communication by using javaScript :

=>lf we want to send request to servlet comp directly from the form component without using
hyperlink, submit button then go for html to servlet communication uslngjava sqipt.

=>lava script supports event handling like onsubmit, onchange, onDBclick and etc...

ExampIe App:

[Link] Web Server

(1) CountryApp
country India
(2)
Australia Us Country Servlet

(3)
Dynamic web page (4)

New Delhi

ByteCode(IT Soluctions) Page 37


ByteCode(IT Soluction)

E:\[Link]
|----——>WEB-lNF
|—->[Link] |--- ------- >classes
|------->[Link] l
|------>[Link] |------->[Link]
|------> [Link]

------------------------------[Link]---------------------------
<h1><center>Select Country and Get State</center></h1> '
<form action=”countryurl” method=”post” name=”frm”>
Country :<select name=” country” onChange=”[Link]()”>
<option vaIue="">seIect' a vaIue</option>
<option vaIue=”australia”>Australia</optian>
<option vaIue="india”>india</optian>
<option vaIue="us”>us</optian>
</select> </form>
------------------—CountryServlet.]ava---------------------------
Package [Link];
Import [Link];
Import [Link];
Import [Link];
Import [Link];
Import [Link];
Import [Link];
Import [Link];
public class CountryServlet extends HttpServlet{
@Override
public void doGet(HrtpServletRequest req, HttpServletResponse res) throws
ServletException,IOException {
String srateslndia[]={"AP", "TS", "MH", "MP", "UP");
String UsStates[]=({"CA "LA ", "NY", "CR", "AZ"};
String ausisStates[]={"TMS","BB”,"CBR”)
String country=null;
@ //read form data
country=req. getParameter("country);
//general settings
PrintWriter pw=[Link]();
[Link]("text/htmI");
//get states based on the country that Is selected.
if([Link]( “India ")){
[Link]("states= "+Arrays. toString(statesIndia));
}
else if([Link]("us")){
[Link]("states="+[Link](UsStates));
}
eIse(
[Link]("states="+[Link](ausisStates));
}
pw close();
}
//Override
I

ByteCode(IT Soluctions) Page 38


ByteCode(IT Soluction)

public void doPost(HttpServletRequest req, HttpServlerResponse res} throws


ServletException,IOException {
doGet(req,res);
}
}

Submit

Reset

And etc...

Text box:
In form page:

Name: <input type="text” name =”tname">

In Servlet Component:

String s = [Link](”tname");

Password box:
In form page:

Age<input type="password” name =”tage”>

In Servlet Component:

int age: [Link]([Link]("tage"));

Text area:
In form page:

Address <textarea name =“taddr" rows=30 cols =20>heIlo</textarea>

In Servlet Component:

String address= [Link]("taddr"),'

Radio button:
We never take single radio button we always take multiple radio buttons by grouping them
into single unit, for this we need to give same name to multipule radio buttons. This process
allows to select one radio button at a time form that group.

In form page:

Gender: <input type=‖radio‖ name =‖gender" value ="m">male

<input type=‖radio" name ="gender" value ="f">female

In Servlet Component:

ByteCode(IT Soluctions) Page 39


ByteCode(IT Soluction)

String gender = [Link]("gender‖);

Note:

The Radio button label will not go to server as request parameter value. The value kept an
value attribute (m/f) will go to sever as request parameter value.

Single check box:

In form page

Marital status : <input type=‖checkbox" name =‖rns" value ="married"‘ >Married

In Scrvlet Component:

String ms = [Link](‖ms "1;

Givez "married: when check box us selected, otherwise gives null.

Multiple checkboxes:

In form page:

Hobbies: <input type= ‖checkbox" name =‖hb‖ value ="'roaming‖>travelling

<input type="checkbox‖ name ="hb" value =‖sleeping‖>Meditation

<input type="checkbox" name =‖hb‖ value ="collection">starnp collection

In Servlet Component;

String hobbies[] = [Link]( "hb");

hobbies[] contains 3 values in elements, if all the 3 check boxes are selected.

hobbies[] --->("roaming , sleeping, collection")

Hidden box:

In form page:

<input type="hiddenbox " name ="h1" value ="hello"'>

In Servlet Component:

String s1 = [Link]("'h1");

Select box/combobax/choicebox;

In form page:

Qualification: <select name=”qlfy”>

<option value ="Engg">BE/[Link]</option>

<option value ="arts">BA/MA</option>

ByteCode(IT Soluctions) Page 40


ByteCode(IT Soluction)

<option value ="medical">MBBS</option>

</select>

In Servlet Component:

String qlfy = [Link]("qly‖).

If 1st items selected engg comes to server as req parameter value.

Selected item doesn't come to sever as request param. The value heat value attribute of
selected item comes to server as request param value.

List box:

In form page:

Courses :< select name=”crs" rnultiple>

<option value =”cjava”>core java</option>

<option value =”ajava”>adv java</option> </select>

Allows to select multiple items by holding ctrl key.

In Servlet Component:

String crs[] = [Link](―crs‖);

Gives crs[] wlth (cjava", 'ajava", ' hb"} values when all items are selected.

 A good programmer always design from page as the content html table having labels
in 1st column and from components in 2nd column. This gives easy alignment of cops
in from page by using align attribute of the <table> tag.

E:/FonnApp-AllComps
|--——-> WEB4INF
|----->[Link] |—~----->classes
|-—->[Link]
|-—~--->[Link]
|---->[Link]
|—>[Link]

Example Application:

<h1 Style="color:red> Personal Details </h1>


<form action=”formurl”>
<table border=”1”>
<tr>
<td>Name</td>
<td><input type= "text " name="tname" vaIue=""/></td>
</tr>
<tr><td>Age</td>
<td><input type= "password" name="tage" value="" /> </td>
ByteCode(IT Soluctions) Page 41
ByteCode(IT Soluction)

</tr>
<tr>
<td>Gender</td>
<td>
<input type="radio" name="gen" value="M " checked: "checked" /> Male
<input type= "radio" name="gen" vaIue="F"/>FeMale
</td>
</tr>
<tr>
<td>Address: </td>
<td><textarea name=”taddress” rows=”4” cols=”20”>
enter address
</textarea></td>
</tr>
< tr>
<td>Marital Status</td>
<td><input type="checkbox" name= "tnames " vaIue="married"/> </td></tr>
<tr><td>Quantification</td>
<td>
<select name=”qlfy”>
<option value= “B. Tech">Engg</option>
<option value="MBBS">Medical</option>
< option value= "B.A ">Arts</ option >
</select>
</td>
</tr>
<tr>
<td>Courses:</td>
<td><select name="crs" size="3" multiple=“ multiple ">
<option value="java">JAVA pkg</option>
<option value=".net">.NET pkg</option>
<option value="testing "> Testing pkg</option>
</seIect>
</td>
</tr>
<tr>
<td>Hobies</td>
<td>
<input type="checkbox“ name="hb" vaIue="read" checked/> Reading
<input type: "checkbox" name="hb" value=“srumps "/> Stamp Collection
<input type="checkbox“ name="hb" value="roaming"/> Travelling
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit“ value="submit" />
<input type="reset" value="cancel" />
</td>
</tr>

ByteCode(IT Soluctions) Page 42


ByteCode(IT Soluction)

</tab!e>
</form>
------------------------[Link]-------------------------------------
<servlet>
<servlet -name>abc</servlet-name>
< servlet -class>[Link]</servlet-cIass>
</servlet >
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/formurI</url»partern>
</servlet -mapping>
<welcome-file-list>
<weIcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app

package [Link];

import [Link];

import [Link]:

impart [Link];

import [Link];

import [Link];

import [Link];

public class FormServlet extends HttpServlet {

public void doGet(HttpServlerRequest request, HttpServletResponse response)

throws ServletException, lOExceptian (

String name=null,gender=null,ms=null, addrs=null, qlfy=null,crs=null,hb=null;

Int age=0;

PrintWriter pw=null;

//get PrintWriter object

pw=[Link]‟);

// set response content type

[Link]("text/html");

// read from data

name =request. getParameter("tname");

ByteCode(IT Soluctions) Page 43


ByteCode(IT Soluction)

age =[Link]([Link]("tage”));

gender =[Link]("gen ");

ms=[Link]("ms ");

addrs=[Link]("taddress");

qlfy=[Link]("qlfy”)

crs[]=[Link] ("crs ");

hb[]=[Link]("hb");

// write request processing logic

if(gender. equalsIgnoreCase("M")) ;

{ if(age<=5)

[Link](name+"u r baby boy");

else if(age<=12)

[Link](name+ "u r small boy");

else if(age<=l9)

[Link](name+"u r teenage boy");

else if(age<=35)

[Link](name+"u r young man ");

else if(age<=50);

[Link](name+ "u r middle aged man ");

else

[Link](name+ " u r Budda");

else if([Link]("F"))

if(age<=5)

[Link](name+"u r baby girl");

else if (age<=12)

[Link](name+"u r small girl”);

else if(age<= 19)

[Link](name+"u r teenage girl");

ByteCode(IT Soluctions) Page 44


ByteCode(IT Soluction)

else if(age<=35} '

[Link](name+"u r young woman "),-

else if(age<=50)

[Link](name+“u r middle aged woman”);

[Link](name+" u r old woman");

[Link](“<br>name=”+name);

[Link]("<br>age= "+age);

[Link](“<br>Gender= "+gender);

[Link]("<br>Marital Status= "+ms);

[Link]("<br> Qualification="+qlfy);

[Link]("<br> Hobies"+[Link](crs));

[Link]("<br> Hobies"+[Link](hb));

public void doPast(HtrpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet( request,responsej;

}//class

Procedure to develop above application by eclipse IDE :


Step1: launch eclipse IDE by choosing workspace folder.

Step2: configure tomcat9.x server with eclipse IDE

Widow menu—) preferences-) server-) runtime environment ----->add ---> apache tomcat 9

Tomcat9----) installation ' folder(<tomcat_home---->finish--->ok,

Stpe3: create dynamic web project in eclipse IDE having name form app

File menu--->new------->dynamic web project---->FormAap------>next---->next-----


>generate [Link]--->finish.

The directory structure and Eclipse dynamic projects is not deployment directory structure it
is given only for programmer to add difficult resources.

Eclipse does not use the configured Tomcat server. It use cop of Tomcat in eclipse workplace
folder.

ByteCode(IT Soluctions) Page 45


ByteCode(IT Soluction)

ForrnApp-Allcomps (EDWP)
|---- -->java resources
|--—---—>src
|----->[Link]
|-------->[Link]
|------>web content
|-->[Link]
|--—>WEB-INF „
|--->[Link]

The above directory structure is not deployment directory structure of web application that is
given for programmer to arrange various resources of the web application. When we ask
eclipse IDE to run the project it generates the regular deployment directory structure
internally.

=>Except Checkbox, Listbox form components, the remaining form sends either default
values or empty string values to server as request parameter Values EVEN they are not filled
up or checked/selected but listbox, check box components will send request param values
only when they are selected.

=>While working with eclipse IDE the modification done in any web components of web
application will be reflected to server dynamically, so there need of going for recompilation
and reloading

=>When tomcat server is configured with eclipse , the eclipse IDE gets one copy of tomcat
server into workspace folder of eclipse and uses into tomcat Servleterto deployment and
execute the web application

Sending additional data along with hyperlink generated request

eg:<a href =‖turl"> go</a>

->This hyperlink does not carry data along with the request

eg:<a herf="turl?sno=101&sname=raja‖>go </a>

->This hyperlink carries data along with request.

->Basically hyperlink generated request can't carry data along with request but by appending
query string to the href url we can send data.

ln Servlet Component:

String s1 = [Link]("sna‖);

Srirng s2 = [Link]("sname");

-Q. How to differentiate logic in Servlet Component when multiple hyperlinks are generating
request to single Servlet Component?

Ans: Make multiple hyperlinks_carrying additional request param having same name and
different values and read that request param values in Servlet Component to differentiate the
logics.

ByteCode(IT Soluctions) Page 46


ByteCode(IT Soluction)

Browser
WebServer

[Link]
(1) (2)
LinkApp
Allcountries
?s1=link1
LinkSevlet
All Language
?s1=link2
Sysdate
?s1=link3
(4) (3)
Dynamic web page
(5)

…………………….

………………..

LinkApp
|-------->java resources
|--------->src
|---------->[Link]
|---------->[Link] |-------->[Link]
|--------->WEB-INF
|-------->[Link]
|---------->[Link]

Example Application

[Link]

[Link];

Import [Link];
Import [Link];
Import [Link]
Import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Linkservlet extends HttpSevlet{
//override
public vold doGet(HttpServletRequest req, HrtpServletResponse res)
throws ServletExceptlon, IOException {
ByteCode(IT Soluctions) Page 47
ByteCode(IT Soluction)

PrintWriter pw=nulI;
String link=null;
Locale locales()=null;
//get PrintWriter
pw=[Link]();
//set response content type
[Link]("tex:/htmI");
//read "s1" req param value to know the hyperlink that is clicked
link=[Link]( "s1 ");
if([Link]("link1"))( // all languages
//get all available locales ~
locales[]=[Link]();
far(locale lc:locales){
[Link]([Link]()+"<br>");
}
}//if
else lf([Link]("link2")){
//get all available locales
locales[]=[Link]();
for(Locale lc:locales){
[Link]([Link]()+"<br>");
}//for
}//else

else{
[Link](“Date and Time "+new Date());
//add hyperlink
. [Link]("<a href='[Link] ‟>home</a>");
}//doGet(-,-);
@Override
public void doPost(HttpServletRequest req, HrtpServletResponse res) throws
ServletException, IOException {
doGet(req,res);
}
}//class
[Link]
<web-app >
<display-name>LinksApp</display-name>
<welcome-file~list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>links</servlet-name>
<servlet-cIass>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>links</servlet-name>
ByteCode(IT Soluctions) Page 48
ByteCode(IT Soluction)

<url-pattern>/linkurl</url-pattern>
</servlet-mapping>
</web-app>
[Link]

<h1><center>Choose u r hyperlink</center></h1>

<a href=”linkurl?s1=link1”>all Languages</a><br><br>


<a href=”linkurl?s2=link2”>all countries</a><br><br>
<a href=”linkurl?s3=link3”>Sys date and time</a><br><br>
--->Local names language+countery every [Link] object represent one local

Eg; en- US(enflish as it speaks USA)

fr-FR

de-DE

fr-CA(French as it speaks in CANADA)

Local locales[]=[Link]()

Returns [Link] class object array having all the locales of this world.

Locales[]

Locale
0

Locale 1

Locale 2

Understanding submit buttons

<form action=”………”>
<input type =”submit” name=”s1” value=”send”>
</form>
//sends s1=send on the additianalreq name and param value

<form action=”………”>
<input type =”submit” value=”send”>
</form>

ByteCode(IT Soluctions) Page 49


ByteCode(IT Soluction)

//sends s1=Does not send the caption to server as request parameter value.
Note:

When we take submit buttons with name then the caption of submit goes to web server as
request parameter value otherwise caption will not go to sewer as request parameter valu

Q. How to differentiate logics in the Servlet Component if multiple hypetlink, submit


button are generating request single Servlet Component?

Browser

[Link]
Web server
request
Value1
ProcessApp
Value2
(1)
S1 S1 ProcessServlet
S1 (2)

add sub mul

Sys date Sys props (3)


?s1=link1 ?s1=link2

Dynamic web page


……………..…. responce
………………………….
…….

=>Give same name and different captions to submit buttons and give additional request
param by appending query string to the href url of <a> tag, and use submit button captions
and hyperlink generated additional request param values as the criteria values to differentiate
the logics in servlet comp.

ProoessApp
|-—->java resources
|---->src
|--~-->[Link]|et
|----->web content |—> ProcessServlet.]ava
|--->WEB-INF
|-—>[Link]
|----->[Link]

ByteCode(IT Soluctions) Page 50


ByteCode(IT Soluction)

Example Application

[Link]

<h1><centre> Use Submit or hyperlink to submit the request </center></h1> <br><br>


<form action=”processurl” method=”get”>
Value1: <input type =”text” name=”t1”><br>
Value1: <input type =”text” name=”t2”><br>
<input type=”submit” name=”s1” value=”add”/>
<input type=”submit” name=”s1” value=”sub”/>
<input type=”submit” name=”s1” value=”mul”/><br>
</form>
<a href=”processurl?s1=link”>Sys date</a>&nbsp;&nbsp;&nbsp;
<a href=”processurl?s1=link2”>Sys properties</a>
[Link]

[Link]

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ProcessServlet extends HttpServlet {
@0verride
public void doGet(HttpServletRequest req, HttpServletResponse res)
ServIetException, IOException {
PrintWriter pw=nuIl,-
String comp=null
int val1=0,val2=0;
//get PrintWriter object
pw=[Link]():
//set response content type
res. setContentType( “text/htmI");
//read s1 req param value lo know the component that
// is used to send the request
comp=[Link]("s1 ");
//write logic
if([Link](“link”))//sys date
[Link](Date and time +new Date());
}
else if([Link](“link2")){//for sys props
[Link](“System properties”+[Link]());
}
else if([Link](“add")){//for add button

ByteCode(IT Soluctions) Page 51


ByteCode(IT Soluction)

//read form data


val1=[Link]([Link](“t1”));
val2=[Link]([Link](“t2”));
[Link] t!n( "Addition "+(val1+val2));
}
else lf([Link]("sub")){
//read form data
[Link]("Subtraction"+(vaI1-vaI2));
}
e!se{
//read form data
[Link]( "Multiplication "+(vaI1 “val2))-
//add hyperlink
[Link]("<a href=”[Link]”>home</a>");
}//doGet(-,-)
@0verride
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException,
}//doPost(-,-)
}//class
---------------------- --[Link]------.-----—~
<web-app >
<welcome-file~list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>process</servlet-name>
<servlet-cIass>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> process </servlet-name>
<url-pattern>/ processurl</url-pattern>
</servlet-mapping>
</web-app>

ByteCode(IT Soluctions) Page 52


ByteCode(IT Soluction)

1. GET POST
2. Designed to get data from the
comp of server 1. Desrgned to post/send data to
3. Can carry limited amount of along me comp of the server.
with the request (maxzlkb-8kb) 2. Can carry unlimited amount of
4. Supports caching data Along with the request.
5. Supports Bookmarking 3. Doesn'1suppon caching
6. Allows only ASCil characters 4. Doesn't support bookmarking
(text data) 5. Allows both ASCII
7. Supports to add param values to characterhext), and binary
history data(non-text data).
8. No security because form data 6. Does not support
appears In the address bar along 7. Provide security because the
with the url. form data does not appears in
9. Form data goes ta Server as query the browser address bar and
String appended to the request url doesn't store as history.
10. GET isldempotent. Safe to repeat 8. Form data goes to Server as
same request either usingback requestbody /payload content
button or using refresh button Not a idempotent, not safe
11. It is a default request repeat same
methodology/method. 9. Not a default request
12. Use service(-,-)method/doGet(-,-) method,methodology
method to process the request. 10. Use service(-,-)/doPost(-,-)
13. It is read -only request. method to process the request.
14. To generate GET mode request 11. It rs update request becoz it
use updates Content/data at sr=r\/er
15. Typing url in the browser address ‗.100
bar 12. To generate POST 'mode
16. Using hyperlink to generate request use <form
request action="method-"post">
17. Using <form action="..." > </form>
18. </form> 13. Sutiable for file uploding
19. Using <form action="."
method="GET">
20. </form>
21. Not suitatide for file uploading.
 URL typed in the browser address bar, hyperllnk generates GET
method/methodology/mode requests by default where as form page can generate
either GET or POST ‗ method/methodology/mode request.
 Cache is temporary memory that holds data for temporary [Link] client-server
communlcation the cache at client side holds server supplied data and uses that data
across the multiple same requests and this reduces network round trips between client
and server.

Servlet Life cycle


Life cycle means keeping track of various activities from object birth to object death.
Servlet life cycle means keeping track of all the operations from Servlet Class object creation
to destruction. In human life cycle the following life cycle events will takes place.

ByteCode(IT Soluctions) Page 53


ByteCode(IT Soluction)

Birth ---> naming ---> start of schooling ---> end of schooling —> start of carrier —>
marriage —>end of carrier ----> death.
->servlet container manages the whole servlet life cycle of servlet component raises 3
events as servlet life cycle events
a) Instantiation event
 Raises when Servlet Container creates our Servlet Class object

Request processing event :


 .raises when Servlet Container keeps our Servlet Class object ready to process the
request

Destruction event:
Raises when Servlet Container is about to destroy our Servlet Class object.
 Servlet Container calls 3 life cycle methods on Servlet Class object for 3 life cycle
events to process the events.
a) init(ServletConfig): For instantiation Event : signature public void
init(ServletConfig cg)throws ServletException
b) service(-,-): For request processing Event signature: public void
scrvice(ServletRequest req, ServletResoonse res) throws
ServletException,lOException
c) destroy(): For destruction Event Signature . public void destroy()
Note =>The methods that are called by underlying container automatically are called
container call back methods. We can call servlet life cycle methods also as container call
back methods. Browser

Web-App
url
A1 A5 Web comp

A7 A4

Catch a1, a2

DateServlet class
HtmlServlet
objectect object Servlet Config
Class Object
Servlet
object
Config obj

ByteCode(IT Soluctions) Page 54


ByteCode(IT Soluction)

=>ServletConfig (cg) object is Servlet Container created object on one per our Servlet Class
[Link] Container creates this object and hand overs that object ( to our Servlet Class
object. We can use ServletConfig object to pass information to Servlet Component and to
gather details about our Servlet Component. Servlet contemnor create multiple servlet config
object on the deploy of web app based multiple servlet comp that are configured in [Link]
file are servlet config object for servlet class object based.

Programmer use servlet life cycle methods for two purposes:

a) To place and execute his choice logics in various life cycle events oi Servlet Component

b) To access Servlet Contained' created objects in Servlet Component through the life cycle
method parameters. init(-,-) gives access to ServletConfig and service(-,-) gives access to
ServletRequest,ServletResponce objects.

--> There are two init methods in servlet api (init(), initServletConfig cg)).only
init(ServletConfig cg) life cycle method and init) is not a lite cycle method.

=>Only 1st service(-,-) is life cycle method and 2nd service(-,-), doXxx(-,-) are not life cycle
methods.

init(ServletConfig) is one time execution block of Servlet Component life cycle that executes
for instantiation event, we generally place initialization logic like creating JDBC connection
by overriding this initi(-) method in our Servlet Component.

Service (-,-)is repeatedly execution block of Servlet Component which executes for every
request given to Servlet Component we generally place request processing logic business
logic by overriding this method in our servlet comp. t

destroy () is one time execution block of Servlet Component lire cycle for destruction event.
We generally place uninitialization logic like closing ,!DBC connection by overriding this
method in our Servlet Component.

Pending ->Servlet Life diagram.

What happing when 1st request is given to our Servlet Component

a) Servlet Container creates one set of ServletRequest, ServletResponse objects for current
request.

b) Servlet Container our Servlet Class from WEB~INF/classes folder and instantiates that I
obiect by using 0-param constructor. .

eg: [Link](”[Link]").newslnstance();

c) Servlet Container raises instantiation event and calls init(ServletConfig) method on our
Servlet Class object. Here ServletConfig object will assigned to our Servlet Class object.

d) Servlet Container starts/creates one thread representing current request and raises request
processing event.

e) Servlet Container calls 1st service(-,-) method on our Servlet Class object having
ServletRequest, ServletResponse object as the arguments.
ByteCode(IT Soluctions) Page 55
ByteCode(IT Soluction)

f) service(-,-) sends the generated output to browser through response object ano webServer

g) Destroys the thread that is created for current request.

h) Destroys the ServletRequest, ServletResponse Objects of the current request.

What happens when Servlet Component gets then 1" request from browser?

Servlet Container creates one set of ServletRequest, ServletResponse objects for current
request.

Servlet Container checks the availability of our Servlet Class object.

If not available, perform b to i operations of 1st request.

If available, Servlet Container locates that object and performs e toi steps of 1st request.

Procedure to add new Servlet Component in MlMEApp web application to demonstrate


servlet life cycle .

Step 1: keep MlMEApp web application ready

Step2: create [Link] in WEB-lNF\classes folder of MIMEApp web


application

//[Link]

package [Link];

import [Link].*;

import [Link];

import [Link].*;

import [Link].*;

public class Lc TestServIet extends HttpServlet{

[Link]("LcTestServlet:static block");

public class Lc TestServIet(){

[Link](LcTestServlet:0-poram constructor ”);

Public void init(ServletConfig cg){

System,[Link](LcTestServlet: init(ServletConfig) );

ByteCode(IT Soluctions) Page 56


ByteCode(IT Soluction)

Public void service(ServletRequest req, ServletResponce res)throws


ServletException,IOException{

[Link](“LcTestServlet:service(-,-)‟);

//set response content type

[Link](“text/html”);

//Get Printwriter object , .

PrintWriter pw=[Link]();

// write response

Date d=new Date();

[Link](“<b><i><center> Date and Time is "+d+" </b></I></center>");

//close stream

[Link]();

//service(-,-)

public void destroy(){

[Link]("LcTestServlet:destroy()");

//class

}//destroy()

Step3: compile the Servlet Component.

<Tomcat_home>\webapps\MIMEApp\WEB-INF\classes>javac —d . [Link]

Step4: configure LCTestServlst in [Link] file with logical name "lc" haying url pattern
"/lctest".

[Link]
<web-app>

I<servlet> <servlet-name>Ic</servlet-name>

<servlet~class>[Link]</servlet-class> .

</servlet>

<servlet-mapping> -

<servlet-name>Ic</servlet-name>

<url-pattern>/Ictest</url-pattern>

ByteCode(IT Soluctions) Page 57


ByteCode(IT Soluction)

</servlet-mapping>

Step5- Test the web application

Note: Give multiple requests to LcTestServlet and observe the server console.

=>Servlet Container maintains its own internal logic to load and instantiate our Servlet Class
,so we can't say Servlet Container is using the logic of init(-) method to create our Servlet
Class object.

=>Servlet Container internally uses its own logic and garbage collector to destroy our Servlet
Class object. So we can't say Servlet Container is using the logic of destroy method to destroy
our Servlet class object.

Servlet container integrally maintain logic to create on destroy servlet class object infect
every servlet container come with a separate garbage collector to destroy various object of
our web application so filling the logic inhalation is creating our servlet class object and
falling logic destroy method is destroying our servlet class object is a wrong this container
creates servlet config object first before create our servlet class objects but it assigns servlet
config object is servlet class object while instantiation event is roused by calling init()
method.

ByteCode(IT Soluctions) Page 58


ByteCode(IT Soluction)

Servlet life cycle diagram: First Request

Other than 1st Servlet loading(static block)


requsest

Servlet instantiation(0-
param constructor)

Servlet instantiation
(init(-) method)

response
Service(-,-) request processing

Servlet uninitailization
destroy()

Servlet desinstantition
garbage calector

Servlet class unloding

end

Understanding the <load-on-startup>;

=>When we enable-<load-on-startup> on Servlet the Servlet Container creates our Servlet


Class object either during Server startup or during the deployment of web application this
ByteCode(IT Soluctions) Page 59
ByteCode(IT Soluction)

called pre-instantiation & pre-initialization of servlet.(if load in startup is not enable the
servlet container creates ine servlet comp. class objects when is gets first request where
is lazy/late instantiation.)

<web-app>
<servlet>
<servlet-name>lc</sevlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>lc</sevlet-name>
<url-pattern>/lctest</url-pattern>
</servlet-mapping>
</web-app>

Q. What is the advantage of enabling <load-on-startup> on servlet?


 Ans. if <load-on-startup> is not enabled on servlet, the first request given to sen/let
participates in servlet loading, servlet instantiation servlte initialization and request
processing, whereas the other then first request given to servlet directly participates in
request processing, due to this the response time of 1*‗ request is little bit high when
compare to the response time of other than 1― request. To reduce the response time of
1― request and equalize with other then 1― request we need to make Servlet Container
performing servlet loading, instantiation, initialization either during server startup or
during the deployment of web application, For this we need enable <load-on-startup>
on servlet.
 it is not mandatory to enable <load-on-startup> on every Servlet Component of web
application.
 Enable <load-on-startup> on such Servlet Component which will be requested
immediately after deployment. eg:,Servlet Component giving main menu/home page.

Q. When the Servlet Container creates our Servlet Class object?


if <load-on-statup >is not enabled.

 For the first request given to our Servlet Component


 For the first request given to our servlet after restarting web application/restarting web
server] reloading the web application /redeploying the web application.

if <load-on-startup>is enable.

Either during server startup or during the deployment of web application.

Q. When the Servlet Containers destroy our Servlet Class object?


1. Ans: 1. when the web application is stopped/reloaded/undeploved.
2. when the server is stopped/crashed
3. if our Servlet Class object is continuously idle for long time.
ByteCode(IT Soluctions) Page 60
ByteCode(IT Soluction)

Note:

 Servlet Container does not give any special priority towards destruction our Servlet
Class object even though <load-on-startup> is enabled on it.
 If multiple Servlet Component of a web application are enabled with <load-
Or\~startup> then their order of pre instantiation and pre initialization will be decided
based on the <load-on-startup> priority values
 ~>Hlgh values indicate low priority.
 ->Low values indicated high priority.
 -Ve value will be ignored as <load-on-startup> priority value.

Example

Servlet of web application <load-on-startup> value <load-on-startup> value

Servlet1 10(iv) 5(ii)


Servlet2 5(ii) 0(i)
Servlet3 6(iii) 11(iii)
Servlet4 1(i) 1(ignores)

In Tomcat server taking <load-on-startup> without priority value will generate error.

Enabling <load-on-startup> on servlet with having ve value as the priority value is equal to
not enable <load-on-servlet> on two enable load-on-servlet on multiple servlet with same
priority value the understanding container/servlet decides the order of pre installation
initialization

Q. What happens if we call destroy () method form service(-,-)method.

Ans: The logic of destroy () executes along with service(-,-) method, but destruction event
will not be raised and our Servlet Class object will not. be destroyed.

. ->When life cycle event IS raised, the Servlet Container calls life cycle method, since the
life cycle method is invoked explicitly the container will not raise any life cycle event.

Q1. What happen if we call init() from service method?

Ans: The object of our Servlet Class will not be created for every request, but logic of initl]
method executes along with service(-,-) method. Init () destroy() method does not logics of
servlet instantiation respective these logics are actually available servlet container

Note: when Servlet Container calls servlet life cycle method we can say life cycle event is
raised. If programmer calls same life cycle method manually then Servlet Container does not
raise any life cycle event.

Q. What happens if main(-) method is placed in our Servlet Component?

ByteCode(IT Soluctions) Page 61


ByteCode(IT Soluction)

Ans: Servlet Container executes our Servlet Component through life cycle methods. Since
main(-) method is not a life cycle method oi our Servlet Component it will not be executed as
Servlet life cycle method.

Q. How Servlet Component is executing without main(-) method?

Ans The stand alone application begins the execution by calling the main l-l method. Since
Servlet Component is not a standalone application and It is a web component of web
application, So there is no need of having main(-) method .

Ans2: Servlet Container executes our Servlet Component through life cycle method, since
main (-) is not the life cycle method of Servlet Component ,so there is no need of placing
main(-) in our Servlet Component.

Ans3: If any lava application wants to create certain class obiect and wants to call method on
that object then there is no need of having main(-) method in that class.

Servlet Container is continuously running software application/service which creates


our Servlet Class object and calls various life cycle methods on the object. So there l5 no
need of having main (-) method in our Servlet Component

ServletConfig ODJECT IS useful lo know information about current Servlet logical name. it
is also useful to gather additional information given in [Link] file along with configuration
of Servlet Component

GET

Default request method, designed to get data from server by generating request without data
or with limited amount of data (max. of2kb~8kb).

POST:

Can send request with unlimited amount of data and gathers data from server as response.
The response of GET based or POST based request contains everything including response
body like response headers, miscellaneous information, etc...

HEAD:

Same as GET but the HEAD based request related response does not contain response body.
HEAD based requests are useful to test whether web component is present or not. Note: Even
though there are 7 request methods the most regularly used request methods in real world
while developing iava websites are GET, POST

PUT

This is capable of allowing client to place new file or web component in already deployed
web application of web server. in real projects after placing websites in the web server of
ISP(internet) Service Providers) machine we use FTP[File Transfer Protocol) application
from our computers to maintain that website. This FTP application uses PUT method request
to add new file or new web resource component in that ISP machine website.

DELETE:

ByteCode(IT Soluctions) Page 62


ByteCode(IT Soluction)

Allows client to send a request having the capability to delete hie or web component of web
application in the server. FTP application uses this delete method to delete web page or
document or anything from the hosted web application ofthe ISP machine based web server.

TRACE:

This trace method request returns all the debugging messages and Flow of execution details
regarding the request and response of certain web components.

OPTIONS:

The options method based request given to web resource component determines using which
Httprequest menthods that this servlet can be request from client.

For example:

if our Servlet Component overrides doGet(-.-) method as shown beiotiv then the OPTIONS
method based request given to the Serviet Component returns the following response

Allow HEAD. GET. OPTlONS, TRACE

Eg: public class TestSerllet extends HttpServlet


{
Public void doGet(HttpServletRequest req ,HttpServletResonce res)throws
ServletException,IOException{
-----
…….
}
}
use synchronization concepts.

Local variables of service (-,-) are thread safe variable by default because every thread its
copy local variable.
public class TestServlet extends HttpServlet {
Int a; Object or variable is thread safe with it
public void service (-,-)/doXxx(-,-) throws SE,IOE always one thread at a time or when it
Int b; becomes septet copy of all thread
………….
}
}

ByteCode(IT Soluctions) Page 63


ByteCode(IT Soluction)

Request 1
Browser 1 T1
(b)

Request 2 (a)
T2
Browser 2
(b)

Request 3
T3
Browser 3 (b)
TestServlet object

The thread than are representing requests will always execute service(-,-) method. Once this
Service (-,-) method execution is completed that thread will be destroyed. In ordinary java
class servlet instance variable are not thread safe where as local variable are thread safe

Servlet to DB software communication:

->To save thé inputs coming to Servlet Component lfl DB software or to save the result
generated by Servlet Component in DB software or to got aha inputs from DB Software to
Servlet Component we need to go for servlet to DB communication".

cg: Email id registration. Login application and etc..

->For Servlet to DB software communication we need to place JDBC code in Servlet


Component.

There are 4 approaches to place JDBC code in servlet component.

Approach 1:

 Create JDBC connections in the init().


 Use JDBC connections in the Service (-,-)/doXxx(-,-).
 Close JDBC connections in the destroy method

Note :

Here JDBC connections (con) must be taken as instance variable of Servlet Component class

Conclusion.

In small scale java application use! Approach l and in medium, large scale java web
applications either approach3 or approach4.

ByteCode(IT Soluctions) Page 64


ByteCode(IT Soluction)

Servlet to DB software communication using Approach1:

Browser DBApp
[Link]

EmpNo
: DBServlet
(1)req
Details
(2)

(4)resp

(3)
No………….
Name………….
Address……………

Oracle DB Software

DBApp
|---->java resources
|----->[Link]
|------->web content |----->[Link]
|------->WEB-INF
|------>[Link]
|------>lib
|------>[Link] Add for servlet component
|------>[Link] smooth execution after
compilation code

Standalone java application will be compile and executed from command .so if application
user any third party api (like oracle thin driver) so we need to add third party api related jar
file (like [Link]) only in the CLASSPATH.

=>lf java Servlet uses third party api then we need to add that third party api related jar file to
CLASSPATB and also to WEB-lNF/lib folder to web application.

ByteCode(IT Soluctions) Page 65


ByteCode(IT Soluction)

=>Jar file added to CLASSPATH will be used by the compiler to recognize the third party
api during the compilation of Servlet component, similarly the jar file added to WEB-INF/lib
folder will be used by Servlet Container to recognize and use third party API during the
execution of Servlet Component.

Example Application:

—---—-—---—-[Link] ----- - -------—~ -


<form action= "dburl " method="post">
Employee no." <input type =”text“ name-="teno”><br>
<input tvpe=“submit" value=”GetDetails">
</form>
-----------------[Link]----------------
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup> 1</load-on-startup>
</servlet>
<servlet-mapping> „
<servlet-name>abc</servlet-name>
<url-partem>/dburl<url-pattern>
<servlet-mapping>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</web-app>
-—----——————————-—-~-[Link]-~-------—---------------
//DBServlet
package [Link];
import [Link].*;
[Link] .http.*;
import [Link].*;
import [Link].*;
public class DBServlet extends HttpServlet
{
Connection con;
PreparedSatement ps;
public viod init(){
try{
//reglstr JDBC driver
[Link]("[Link]”);
con=DriverManagér.gétConnection("JDBC:oracle:thin:@localhost:1521:xe”,scott”,tige
r”);
//create JDBC PreparedStatement object
ps=[Link](“seIect empno,ename,job,sal form emp where empno=?”);
)//try
catch(Exception e)

ByteCode(IT Soluctions) Page 66


ByteCode(IT Soluction)

{
[Link]();
}
}//init()
public void doGet{HttpServletRequest req,HttpServletResponcse res )throws
ServletException,IOException {
trv {
//General Setting
PrintWriter pw =[Link]();
[Link](“text/html”);
//read from data
int no=[Link]([Link](“teno”));
//set param value to SQL Query
[Link](1,no);
//excute the SQL Query
ResultSet rs=[Link]();
//process the ResultSet
if([Link]())
{
[Link](“<br> Employe no”+[Link](1));
[Link](“<br> Employe no”+[Link](2));
[Link](“<br> Employe no”+[Link](3));
[Link](“<br> Employe no”+[Link](4));
}// if

else
{
[Link](“<br> No Employee Found “);
}
}//try
Catch(Exception e)
{ [Link]();
}
}//doGet(-,-)
Public void doPost(HttpservletRequest req,HttpServletResponce res)throws
ServletException,IOExceptin
{
doGet{req res);
}//doPost(-,-)
public void destroy()(
//close JDBC objects
try{
if(ps!=null)
[Link]();
}//try
catch(Exception e)
[Link]();
ByteCode(IT Soluctions) Page 67
ByteCode(IT Soluction)

trv{
if{con!=nuIl)
[Link]();
//try
catch(Exception e)
e. printStackTrace();

}//destroy()
)//class
//>javac -d . [Link]
Q. Can we place on parameterized constructor in our Servlet Class?
Ans: no, not possible.

Serviet Container creates our Servlet Class object by using 0-param constructor.

If parameterized constructor is placed in our Servlet Class, then 0-param constructor


will not be generated as default constructor by java compiler, so Servlet Container fails to
instantiate our Servlet Class. This indicates we can't place only parameterized constructor in
our Servlet Class.

 Servlet compilation takes place from command prompt and execution takes place in
Servlet Container. Since the Servlet Container can't use the jar files added to
CLASSPATH environment variable of my computer properties, we add jar files to
WEB-INF/lib folder of every web application's directory structure to make the Servlet
Container recognizing and using 3" party api.
 In a server if multiple web applications are using same third party apilliite oracle thin
driver) then we can place that api related jar file directly in server library folder
instead of placing in WEB-INF\lib folder of every web application.

Server Server library folder

Tomcat <Tomcar_home>\lib folder

weblogic <weblogic_home>\user_project

\domoins\<domain name>\lib
folder

Glashfish <Glassfish_horne>\dornian

\<domain nome>\lib\ext folder

 Application based on Servlet configuration done in [Link] file


 ServletContainer destroys this object right after our Servlet class object
destruction

ByteCode(IT Soluctions) Page 68


ByteCode(IT Soluction)

 it is the object of Servlet Container supplied java class that implements


[Link](l).
 it lS useful to pass additional information Servlet and to ether information
about servlet component Servlet container driver our servlet config object to
our servlet class object through servlet installation process
 Can be used to gather init param values from [Link] file to our Servlet
component
 Can be used to access ServletContext object

ServletContext object
 lt is one per web application .so it is also called Global memory of web
application.
 This object is visible and accessible in all the servlet/jsp components of the
web application.
 Servlet Container creates this object either during Server startup or during the
deployment of web application.
 Servlet Container destroys this object when the web application is
stopped/reloaded/undeployed.
 it is the object of ServletContainer supplied java class that implements
[Link]|etContext(I).

We can use Servlet Context object


 To read global init param/context param values from [Link] to our Servlet
component.
 To write message to log files.
 To get Server information and servlet API version.
 To get path of certain resource of Server machine file system.
 To get inputStream pointing to certain resource.
 To know the MIME type of certain file belonging to the web application.
 To get the context path name of the web application
 To get path of deployed web application from server.

To perform dynamic request response of web components like servlet filter and
etc (servlet 3.0)

Q. In a web server total 10 web applications deployed in that 7 web applications


are in running mode and 3 web applications are in stopped mode. Can u tell me how
many ServletContext objects are currently available?

Ans: 10-3 = 7.

Q. In a web application total 10 Servlet Components are available in that 3


Servlet Components are already requested and another 3 Servlet Components are
enabled with <load-on-startup>.Can u tell me how many ServletConfig objects are
currently available.

Ans: 10

ByteCode(IT Soluctions) Page 69


ByteCode(IT Soluction)

ServletContainer create Servlet config object before one done object and assign to own
Servlet class object through initialization .

Note
 Our Servlet Class object,request object,response object,ServIetConfig
object,ServletContext object are ServletContainer created objects. So we can not
create those objects, but we can access.

Those objects to our Servlet Component from ServletContianer.

 To access request,response objects use service(-,-)/doXxx(-,-) method parameters


 To access our Servlet Class object use "this" operator/keyword

Different ways accessing ServletConflg object,

a] Through Init(—) method param.

public void=int(ServletConfrg cg){

//use cg

b) Using getServletConflg) method of GenericServlet (AC)(good approach)

ServletConfig cg = getServletConfig();

Diffrent ways of accessing ServletContext object.

A) ServletConfig cg = getServletConflg():

ServletContext sc= [Link]();

B) ServletContext sc =getServletContext(); //internal uses (a)

c) ServletContext sc = [Link](); //From servlet api 3.x

Servlet-DB software communication (Using Init param values}

The standard principle of software industry is don't hard code any values in our
application that are changeable in future. It is recommended to pass such values to
application from outside the application.

In order to get n0n~technica| inputs from end-user(client side) to Servlet comp like name,age.
address use request parameters through request object. in order to get technical inputs to
Servlet Component through [Link](from Server side by programmer) file we can use init
parameter values. To get these values in our Servlet comp we can use ServletConfig object
(getting JDBC properties). ' -

Driver class name, url, DBuser, DBpwd, are called JDBC properties. In order to get
those values from [Link] file as init parameters values we need ServletConfig object This
helps to make JDBC code of our Servlet Component as flexible code to modify.

Examgle Application:

ByteCode(IT Soluctions) Page 70


ByteCode(IT Soluction)

[Link]
<form action="dburI" method=“ger“>
Employee no: <input type="text" name="tenu"><br>
<input type="subrnit“ value="getEmpDetails">'
<web-app>
<servlet>
<servlet-name>DF</servlet-name>
<servlet-class>[Link]. DBServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>[Link]</param-value>
</init-param>
<init-param>
<param-name>dburI</param-name>
<param-vaIue>jdbc:oracIe:thin@localhost:1521:xel</param-vaIue>
</init-param>
<init-param>
<param-name>dbuser</param-name>
<param-value>scott</param-vaIue>
</Init-pamm>
<init-param>
<param-name>dbpwd</param-name>
<pnram-value>tlger</pamm-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DB</servlet-name>
</servler-mapping>
</web-app>
[Link]
//DBServlet. java (show server to DB software communication based on
approach!)
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class [Link] extends HttpServlet {
Connection can;
PreparerdStatement ps:
public void init()
{
try {
//get Access to ServletConfig object
ServletConfig cg=gerServlerComfig();

ByteCode(IT Soluctions) Page 71


ByteCode(IT Soluction)

a
// read init param values from [Link]
String s1=[Link]("driver");
String s2=[Link]("dburl");
String s3=[Link]( "dbuser");
String s4=[Link]("dbpwd");
// create JDBC con object
[Link](s1);
con=[Link]{s2,s3,s4);
// create JDBC PreparedStarement object.....
ps=[Link]("select ename,saI from emp where empno=?");
//try
catch(Exception e)
{
[Link]();
}
}//init
public void d0Get(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
// read form data from form page
int no=[Link]([Link]( “teno” ));
//get PrintWriter object
PrintWriter pw=[Link]();
// set response content type
[Link]("text/html);
// write JDBC code.....
//set value to parameter of the qry
[Link](1,no);
// execute the query
ResultSet rs=[Link]();
//process ResultSet object and display emp details....
if([Link]())
{
[Link](”<br><b><i> Emp name rs; </i></b>"+[Link](1));
[Link]("<br><b><i> Emp Salary is: </i></b>"+[Link](2));
}//if
//close ResultSet object
[Link]();
//close stream object
[Link]();
}//try
catch(Exception e){
[Link]();
}
)//doGet(-,-)
public void doPos t(HttpServletRequest req,HtrpServletResponse res)throws
ServletException,IOException
ByteCode(IT Soluctions) Page 72
ByteCode(IT Soluction)

{
doGet(req,res);
}
public void destroy(){
try{
if(ps!=null)
[Link]();
}
catch {Exception el)
{
el .printStackTrace();
}
try
{
if(con!=null)
[Link]();
}
catch(Exception e2)
{
[Link]();
}
}//destroy()
}//class
Servlet Component can read input values in 2 wavs:

a) Request parameter:

->For non-technical inputs from end-user (client side).Use [Link](-) in


Servlet Component.

b) Servlet lnit parameter

For technical inputs from programmer (server side].Use [Link](-) in


Servlet Component.

Eclipse: jar files added to build path of eclipse IDE Dynamic web project will not be
moved to WEB-INF\lib folder automatically on deployment,To make that happening use
deployment assembly option of eclipse.

Procedure: Right click on project build path configure build path deployment
assembly  add build path entries next  select gar files  finish-apply  ok.

Note  Instead f using deployment assembly option we close copy same jar files to
WEB-INF/lib folder

Servlet init params are specific to t at servlet component for which they are
configured.

Using ServletConfig object, we can get logical name of Servlet component that is
given in [Link] file

ByteCode(IT Soluctions) Page 73


ByteCode(IT Soluction)

[Link]("<br> Logical name of servlet: "+[Link]());


[Link](”servlet config object class name: "+[Link]());
->The class of ServletConfig object on tomcat server is
[Link]

Different ways reading init param values

String s1 = [Link]("dbuser―);

Note: we must init param name to get its value.

Approach

Enumeration e = [Link](); //gives all init param names

while([Link]()){

String name = (String) [Link](); //gives each init param name

String value =[Link](name); /gives each init paral value

[Link](name +"<-——-~—>'+vaIue);

=>Instead of placing same init param values in multiple Servlet Components of a web
application through [Link] file configurations, it is recommended to place them as context
param values only for 1 time in [Link] file by using <context-param>,<param-
name>,<param-value> tags.

=>init params are specific to each Servlet Component for which they are cfg where as
context pmams are common for multiple Servlet Components of web application.

=>We can use ServletConfig object to read init params from [Link] file and we use
ServletContext object to read Context param from [Link] file.

[Link](-)// gives init param value

[Link](-) // gives context param value

AlI the context param values will be collected from the in-memory meta data of
[Link] and will be stored in ServletContext object.

Example:

<web-app>
<context-param>
<param-name>dbuser</param-name>
<pardm-value>scott</param-value>
</context-param>
<context-pnram>
<param-name>dbpwd</param-name>
<param-value>tiger</param~-value>
</context-param>
</web-app>

ByteCode(IT Soluctions) Page 74


ByteCode(IT Soluction)

To read context param value In any Servlet Component of web application

ServletContext sc = getServletContext();

String s1 = [Link]("dbuser‖);

 lf multiple Servlet Components want to get same JDBC properties from


[Link] then It is recommended to place them in [Link] file as context
param values.
 For improved DBApp that uses context parameter support to get JDBC
properties from [Link] file refer below example

Servlet-DB software communication (using context param values)

Example Application:

[Link]

<form action-="dburl“ method="post">


Employee no: <input type= "text " name= " teno "><br>
<Input type="submit " value= "gerEmpDetaiIs">
</form>
[Link]
<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>[Link]</param-value>
</context-param>
<context-param>
<param-name>dburI</param-name>
<pamm-value>Jdbc:omcle:thin:@loclahost:1521:orcI</param-vaIue> „
</context-param>
<context-param>
<param-name>dbuser</param-name>

<param-value>scort</param-value>
</context-param>
<com¢xt-pamm>
<param-name>dbpwd</param-name>
<parum-value>tiger</pamm-value>
</context-param>
<servlet>
<servlet-name>DB</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on—startup>
</servlet>
<servlet-rnapping>
<servlet-name>DB</servlet-name>
<url-pattern>/dburI</url-pattem>

ByteCode(IT Soluctions) Page 75


ByteCode(IT Soluction)

</servlet-mapping>
</web-app>

[Link]
-//[Link] (show servlet to DB software communication based on
approach)
package [Link];
import javax. Servle.*t;
import javax. [Link].*;
import [Link].*;
import [Link].*;
public class DBServlet extends HttpServler{
Connettian con;
PreparedStatement ps;
Public void init()
{

//get Access to ServletContext object


ServletConfig sc=getServletContext();
// read context param values from [Link]
String s1=[Link]("driver");
String s2=sc. getInitParamete (“dburI");
String s3=[Link]("dbuser“);
String $[Link]("dbpwd“);
// create JDBC can abject
[Link](sl);
con=[Link](s2,s3.s4);
// créate JDBC PreparedStatement object....
ps=[Link]( "SELECT EMPNO,ENAME,JOB,SAL FROM
EMP WHERE EMPNO=?");
}//try
catch(SQLException se)
{
[Link]();
}
}//init
public void doGet(HttpServletRequest req,HttpServletResponse res )throws
ServletException, IOException
{
try
{
// read farm aura from form page
int na=[Link]([Link]("teno"));
//get PrintWriter object
PrintWriter pw=[Link]();

ByteCode(IT Soluctions) Page 76


ByteCode(IT Soluction)

// set response content type


[Link]("text/htmI");
// write JDBC code.....
//set value to parameter of the qry
[Link](l,no);
// execute the query
ResultSet rs=[Link]();
//process ResultSet abject and display emp details....
lf([Link]())
{
[Link]("<br><b><i> Emp number is: </i></b>"+[Link](1));
[Link]("<br><b><i> Emp name is: </i></b> +[Link](2));
[Link]("<br><b><i> Emp salary is: </i>"</b>"+[Link](3);
[Link]( "<br><b><i> Emp Job is: </i></b>“+[Link](4));;
}//If
//close Resut:Set: object
[Link](),
 Deployment of web application
// close stream object
 Checking of deployment directory structure
[Link](/,'
 Checks whether [Link] file is use for valid or
}//trv not
catch(Exception e)  Create memory must [Link] file
{
[Link]();
}
}//doget(-,-)
Public void doPost(HttpServletRequest req, HttpServletResponce res)throws
ServletException,IOException {
doGet([Link]);
}
public void destroy()
}//close jdbc object
try {
if(rs!=null)
[Link]();
}
Catch(SQLException se)
{
[Link]();
}
try {
if(ps!=null)
[Link]();
}
Catch(SQLException se)
{
[Link]();
}//destroy()
ByteCode(IT Soluctions) Page 77
ByteCode(IT Soluction)

}//class

Q. why are we not using properties file in Servlet Componentming to supply JDBC
properties?

Ans: we can take properties file having JDBC properties but not recommended e
because already we need [Link] file for regular servlet configurations, so It is better to use
same [Link] file to supply JDBC properties.

Different ways of reading context gram values:

Approch1:

String s1 = [Link]("dbuser‖);

Approach 1

Enumeration e = [Link]();//gives all context param names

while([Link]()){

String name= (String)[Link]();

String value = [Link](name);

[Link](name+" ..."+value);

Q. Can we give same name for context param and init param?

Ans: Yes, it is possible because we can read init param value by using ServletConfig
object and Context param value by using ServletContext object.

 lf we give same name to multiple context parameters we can get exception in


tomcat 6, 7 server but we get 2nd value in tomcat B/9 server.
 lf we give same name for multiple init parameters we get 1― value in every
version of tomcat.
 We can give same name fo parameter of two different server

When we deploy the web application, the container/server reads [Link] file and maintain it
content as in memory metadata.

When servletContext object is created the context param"‗of in memory metadata will be
stored into servlet context object, similarly when ServletConfig object created the init param
value will be stored into servletfionfig object.

Using ServletContext obiect we can gather flowing miscellaneous information

//Get ServletContext object

ServletContext sc=getServletContext();
ByteCode(IT Soluctions) Page 78
ByteCode(IT Soluction)

[Link]("<br> Server Info"+[Link](ServerInfo());

// Tomcat 9.0

[Link](‖<br> Servlet api version "~scagetMajarVersian()+


"+[Link]());

//3.1

[Link]("<br> Real path of web application―+[Link](‗7"));

// D:\Tomcat 8.0\webapps\DBApp

[Link] ("<br> Real path of [Link]"+[Link](―/[Link]―));

// D.-\Tomcat 8.0\webapps\DBApp\[Link]

[Link] ("<br> MIME type of input hrrnl‖+[Link]("[Link]"));

//text/html

//writemessage to log file

[Link]("System Date"+new [Link]());

//write <'Tomcate_home>logs folder log file (current days log file)

[Link](<br> effective version “+[Link]()+”.”


+[Link]());

[Link](<br>virtual server name “+[Link]());

//(catlina/localhost)(4.0)

Glassfish

Type application server

Vendor SunMs(Oracle cor.)

Version 4.x (compatible with jdk 1.7)

Solution: Take the support of Bean as shown below

[Link](JavaBean)

public class Student {


private int sno;
private String sname;
private int rn1,m2,m3;
//setters and getters
…..

ByteCode(IT Soluctions) Page 79


ByteCode(IT Soluction)

……
}
[Link]
public class GeneratResult {
public String findResult(Student bean)(
…….
……
}
class ClientApp{
public static void main(String args[]){
GenerateResult obj=new GenerateResult();
Student stud=new Student();
[Link](101); [Link](“ra]a");
stud.setM1(30); stud.setM2(90);stud.setM3(60);
ob].findResult(stud);
}//main '-
}//class

 Java bean is a helper java class whose obj holds huge amount of data to transfer
between two comps/layers of the project.

3 types of JavaBeans

a) Vo class (Value Object class)

b) DTO class/TO class (DataTransferObject class/TransferObject class)

c) BO class (Business Object class)

Vo class

=>The Java Bean whose obj holds either Inputs coming App or outputs to be
displayed by the App is called Vo class. Vo class generally contains String properties to
represent inputs

[Link]

public class StudentVO {

private String sno;

public String sname;

private String m1,m2,m3;

//setters and getters

DTO class

ByteCode(IT Soluctions) Page 80


ByteCode(IT Soluction)

 The javaBean whose obj holds data to send from 1 layer to another layer or 1 comp to
another comp is called DTO.
 Generally this class implement Serializable(l) and contains diff types of properties as
required for the desk comp/layer

public class StudentDTO implements Serializable{

private int sno;

private String sname;

prviate lnt m1,m2,m3;

//setters and getters „

……

….

BO class

=>The javaBean whose obj holds persistable data or data given by persistence logic is
called BO class. This class properties and Db table cols must be compitable with each other.

Db table BO class

Student tab public class StudentBO{ ,


|-—->sno(n) private int sno; i
|--->sname (vc2) private String sname;
|-—->total (n) private int total;
|-—->avg (n) private float avg;
l—->result (n) private String result;

//setters & getters

Conclusin

 ln real time the java bean class is used to hold multiple value in a single object
and also useful to send multiple value from 1 layer to another layer as single
object over the network.
 The java bean whose obiéct represents input values(from data) is called V0
class(value object) this class contains more String information. é
 The java bean whose object can be sent over the network 1 layer to another
layer is called DTO

(Data transfer object) This class must be implements Serializablell).

The iava bean whose object holds data required for persistence operations or data
given by persistence logic is called B0 (Business Object) [Link] method with

ByteCode(IT Soluctions) Page 81


ByteCode(IT Soluction)

multiple params is not recommended because it gives confusion to identify the param while
calling the method. To overcome this problem we design method having single java bean
Object that holds multiple values,

DAO class:

The tava class that separates persistence logic from another logics of the application is
called DAO (Data Access Object) the advantages are.

a) Makes persistence logic as reusable logic

b) Makes persistence logic as flexible logic to modify.

We generally design multiple DAO classes for multiple DB tables on 1 per DB table
basis if db table count <1OO otherwise we design DAO classes on 1 DAO class per related
db tables basis .

Eveg DAO class contains two garts:

a) Query part (SQL Queries declaration)

b) Code part (persistence logic)

 The DAO class methods generally contain 80 class as the parameter types or
return types
 DAO class is helper class for Service class which is a java class that contains
business logic/senrice logic.

StudentDAOApp
|--—-—->java resources
|--->src
| ----- ~>[Link]
|---- —->[Link]
|--~--—>[Link]
|----> [Link]
| ----- >[Link]
|---->[Link]
|---->[Link]
| --->[Link]
|-—-—>-[Link]..dao
|--->[Link] ‟
|-—-web content
|——>[Link]
|---->WEB-INF
|----->[Link]
|--->lib
|—>[Link]

ByteCode(IT Soluctions) Page 82


ByteCode(IT Soluction)

Example Application
[Link]
<h1><center>student Registration</center></h1>
<form action="studurl" method="post“>
No : <input type="text" name="na"><br>
Name: <input type="text" name="name"><br>
Marksl <input type="text" name="m1"><br>
Marks2: cinpur rype="text" ncrme="m2"><br>
Marks3: <input type="text" name=“m3"><br>
<input type="submit" value="register">
</form>
[Link]
package [Link];
public class StudentVO {
private String sno;
private String sname;
private String m1,m2,m3;
public String getsno() {
return sno;
}
public void setsno(String sno) {
[Link] = sno;
}
public String gerSname() {
return sname;
}
public vold setSnume(Sl:ring sname){
[Link] = sname;
}
public String gerM1(){
return ml;
}
public void setM1(String m1) {
this.m1=m1;
}
public String setm2(){
return.m2;
}
public void setM.2(String m2) {
this.m2 = m2;
}
public String getM3() {
return m3;
}
public void setM3(String m3) {
this.m3 = m3;
}
}

[Link]
package [Link];
public class StudentDTO imlements Serializable {
private int sno;

ByteCode(IT Soluctions) Page 83


ByteCode(IT Soluction)

private String sname;


private int m1,m2,m3,'
public int getsno() {
return sno:
}
public void setSno(int sno) {
[Link] = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
[Link] = sname;
}
public int getMl() {
return ml;
}
public void setM1(int m1) {
this.m1=m1
}
public int getM2(){
return m2;
}
public void serIvi2(int m2) {
this.m2=m2
}
public inr getM3() {
return m3;
}
I public void sétM3(int m3) {
this.m3 = m3.
}

[Link]

package [Link];
import [Link];
Import [Link];
import [Link];
public class StudentService {
public String generaleResult(SrudentDTO dto) {
int toraI=0;
float avg=0.0f;
String result=nuII;
$tudentB0 bo=null;
StudentDAO duo=null;
int cnt=0;
//Use [Link] to calculate total,avg,resuIts
total=dto.getM1()+dto.getM2()+dto.getM3();
avg=tolal/[Link];

ByteCode(IT Soluctions) Page 84


ByteCode(IT Soluction)

if(avg<35)
result="FaII";
else
result="Pass";
//prepare BO class object having persrstable data
bo=new StudentBO();
[Link]([Link]());
[Link]([Link]());
[Link](total);
[Link](avg);
bo_setResul:(result);
//Use DAO ‟
dao=new StudentDAO();
cnt=[Link](bo);
if(cnt==0)
return "Registratiom Failed";
else
rneturn "Registration succeded and ResuIt"+resuIt;
//generalResult(-).
}//class
StudentControllerServIet

package [Link];
import [Link];
impon [Link];
import [Link];
import [Link];
import [Link];
import ][Link];
import [Link],'
import [Link];
Import [Link];
import com. nt. [Link];
public class StudentControllerServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOExceptlon {
StudentVO vo=null;
String no=null,name=null,m1=null,m2=null,m3=null;
StudentDTO dto=null;
StudentService service=nuIl;
String result=nuII;
PrintWriter pw=nulI;
ServletOutputStream sos=null;
//read form data
no=[Link]("no ");
name=[Link]( "name ");

ByteCode(IT Soluctions) Page 85


ByteCode(IT Soluction)

m1=[Link]( "m1 ");


m2=[Link]("m2 ");
m3=[Link]("m3 ");
//Create VO class object having form darn
va=new StudentVO();
[Link](n0); [Link](name);
va.setM1(m1); vo.setM2(m2); vo.setM3{m3);
//Convert VO class object to DTO class object
dto=new StudentDTO();
[Link]([Link]([Link]()));
[Link]([Link]());
dta.setM1([Link](vo.getM1()));
dto.setM2([Link](vo.gerM2()));
dto.setM3([Link](vo.getM3()));
//use Service class
service=new StudentServise();
result=[Link](dto);
//display result
sos=[Link]();
[Link]();
[Link](“<h1>Result”+result+”</h1>”);
//add hyperlink
[Link](“<a href=”[Link]”>home</a>”);
//closs streams
[Link]();
}//doGet(-,-)
@Override
protected void daPost(HttpServIetRequest req, HttpServletResponse res) throws
ServletException,IOException{
doGet(req,res);
}//doPost(-,-)
}//class

StudentDAO
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class StudentBO {
private static final STUDENT_INSERT_QUERY=”INSERT
INTO STUDENT_TAB1 VALUSE(?,?,?,?,?)”;
public int insert(StudentBO bo){
InitialContext ic =null;
DataSource ds=null;
ByteCode(IT Soluctions) Page 86
ByteCode(IT Soluction)

Connection con=null;
PreparedStatement ps=null;
int result=0; "
//create InitialContext
ic=new IntiaIContext();
//get Datasoruce object through Iookup operation
ds=(DataSourze)[Link]("Dslndi");
//get Connection form JDBC can pool
con=[Link]();
//create PreparedSmtement object
ps=[Link](STUDENT_INSERT_QUERY);
//set values to query params
[Link](1,[Link]());
[Link](2,[Link]());
[Link](3,[Link]());
[Link](4,[Link]());
[Link](5,[Link]());
//execu re query
result=ps. executeUpdate();
}//try
catch(SQLException se){
[Link]();
}
catch(Exception e){
[Link]();
}
finally{
try{
if(ps!=null)
ps. close ();
}
catch(SQLException se){
[Link]();
}
try{
jf(con!=nulI)
[Link]();
}
catch(SQLExcepti0n se){
[Link]();
}
}//finally
return result;
}//method
}//class
[Link]

ByteCode(IT Soluctions) Page 87


ByteCode(IT Soluction)

<web-app>
<display-name>StudentDAOApp</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>st</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>st</servlet-name>
<url-partem>/studurl<url-pattern>
<servlet-mapping>
</web-app>
Q. What is different between web server and application server?
Web server Application server

1. Designed to deploy & manage 1. Designed to deploy & manage


only web appllcatlon (war) web applications(war), EIB
2. Designed to based on servlet, components(jar) and enterprise
jsp technologles of jee module applications(ear)
3. Does not allow to create 2. Designed based on multiple
domains technologies of jee module.
4. Gives only servlet, jsp 3. Allows to create.
containers 4. Gives Servlet Container, jsp
5. Allows to use http,https container,ElB container and
protocols other Miscellaneous
6. Allows only web containers.
clientslbrowserl 5. Allows to use
7. Suitable for small scale http,https,smtp,llop and other
websites protocols.
8. Gives less [Link] middlware 6. Allows both web clients and
services other normal clients.
9. eg: Tomcat,Resin 7. Suitable for large scale
websites and other jee
modules
8. Gives more [Link] mlddleware
services.
9. eg: Glassfish,weblogic,Jboss
Note: Up to S verslons Tomcat IS web server, from VCISIOH 6 because of addntlonal
tacllmes that It is offering hke connectlon pool suppomdatasource, so that Tomcat can be
called as Applncation server

ear file =war file vwar file +…….

ear file = jar file +]ar file flar file +……….

ear file = war file +jar file +……

ByteCode(IT Soluctions) Page 88


ByteCode(IT Soluction)

AppllcationServer = web server + EJB Contamer 4-addmonal middleware


SERVICES

Jboss:
Type. Application server software

Version 7.1(compitable with jdk 1.7)

Vendor apache(now with redhar)

Default port no; 8080 open source

Download software as jboss-as-7.1.1 [Link] file

 Gives 5 default domain: standard,all,web,default,minimal.

To start jdboss(m mycomputer properties

a) Set java_homejava7 installtion folder


b) Set pathjava7installation folder/bin directory.

To change Http port no:

Go to<Jboss_home>\standalone\configuration\[Link] file and modify the port


attribute value of the following tag

<socker-binding name="http" port= "8899"/>

To crate agglication user in Jboss:

Click on <jboss_home>\bin\[Link]

User type: management user

Username: jbossuser

Password: userjboss

Retype password: userjboss

Procedure to deploye java web application In jboss 7 server.

a) Prepare war file (like [Link])

b) Start jboss sewer

Use<Jboss_home>\bin\[Link] file (run as administrator)

ByteCode(IT Soluctions) Page 89


ByteCode(IT Soluction)

c) Deploy the web application:

[Link] username:jbossuser—-> password:userjboss

 Deployrnent-)mange deployments—>add content—>browse and select the war


file([Link])-)next—>save-) enable- confirm.

d) Test the ppllcation. Procedure to display java application widfy server


10.x(jboss) widfy10.1.0 [Link] file creation for
uri: locaihost:8899'/VoterApp: instanllation

Servlet Communication:

 It speaks about how Serviet cumpouei gets request, now Si:-rvlet component
generates response and how Servlet ::nnnmmicate with other web components of the
same web application or different web applications
 In web applications it is not recommended to place entire logics in on Servlet /Jsp
componentrlt is recommended to place such logics in muitipie web components of
web applications to distribute the logics and we need to use these Servlet Components
interacting with each other.
Servlet
Communication

Request Dispatching
browser to servlet or web Applet servlet
[Link]

Req/Res Sending or Rors Send Redirection Forwaording Req Including Responce

Using
Using Hyperlink
[Link]()

Request dispatching/web components cbmmunlcations:


Here the request given to 1 Servlet Component will be passed to another 1 or more
Servlet Components in [Link] multiple Servlet Components together will process single
request. Due to this all these Servlet Component will use same request and response
objects.
Servlet1 Servlet2 Servlet3 Servlet4
Browser
req req req req

res
res res res
d

ByteCode(IT Soluctions) Page 90


ByteCode(IT Soluction)

RequestDispatching can be done in two ways

 Forwarding request
 Including response

Forwarding request mode request Dispatching

Servlet2(dest)
Browser Servlet (source)
Forward req
request
………….
……….
.
……….
………
………….
response …4

Note: The output of source component (Servlel1) will be discarded, so only the output of
destination componea-it(Servlet2)_goes to browser through Sarvlet1.

2. Including responce

the output of both Servlet1,Servlet2 components together goes to browser as final


responce

Browser Servlet1(source) Servlet2(Dest)

request Including
responce
………….

response ……………

Note: Here no output will be discarded. More ever the output of both Servletl(source
component) and ServIet2.(destination component) together goes to browser as response

 To perform Requestmspatching the source Servlell Component uses


RequestDispatchkig object we call forward(-,-) method on th\s obyect then
fonlvardlng request mode of ServIetCommunication takes [Link] we call includek,-1
method on this object then lndudlng response mode of Servlettommunication takes
place.

ByteCode(IT Soluctions) Page 91


ByteCode(IT Soluction)

 RequestDispatcher object means it as the object of underlying Servlel Container


supplied java class that Implements [Link] (Dispatcher).

Different ways of creating ReuestDispatcher object:


Approach1 (using request object);

In source servlet
RequestDispatch rd = [Link](“/s2url”);
[Link]([Link]);
Or
[Link]([Link]);

Approach2 (using servlet context object);

In source servlet:
ServletContext sc =getServletContext();
RequestDispatch rd = [Link](“s2”);
[Link]([Link]); or
[Link]([Link]);

Approach3 (using servlet context object);

In source servlet:
ServletContext sc =getServletContext();
RequestDispatcher rd = [Link](“s2”);
[Link]([Link]); or |--->Logical name of
dests Servlet comp
[Link]([Link]);

ByteCode(IT Soluctions) Page 92


ByteCode(IT Soluction)

Q. what is the different between getRequestDespatcher(-) and getNamedDispatcher(-) method?

getRequestDispatcherl(-) getNamedDlspatther(-)
1. lnvokable only on Servlefliontext
1. lnvokable on both request, object.
ScrvletContext 1 objects. 2. Takes the logical name of
2. Takes the url pattern of destinatio servlet/isp as argument
destination servlat/jsp value.
component as argument
value. 3. Does ‘not allow to take html file
3. Allows to take html file as as destination component because
destination component by there is no possiblity of configuring
passing html file name html Hie in [Link]
argument value. having lomcal name
4. if distination comp is jsp we
can pass either jsp file name 4. we need to pass logical name of
or url pattern as the argument jsp file as the argument value
value
Q. What is different between creating RequestDispatcher object by using
request object and ServletContext object.

Ans. The request object based RequestDispatcher object allows to keep both soure
and destination componetes in 1 web application where as the ServletContext object based
RequestDispatcher object allowes to keep both source and destination components either in
same web application or in two different web application of same server but not in two
different web application of web different saerver for that we need to use sendRedirection(-)
concept.

Note: If source and destination component are there in two different we application of
two different servers then we need to go for sendRedirection concept.

Understanding [Link](-,-)
Servlet(Source)
browser

Request(1 Servlet(Destination)
) ……(2)

rd=[Link](“/s2url”);
[Link]([Link]);

response(7) ………
… (4)

The html output of source


Servlet(servlet1) will be discarded
and only the html output of Dest
Servlet(Servlet2) goes to browser as
response

Key points:
ByteCode(IT Soluctions) Page 93
ByteCode(IT Soluction)

 [Link](-,-) performs forwarding request mode of Request Dispatching.


 Source Servlet component directly interacts with destination component.
 Source Serviet and destination components use same rec|uest,response objects
,so the request data coming to Source component is visible and accessible in
Destination component.
 To pass additional data from source Servlet component to Destination
component use request attributes.
 Source Servlet and Destination component can be there either in one web
application or in two different web applications of same server.
 Destination component can be a Servlet Component /jsp component/html
component.
 All Statements placed in Source Serviet component before and after
[Link](-,-) executes but their output will be discarded.
 Usecase :[Link](-,-)is very useful in Error Servlet configuration.

Eg: Relway /online Tx

What ls Error Servlet ?

 The Servlet that executes only when exception is raised in other Servlet
Components I web components of web application is called ErrorServlet.
 This Servlet is useful to display exception related message as non-technical
guiding messages to end-users.

UseCase:

While booking ticket by giving credit/debit card no in online, If any exception comes
then instead displaying technical, ugly messages to end user, it is recommended to forward
request to Error Servlet to display non-technical guiding messages to end user.

Note: in Requestmspatching when source Servlet communication with destination


Senrlet ,the Senilet Container performs all life cycle activities on destination Servlet. it is
always recommended to place rdiforward(-,-)in source Servlet Component as conditional
statement to execute.

Sample code for Error Servlet configure on DBServlet :

public class ErrorServIet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServIetResponse res) throws
ServletException,IOExcepti0n{
// general settings
PrinrWriter pw=[Link]();
[Link]("texr/htmI");
//Display Error page
[Link]("<h1><center> Internal problem </center></h1>");
[Link]("<a hre_f=„[Link]”>Try again </a>");
[Link]();
}

ByteCode(IT Soluctions) Page 94


ByteCode(IT Soluction)

public void doPost(HttpServIerRequest req,Http5ervIetResponse res) throws


Sendetfxception,IOException{
doGet(req,res);
}
)//class
Configure [Link] in [Link] file with / eurl url pattern

[Link]

public class DBServlet extends HttpServlet{

public init (){

public void doGet(-,-) throws ServletException,IOException{

try{

catch(Exception e){

RequestDispatcher rd=[Link]("/eurl");

[Link]([Link]);

}//doGet(-,-)

public void doPost(-,-)throws SE,IOE{

doGet(req,res);

)//class

public void destroy(){

……….

}//class

Important points:

 in [Link](-) prefix ‖/" symbol before argument value is optional .


Where as in [Link](-) the same thing is mandatory.

ByteCode(IT Soluctions) Page 95


ByteCode(IT Soluction)

 The [Link](-,-) method placed in source Servlet Component does not discard
[Link](-l statements output, but discards the html output of given by
[Link](-) calls of Source Servlet componet.
 Once the response is committed we can't alter the response content and we can't add
additional content to the response so calling [Link]() or [Link]()
may raise exception.

Q. What happen If we place multiple [Link](-,-l methods in once source


Servlet Component.

Ans: Raises the following exception: [Link].

Important points

 Can't forward after response has been committed.


 Writing presentation logic in the catch block of source Servlet component to
display non-technical guiding message for end-user when exception I5 raise
but it does not discard the output of Source Servlet component . For this use
ErrorServlet.

Undersatanding [Link](-,-) method:

Understanding [Link](-,-)
Servlet 1(Source)
browser
Request (1) rd=[Link](“/s2url”);
……..
……[Link](-,-); Servlet 2(Dest)
(2)
3
Response (7)
(4)

The outputs of both


servlet1(Source),servlet2
(Dest) together goes to
browser as final response.
Key points:

 [Link](-,-) performs including response mode of RequesDispatching:


 Here no output will be discarded. Le. both Source and destination components
output together goes to browser as response.
 Source Servlet component directly interacts with destination component.
 Source Servlet and destination components use same request,response objects
so the request data coming to Source component is visible and accessible in
Destination component.
 To pass additional data from source Serviet component to Destination
component use request attributes.
 Source Servlet and Destination component can be there either in one web
application or in two different web applications of same server.

ByteCode(IT Soluctions) Page 96


ByteCode(IT Soluction)

 Destination component can be a Servlet Component lisp component/hlml


component.
 Destination component (Servlet2l output will be included to output of source
component (Servlet where [Link](-,-) method is called.
 Multipule of website contains same header, footer content. So instead of
writing those header, footer logics imeveg ServletComponent. it
isyrgcommended to write in seperate web components and include their
outputs toiy1ainServlet Component output by using [Link](-,-) method.

Problem

Header logic Header logic


……… ………
…… ……
Body logic of web Body logic of web
page 1 page 2
………… …………
Foter logic Foter logic
………… …………

 All b e of web application contain same header, footer content but header footer
logics are placed in all Servlet Components of web application indicates header and
footer logics are not reusable.

Solution

 place header logic in separate web component and footer logic in separate web
component and Include their outputs to the oupfit of Servlet Conlgonents which
generates web pages.

ByteCode(IT Soluctions) Page 97


ByteCode(IT Soluction)

HeaderServlet

…………………
………………..
(.Header component)
Servlet2
Servlet1
Header
Header [Link](-,-)
[Link](-,-) (hear)the header ……….
………. and footer logics Body logics of b
Body logics of b are reusable page2
page2 …
This process is
… ..
called implements
.. Footer
of composite view
Footer [Link](-,-)
disgin pattern
[Link](-,-)
[Link]

(.Footer logics)

Example Application on [Link](;,;) and [Link](-,-)

DBApp2
|—>java resources
|---->src
|---->[Link]
|--~>[Link]
|-—>[Link]
| ---->[Link]

|——>web content
|--->WEB-INF
|-->[Link]|
|-->[Link]
| --->[Link]
[Link]

<br><br><br><br><br>
<b><i><center> &copy; All rights reserved </center></i></b>
[Link]

<h1><center> Get Employee Details </center></h1>


<form action="dburI" method="post">

ByteCode(IT Soluctions) Page 98


ByteCode(IT Soluction)

Emp no: </input type="text“ name="teno ”> <br>


<input type="submit” vaIue="Details">
</form>
[Link]

package [Link]

import [Link];

import java. [Link];

import [Link];

impart [Link];

import [Link];

import [Link];

public class HeaderServlet extends HttpServlet{

public void doGe:(HttpServIetRequest req,HttpServletResponse res) throws


ServletException,IOException{

//general settings

[Link]("text/html");

PrinrWriter pw=[Link]();

//add header Content

[Link]("<marquee><h1> H C L Technilogies </h1></marquee>");

//do not close stream

public void doPost[HttpServletRequest req,HttpServletResponse res)throws

ServletException,IOException{

}/,/[Link]

doGet(req,res);

}//class

[Link]

//DBServlet java(Servlet Component)

package [Link];

ByteCode(IT Soluctions) Page 99


ByteCode(IT Soluction)

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

public class DBServlet extends HttpServlet {

Connection con;

PreparedStatement ps;

private static final String

GET_EMP_DETAILS_BY_NO=”SELECT EMNO,ENAME,JOB,SAL FROM


EMP WHERE EMPNO=”;

public void init(){

String driver=null,dbser=null,dbpwdpwd=null;

try{

//Acsess ServletContext object

ServletContext sc=getServletContext();

driver=[Link](“driver”);

url=[Link](“url”);

dbuser=[Link](“dbser”);

dbwd=[Link](“dbwd”);

//register JDBC driver

[Link](driver);

//esrablish the connection

con=[Link](url,dbuser,dbpwd);

//creat PreparedStaement object

ps=[Link](GET_EMP_DETAILS_BY_NO);

}//try

catch(CIassNotFoundException cnf){

[Link]();

ByteCode(IT Soluctions) Page 100


ByteCode(IT Soluction)

catch(SQLException se){

[Link]();

catch(Exception e){

[Link]();

}//init)

public void doGet(HttpServIetRequest req,HttpServIetResponse res)

throws Servletfxception,IOException

PrintWriter pw=null;

int no=0;

ResultSet rs=null;

RequestDispatcher rd=null,rd1=null,rd2=null;

try{

//include header content

. rd1 =[Link]("/headurl);

[Link](req,res);

| // get PrintWriter object

pw=[Link]();

// set response content type

[Link](“text/html“);

[Link]( “<b> Before raising Exceptiom</b>");

//read form data (request data)

no=[Link]([Link](“teno"));

//set value to PreparedSatement SQL Query parameter

[Link](1,no);

//execute the SOL Query

rs=[Link]();

ByteCode(IT Soluctions) Page 101


ByteCode(IT Soluction)

//process the ResultSet

if([Link]()){

[Link]("<br>Emp no:“+[Link](1));

[Link]("<br>Emp name:”+[Link](2));

[Link]("<br>Emp Job: “+rs_getString(3));

| [Link]("<br>Emp Salary: ”+[Link](4));

}//if

else{

[Link](”<b> Records nut found </b>");

//add hyperlink

[Link]( "<br><br><a hrej= „input. htm!„>home</a>");

// get Access go SErvletconfig object i

//include footer content

rd2=[Link](“/[Link] ");

rd2. Include(req, res);

//close JDBC objects

[Link]();

//close stream

[Link]();

}//try

catch(Exception e){

rd=[Link]( "/eurl ");

[Link](req,res);

}//doGet(-,-)

public void doPost(HttpServIetRequest req,HttpServetResponse res)throws


ServletException, IOExcepnon{

doGet(req, res);

ByteCode(IT Soluctions) Page 102


ByteCode(IT Soluction)

public void destmy(){/

/close JDBC objects

try{

if(ps!=nuIl){

[Link]();

cutch(SQLException se){

[Link](),

try{

if(con!=null){

[Link]();

}//try

catch (SQLException se){

[Link]();

}//destroy()

}//class

//javac -d . [Link]

[Link]
import [Link]:

Import [Link];

import [Link];

import [Link],

import [Link];

impart [Link];
ByteCode(IT Soluctions) Page 103
ByteCode(IT Soluction)

import [Link];

public class ErrorServlet extends HttpServlet{

public void doGet(HttpServlerRequest req,HttpServletResponse


res) throws ServletException,IOException {

[Link]{ "ErrorServlet:doGet(-,-)");

//Include header content

RequestDispatcher rd 1 =[Link]( "/headurI");

[Link](req,res); */

// general settings

PrintWriter pw=[Link]();

[Link]("text/htmI");

//Display Error page

[Link]("<h1><center> Internal problem </center></h1> ");

[Link]("<a href=””[Link]>Try again </a> ");

//include footer content

RequestDispatcher rd2=[Link]( "/footer. html");

rd2. incIude(req, res); */

//close stream

[Link]();

public void doPost(HttpServletRequest req, HttpServletResponse res)trhrows

ServletException, IOException{

[Link]("ErrorServlet:doPost(-,-)");

. doGet(req,res);

}//class

-[Link].

<web-app>
<welcome-file-list>
< welcome-fiIe>[Link]</welcome-file>

ByteCode(IT Soluctions) Page 104


ByteCode(IT Soluction)

</welcome-file-list>
<context-param>
<param-name>driver</param-name>
<param-value>[Link]</param-value>
</context-param>
<context- param>
<param-name>urI</param-name>
</context-param>
<context-param>
<param-name>dbuser</param-name>
<param-value>manager</param-value>
</context-param>
<context-param>
<param-name>pwd</pamm-name>
<param-value>rajar</parum-vaIue>
</context-param>
<servlet>
<servlet-name>db</servlet-name>
<servlet-class>[Link]</servlet-class>
<lond-on-startup>1</ lond-on-startup>
</servlet>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-
value>
<servlet-mapping>
<servlet-name>db</servlet-name->
<urI-pattern>/dburl-pattern>
</servlet-mapping>
<servlet>
<servlet-name>err</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet~mapping>
<servlet-name>err</servlet-name>
<urI-pattern>/@urI</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>head</servlet-name>
<servlet-class>[Link]</servle-class>
</servlet>
<servlet-mapping>
<servlet-name>head</servlet-name>
<ur1-pattern>/headurl</url-pattern>
<servlet-mapping>
</web-app>

ByteCode(IT Soluctions) Page 105


ByteCode(IT Soluction)

[Link] is the different between [Link](-,-) and [Link](-,-)?

[Link](-,-) [Link](-,-)

1. Performs the fowvarding request 1. Performs including


mode of RequesDispatching. response mode of
RequesDispatching.
2. Discard: the output of source 2. No output will be discarded
Servlet, so only the output of ,more ever both outputs
destination Servlet Component goes together goes to browser
to browser. as response.
3. All statemenqplaced source 3. Will not be discarded.
Servlet comp executes but their 4. Use case: useful to make
output will be discarded. common
5. logic(header,footer logics)
4. Use case: ErrorServlet as reusable logics
configuration. (composite-view disgn
patern implementation

lmportant Points:

If we place multiple [Link](-,-) calls in one Servlet Component the output of


multiple destination cornponenmwill be included by the source component.

 if we place both [Link](-_») & rclincludel-,-J in one Servlet Component


the effected of [Link](-,-) is not there because [Link]/ard not only discard
source component output it also discard included output.
 While working with [Link](-,-) do not close stareamldo not commit the
response) in the destination component it does not allow to add further content
to the response. Don‘t close stream like [Link] , source m source servlet
before closing [Link](-,-)

Note. In source Servlet Component, we can‘! place [Link]() method that commits
the response before [Link](-,-) or rd.|nclude(-,-) method l5 called, because it throws
lllegalStateException saving Can‘t forward or can't include after res onse has been
committed.

In servlet commucation the request methodlogy of req comm to source servlet will be
carried to distivatiion servlet. If source servlet gets Post methodlogy request it user same
methodlogy post while forwarding req to distraction servlet.

ByteCode(IT Soluctions) Page 106


ByteCode(IT Soluction)

Using RequestDispathcher to get Communication between two web application


resource component are In two different web application server.
WebServer/App Server
browser

[Link] WaOne(web application)


FirstServlet(sourse)
Value: 30 …..//calc square
Request (1) (2)
rd.=[Link](“/s2url WaTwo(web application)
GetSquer
(6) SecondSer(Dest)
”); (3)
&Cube ….calc Cube vlue
[Link](-,-)
(4)
Dynamic webpage Respose(7) (5)

Squer :900
Cube:2700

Here source and destination component are there in two different web applications of
same server. So we must use ServletContext object based RequestDispatcher object.

WaOne(EDWP)
|------>java resources
|------>src
|------->[Link]
|------->webcontent
|------->[Link] Deploy both web application in the
|----->WEB-INF same Domain Server of weblogics
|------>[Link] s/w (WLNtAjsDomain)
WaTwo(EDWP)
|------>java resources
|------>src
|------->[Link]
|------->webcontent
|------->[Link]
|----->WEB-INF
|------>[Link]
Example application on RequestDispatcher:

Deploy both web application in same server (weblogic)

Deploy WaOne application

[Link]

<h1><center>Find SQUARE and CUBE Values</center></h1>

<form action=”s1url”v method =”post”>

Value: <input type=”text” name=”t1”><br>

ByteCode(IT Soluctions) Page 107


ByteCode(IT Soluction)

<input type=”submit” value=”Square & Cube”>

</form>

[Link]

package [Link];

import [Link];

import java. [Link];

impart [Link];

import [Link];

import [Link];

Import [Link];

Import [Link];

import [Link];

public class FIrstServlet extends Httpservlet{

@Override

public void doGet(HttpServletRequest req, HttpServletResponse res)throws


ServletException, IOException

//general settings

PrinrWriter pw=[Link]();

[Link]("text/html ");

//readform data

int val=[Link]([Link]("t1"));

//calc SQUARE value

int square=val*vol;

[Link]("<br>FirstServlet:SQuare :"+square),

//include the response of SecondServlet Component

//get Servletcontext object of current web application

ServletContext sc1=getServletContext();

//get Servletcontext object of WATwo web application

ByteCode(IT Soluctions) Page 108


ByteCode(IT Soluction)

ServIetContext sc2=[Link]("/WATwo");

//get RequestDispatcher object pointing to SecondServlet

RequestDispatcher rd=[Link]("/s2urI");

[Link](req,res);

//close stream

[Link]();

}//doGet(-,-)

@Overrid

public void doPost(HttpServletRequest req, HttpServletResponse res}

throws ServletException,IOException {

doGet (req,res);

[Link]

<web-app>
<display-name>WAOne</display-name>
<welcome-file-list>
<welcome-flie>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/s1urI</url-pattern>
</servlet-mapping>
</web-app>
Develop WaTwo Application

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

ByteCode(IT Soluctions) Page 109


ByteCode(IT Soluction)

import [Link];

import [Link];

import [Link];

public class SecandServIet extends HttpServlet

@Override

public void doGet(HttpServletRequest req, HttpServletResponse


res) throws ServletException, IOException {

//General setting

PrintWriter pw=[Link]();

[Link](“text/html”);

//read from data

Int val=[Link]([Link](“t1”));

//cal cube value

Int cube=val*val*val;

//display

[Link]("SecondServlet:Cubevalue "+cube);

//do not close stream

}//d0Get(-)

@Override

public void doPost(HttpSenrletRequest req, HttpServletResponse res) throws


ServletException, IOException {
We running these two wep application
doGet(req,res); from Eclipes don’t remove second web-
app while running the first web-app
} that’s means first run second web
application then run first web application
}

[Link]

<web-app>

<servlet>

<servlet-name>second</servlet-name>

<servlet-calss>[Link]</servlet-name>
ByteCode(IT Soluctions) Page 110
ByteCode(IT Soluction)

</servlet>

<servlet-mapping>

<servlet-name>second</servlet-name>

<url-pattern>/s2url</url-pattern>

</servlet-mapping>

</web-app>

Note

Being from one ServletContext object of one web application, if we want to access
ServletContext object of destination web application then we can call getContext(-) having
the name of destination web application

lmportant Points

 By Default Tomcat sever does not support the above CrossContext


communication because getContext(-) method is not implemented properly in
Tomcat server To enable cross context communication we can place
 it <Context crossContext = "true"/>in <tomcat_home>\config\[Link] file
 Scince Glassfish, Jboss servers internally use Tomcat server this crossContext
communication is also not possible In this two sewers.
 ServletConteirt of one web application which ls accessed from the
ServletContext object another web application is celled Foreign Context

In Eclipes project exploer--->server--->[Link]--->tomcat

Limitations on RequestDispatching(Requestdispatcer);

1. Source and destination components cannot be placed ln two different web


applications of two different servers.
2. Destination component can‗t be plip component or [Link] [Link]
overcome this problem use sendRedirection
3. Few server do not support croes-context commnucation throught request
dispatding

Sending Redirection:

Two ways of sendRedirection

 Using hyperlink
 Using [Link](-) method.

ByteCode(IT Soluctions) Page 111


ByteCode(IT Soluction)

Send Redirection using hyperlinks


Browser window
Tomcat Server
SendRDApp1
Intial request(1)
SearchServlet
Dynamic webpage
Response1 (3) (2)
Google

Dynamic webpage Requset2 (4)


Google pages

Final Response (6) [Link] (5)


(3)
 We use sendRedirection to redirect the request coming to one website to another
website when one company acquires another company

Example

 IBM has acquired Rational Company so the request given to [Link] will be
redirected to [Link].
 ln hyperlink based sendkedirecllon the visitor gets hyperlink when we gives request to
1st website by clicking on this hyperlink request goes to another website if he fqrgets
to click on hyperlink then send redlrection fails..
 overcome this problem ues [Link](-)method based
SendRedlrection.

sendRedirection using [Link](-) method


Browser WebServer1/AppServer1(Tomcat)
WA1 Servlet1(Sourse)

(2)

[Link]([Link]
Dynamic webpage

WebServer2/AppServer2
(web logic)WA2(web
(6)final applicaton)servlet(Dost)

Response (contains only the html (5)


output of Dest Servlet2 comp)

ByteCode(IT Soluctions) Page 112


ByteCode(IT Soluction)

Understanding [Link](-) method:

1. Browser gives initial request to Servletl component

2. AIl'the Statements of Servletl component, including [Link](-) method


executes due to this the output ofServlet1 component discards.

3. Implicit response goes to browser having the url placed in [Link] - od.

4. Browser uses that url and sends the request to Destination Servlet2 Component.
5&6 All the Statements of Servietl component executes and its output goes to browser.

Key Ponits:

[Link](-) performs sendRedirection mode of Servlet communication.

Here source component interacts with destination component after having 1 network
round trip with browser.

Source and destination components do not use same request, response objects, so the
request data coming to source component is not visible and accessible in Dest component.

To pass additional data form source component to destination component we need to


append query string to the url of [Link](-) method.

Eg:

In Servlet1:

[Link]("httpdocalhost:7070:/wo2/s2urI?sno=101 & sname=raja‖),"

In Servlet2:

String sl = [Link](‖sno");

Stirng s2= [Link]("sname");

 Servletl and Servlet2 components can be there in same web application or in two different
web applications of same or different servers.
 Servlet2 ([Link] component] can be therein any web technology.
 All statements of Servletl component executes, but their output will be discarded because of
[Link](-) method execution.
 if Servletl, Servlet2 components are local to each other then we can pass relative url in
[Link](-) method otherwise we need to pass absolute url.I
 It is recommended to place [Link](-) method as conditional statement to execute in
Source Servlet Component

Use Case:

 When company A acquires company B the request coming to [Link] website will be
redirected to [Link] by using this rE5.5eHdRedireCtl-] method.
 eg: IBM has acquired rational company ,so the request given to [Link] will go to a
page of [Link]
 eg:The request given to [Link] will he redirected to a page ol [Link]

ByteCode(IT Soluctions) Page 113


ByteCode(IT Soluction)

Exampleb App on [Link](-) method

(HUB for SeachEngines)


Browser
Search App
SearchSrv
Search String 7 wonders
(2)
Search Engg G B Y

Search

Dyanic web page

………(search)
………(Result)

SearchApp (EDWP)

|---->java resources
|---->src
|—>[Link]
|---->[Link]
|----->web content
|—->[Link]
|---->WEB-INF
|-->[Link]
Note:

Here the local servlet (SearchSenrlet) wants to communicate with remote web
component of search engine website. For this we need to use sendRedirect(-) method.

[Link]

[Link]

[Link]

Example Application on sendRedirect(-)

[Link]

<h1><center> Search through Search Engines</center></h1>

<form action=“searchurI" merhod=“post">

Search String : <input type="text" name="ss"><br>

Search Engine : <input type="radio" name= "engine " value="google”


checked>GoogIe

<input type=" radio" name="engine" value-= "bing ">Bing

ByteCode(IT Soluctions) Page 114


ByteCode(IT Soluction)

<input type: “radio " name=“engine" vnIue= "yahoo “>yahoo Search


<br>

<input type="submit" value="search">

</form>

[Link]

package [Link];

import [Link];

[Link];

import javax. [Link];

import [Link];

import [Link];

import [Link];

public class SearchServlet extends HttpServlet{

@Override

public void doGet(HttpServlerRequest req, HttpServletResponse res) throws


ServletExceptian, IOExceptlon

String ss=null;

String engine=null;

String urI=null; . -

//readform data

ss=[Link]("ss”);

engine=[Link]( "engine");

//prepare url with query String for send redirection ‟

if([Link](“google”)){

url=[Link]

else if([Link](“bing”)){

url=[Link]

else if([Link](“yahoo”)){
ByteCode(IT Soluctions) Page 115
ByteCode(IT Soluction)

url=[Link]

System .[Link](“Before SearchServlet:sendRedirect(-)”);

[Link](url);

RequestDispatcher rd=[Link](“[Link]”);

[Link](req,res);

[Link](“After SearchServlet:sendRedrirct(-)”);

}//doGet(-,-)

@override

Public void doPost(HttpServletrequest req, HttpServlertResponse res)throws


ServletException,IOException {

goGet(req,res);

[Link]—

Configure [Link] with*/ search url pattern

Confi [Link] as welcome file

<web-app >
<display-name>SendRDApp2</display-name>
<welcome-file-list>
<welcome-_file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>search</servlet-name>
<servlet-class>[Link]</servlet-closs>
</servlet>
<servlet-mapping>
<servlet-name>search</servlet-name>
<url-pattern>/searchurl</url-partern>
</servlet-mapping>
</web-app>

ByteCode(IT Soluctions) Page 116


ByteCode(IT Soluction)

Example on Hyperlink based SendRedrection:-

[Link]:-

<form action=‖searchurl‖ method=‖post‖>


Search String: : <input type=‖text‖ name=‖tsearch‖><br>
<input type =‖submit‖ value=‖search‖>
</form>
SearchServlet:-

public class SearchServlet extends HttpServlet{


public void doGet(-,-) throws ServlatException, IOException{
//genral settings
//read form date
ss = [Link](“tsearch”);
//GenrateDynami webpage havig hyperlink to perform send
redirect
[Link](<h1 style=”color:red”>check the link below</h1>
[Link]<a href=[Link]
} //doGet(-,-)
public void doPost(-,-) throws ServletException,IOException{
doGet(-,-){
}
}//close

Example Application

 Using [Link](-) method to get lnteractlon between web resource


components of two different serverskomcat, weblogic)
 Using [Link](-) method to get Interaction b/w web resource prgs of two dlff
Server (Tomcat , Web logic) ‗

Using [Link](-) method to get interaction b/w web resourse prgs of two diff server
(tomcat,web logic)

ByteCode(IT Soluctions) Page 117


ByteCode(IT Soluction)

Browser Window TomcatServer

TestAp(webaplication1
)
Bill(source prg1)calc Bill
Name: table Amt if(billAmt>=50000){
Price Redirect the request
2000 DiscountSrv }
Request(1) else { implicit response
Qty: 30
display bil Details
} (2)
Get BillAmt
(3)

Dynamic webpage TestAp(webaplication2)


Imlicit request(4)
Name: table DiscountSrv
Bill Amt: 60000 Calc discount amt
Discount: 18000 Final responcse(6)
Final amt : 42000
(5)

BillSrv calcs Bill amt and redirecs the request to DiscountSrv if bill amt >=50000 In this it sends
bill am! to Discount Srv by appending query stlmg to the url of [Link](-) method.

NtAj9Domain

TestApp1 (EDWP ) (for Tomcat) TestApp2 (EDWP ) (for Tomcat)


|—-->java resoruces |—-->java resoruces
|-->[Link] |-->[Link]
|--->[Link] |--->[Link]

|——>weh content |——>weh content


|-_->[Link] |-_->[Link]
|->WEB-INF |->WEB-INF
l—>[Link] l—>[Link]

BillServlet calculates blll amount and redirects the request to DiscountServlet, if bill
amount>=5000. In this It sends bill amount to DlscountServlet by appending query String to
the url of [Link](-) method.

TestApp1(First App)

[Link]

<form action=”billurl”>
Item Name: <input type =”text” name=”t1”><br>
Item Price: <input type =”text” name=”t12”><br>

ByteCode(IT Soluctions) Page 118


ByteCode(IT Soluction)

Item Qty: <input type =”text” name=”t3”><br>


<input type =”submit” value=”Get Bill deatils”>
</form>

[Link]
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>[Link]</servlet-cIass>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-partern>/billurl</url-pattem>
</servlet-mapping>
</web-app>

[Link]

//[Link]
package [Link];
import [Link].*;
import [Link].*;
[Link].*;
public class BillServlet extends HttpServlet
{
public void doGet(HttpServletRequest req. HttpServletResponse
res) throws ServletException,IOException
//General settings
PrinrWriter pw=[Link]();
[Link]("text/html");
//readforrn data
String name=[Link]( "t1”);
float price=[Link]([Link](“t2"));
float qty=[Link]([Link]("t3")).'
//calc Bill Amt
float bamt=price „qty;
if(bamr>=50000)
{
[Link]("before res. sendRD(-) in BillServlet“);
[Link]("[Link]
lname="+name);
[Link]( "after [Link](-) in BillServlet");
}//if
else
{

ByteCode(IT Soluctions) Page 119


ByteCode(IT Soluction)

[Link]("<br> From BiIlServIet component <br>”);


[Link]("<br> Item name: "+name+" Price; "+price+" Qty :"+qry+
"Bill Amt: "+bnmt);
}//else
//close stream
[Link](),'
)//doGet(-,-)
public void doPost(HttpServletRequet req,HttpServletResponse res)throws
[Link]{
doGet(req,res);
}//doPost(-,-) __
}//„class

TestApp2(second application)

[Link]

//[Link]

package [Link];
import [Link].*;
import [Link].*;
[Link].*;
public class DiscountServlet extends HttpServlet
{
public void doGet(HttpServletRequest req. HttpServletResponse
res) throws ServletException,IOException {
//General settings
PrinrWriter pw=[Link]();
[Link]("text/html");
//read additional request params given by BiIlServIet component (source
prg)

float amt=[Link]([Link](“bill"));
String name=[Link]( "iname”);
[Link](“Form DiscountServlet:doGet(-,-) method”):

//Calc discount Amt:


float Discount=amt * 0.3f;
float finalamt=amt-discount;
// Display Details
[Link]("<br> Item name : "+name);
[Link]("<br> Bill Amt :"+amt);
[Link]("<br> Duscount :"+discount+" Final Amount"+finalamt);
[Link] ("<br> From DiscountServlet component")
//close stream
[Link]();
}//doGet(-,-)
ByteCode(IT Soluctions) Page 120
ByteCode(IT Soluction)

„ public void doPost(HttpServletRequest req, HttpServletRespons


res)throws
ServletException,lOException{
daGer(req,res) ;
}
}// class
[Link]
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
servlet-name>xyz</servlet-name>
<url-pattern>/discounturl</url-pattern>
</servlet-mapping>
</web-app>

Important points:

 If we place multiple [Link] ;ggt(-) methods in one source Servlet


Component then [Link] will be raised.
 lf we place [Link](-) and [Link](-) in one source Servlet
Component then [Link] will be raised.
 If we place [Link](-) and [Link](-,-) in one source Servlet
Component then the effect of [Link](-.-) will not be there.
 lf source and destlnauon component are therein two different web applications
of same or different server ,Append query String to the url of
[Link](-) method.
 Its always recommended to place [Link] and response send Redirect(-) as
conditional stants in sources servlet.

eg; res sendRedlrect(url)param=val& param2=val2,....);

Note: ln sendRedirection we can‗: include the output of any Destlnailon component.

ByteCode(IT Soluctions) Page 121


ByteCode(IT Soluction)

Different between [Link](-,-) and [Link]()

[Link](-,-) [Link]¢t(-,-)
1. Perfomrs forwarding request mode of 1. Performs sendfiedirection mode of Servlet
Servlet communication communication.
2. Source component talks with destinauon 2. Source component talks with destination
component directly component after having network round trip
3. Source and destination component uses with browser.
same request and response objeqs so 3. Source and destination components do
request data coming to source component is not uses same request and response object
visiable and accessible in distination so the request data coming to source
component component is not visible and accessible in
destination component.

SESSION TRACKING/SESSION MANAGEMENT

Understanding the lmgqytance of dynamg form pages:

 htrnl files based form pages are called "static form pages‖. The form page that comes
as response of dynamic web resource components like servlet/JSP havlng dynamic
components and content is called as "dynamic form page”.
 static form page contains fixed form comps where as dynamic form pages contain
varying content. .
 To generate dynamic form page from Servlet Component place <forrn>, <lnput> tags
in [Link](-).To read huge amount of data from end user, it is not recommended to
take single static form page, where end user will be forced to read and ignore some
unrelated questions.

[Link](static form page)

Name: Raaj

Age: 23

Father Name: ramesh

Marital Status:

Spouse Name:

No. of Childern:

When to Marry After 2 year

Submit

ByteCode(IT Soluctions) Page 122


ByteCode(IT Soluction)

 ln the above forrn page, end user is forced to read and ignore marriage life related
questions even though he has not selected that marital status checkbox
 To overcome this problem ask common questions In first form page which is static
form page and generate second form page dynamically based on the content given in
first form page, so end user will not be forced to read and ignore certain questions of
form pages.
 Set of continues and related operations performed on web application by a client
(browser)with the support of multiple requests and responses is called as "session". f
eg:login to logout in [Link] '
 Start of advanced java class to end of advanced java on a particular day.

[Link](Static form)

C
Name raja
O
c Age 23
N
Marital status : married E
DynaFormApp
C
continu T
I
O Servlet org
Dynamic form (1)Request
N

Spouse name: (2)


rani 1
(3) Response1
No of children: 07

Submit Servlet2
(4) Request2
Or
(5)
When to marry:
C
Why to marry:
O

Submit N
E (6) Response2
C
Dynamic page
T
I
Form1/request data:
O
null…null..null
N
2
Form2/request2 data: rani…..7

In the above diagram Servletl is reading content of forml form page (Detailshtml) and
uses the value given by marital status checkbox to generate form}! as dynamic form page
with dynamic content. -

ByteCode(IT Soluctions) Page 123


ByteCode(IT Soluction)

ExampIe App demonstrate Stateless Behavior of Web Application

[Link]

<form action="s1url" rnethad="get">


<b> Name: </b><input type="tex1" name="pname"><br>
<b> Age :</b><inpur type="texr" name= "page"><br>
<b> MaritalStatus: </b><input type= "checkbox" value="married“ narne="ms">
Married
<input type=”submit” value=”continue”>
</form>
[Link]
<web-app>
<servlet>
<servlet-name>ABC</servlet-name>
servlet-cIass>[Link].Servlet1</servlet-c!ass>
</servlet>
< servlet -mapping>
< servlet -name>ABC</servlet-name>
<url-pattern>/s1urI</url-pattem>
</servlet-mapping>
< servlet>
< servlet-name>XYZ</servlet -name>
< servlet-class>[Link].Servlet2 </servlet-class>
</ servlet>
<servlet-mapping>
< servlet-name>XYZ</ servlet-name>
<urI-pattern>/s2urI</url-puttern>
</servlet-mapping>
<weIcome~file-list>
welcome~file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
[Link]

/[Link](Genmtes Second Form Dynamically Based on first Form Data)


package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class Servletl extends HttpServlet
{
pubiic void doGet(HttpServletRequest req,HttpServletResponse
res)throws ServletException,IOExceptian {
// read form1/request1 data
String name=[Link]("pname");
String age=[Link]("page"),'

ByteCode(IT Soluctions) Page 124


ByteCode(IT Soluction)

String mstatus=[Link]("ms");
if(mstatus==nuII)
mstatus="singIe";
// Get PrintWriter object
PrintWriter pw=res. getWriterf);
[Link]("text/html");
// Generate Second Form Dynamically Form here.
if([Link]("married"))
{
[Link]("<form action='s2urI' method="post" >");
[Link]("<b> Spouse Name </b><input
type=„text'name='st1'><br>");
[Link]("<b> [Link] Children </b><input type='text'
name='st2‟><br>");
[Link]("<input type= „submit‟ vaIue= 'sumbit ‟>");
[Link]("</forrn>");
}
else
{
[Link]("<form action='s2urI' method="post" >");
[Link]("<b> when do u want marry </b><input type=-„text‟
name='st1'><br>");
[Link]( "<b> why do u want marry </b><input type=„rext„
name='st2'><br>");
[Link]("<input type='submit' value='sumbit‟>"
[Link]("</form>");
}
[Link]();

}//doGet(-,-)
public void doPostHttpServletRequest req,HttpServletResponse
res)throws ServletException,IOException {
doGet(req, res);
}
}//class

[Link]

//[Link] (takes the request form second form (Dynamic Form))

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class Servletl extends HttpServlet
{

ByteCode(IT Soluctions) Page 125


ByteCode(IT Soluction)

pubiic void doGet(HttpServletRequest req,HttpServletResponse


res)throws ServletException,IOExceptian {
// get Printwriter object
PrintWriter pw=[Link](),-
[Link]("text/html"};
//read 1st form , second fonn data
[Link]("<br>First Form data is "),'
pw. println("<br>Nam'e Is "+[Link]("pname"));
pw. println("<br>Age ls "+[Link]("page"));
pw. println("<br>MnritaI Status is "+[Link]("ms"));
[Link] ("<br><br>$econd from data is
"+[Link](“st1")+"<br>
"+[Link]("st2"));
[Link]();
}//doGet(-,-)
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
doGet(req,res);
}
}//class

 During a session, If web application is not capable of remembering cllentlbrowser)


data across the multiple requests then it is called as "stateless behavior” of web
application, i.e while processing current request in web application, we cannot use
previous requests related [Link] example scenario of stateless behavior of
web application is nothing but the above web application where Servlet2 is getting
second request from cliéntlbrowserl but it failing to read and use requestl/forml data,
that means the web application failing to use previous request data while processing
current request.
 By default all web applications are stateless web applications During a session if web
application is able to rernernbet clientlbrowserl data across the multiple requests then
it is called as "statefull behavior" of web application. That means. while processing
current request in web application, we can use previous requests related information.
 To make web applications as stateful web applications we need to work with "session
tracking session management techniques".

Technique1:
Hidden Form fields (hidden boxes)
Hidden Box is an invisible text box- of for}n page_,_hidden box vélue goes to server
as request parameter when from is submitted. V
In form page;
<input type="hidden" name="h1" value= "hello"‘>
ln'ServIet Component:
String vall =[Link]("h1 "); //gives "hello " .
Session management or session tracking both are same.

ByteCode(IT Soluctions) Page 126


ByteCode(IT Soluction)

Browser window

[Link](Static form1 page) HiddenApp Web

Name raja FristServlet(Servlet Componet)

Age 23

Marital status : married (1) Request 1 (2)

continue
Response 1

Spouse name: SecoundServlet


rani
(1) Request 1
No of children: 07

Submit

When to marry:

Why to marry:

Submit Response 2 Insert form DBtable

Oracle database (DB table)

Form data raja…fraja…married

Form data rani …2 Person tab (DBtable)


Name fname ms {2vall f2vall
Raja fraja married rani 2

in the above diagram FirstSer\/let Component is reading formll requestl data and adding that
data to the dynamicaily generated forml as hidden box values(look at step 2 and step3).Due to
this when form2 sends its request2 to SecondServlet component the SecondSewlat
component can read forml/requestl, forml/request2 data, this is nothing but accessing
previous requests data (requestl data) while processing current request (requestl). Technically
this is called "session tracking”(look at step 4 & step 5). -‗ ‗

Example Application on Session Tracking using Hidden Form Faleds

[Link]

<form action= "furl" method="post">


Name: <input type="text" name="tname"><br>
Father name: <input type="text" name="tfname"><br>
ByteCode(IT Soluctions) Page 127
ByteCode(IT Soluction)

Morita! Status <input type="radio" name="ms" vaIue="married”>Married


&nbsp;&nbsp;&nbsp;
<input type="mdio" name="ms“ value="singIe">Single <br>
<lnput type="submir" value="continue">
</form>
[Link]
<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
< url-pattern>/furl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>second</servlet-name>
<servlet=class>[Link]</servlet-dass>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/surl</url-pattern>
</servlet-mapplng>
</web-app>
[Link]
//[Link] (generates dynamice form page)

package [Link];

import javax servlet.*;

import [Link].*;

Import [Link].*;

public class FirstServlet extends HttpServlet

public void doGet(HttpServletRequest req,HttpServletResponse res) throws


ServletException,IOExceptIon

// general code

PrintWriter pw=[Link]();

[Link]("text/html");

ByteCode(IT Soluctions) Page 128


ByteCode(IT Soluction)

// read forml data

String pname=[Link]("tname”);

String pname=[Link]("tfname");

String pms=[Link]("ms”);

//design and send dynamic form page to browser window

// based on the marital status....

if([Link]("single“))

[Link]( “<form action='surI„ method= „post'>");

[Link]("why do u want to marry <input type='text' name='f2t1'><br>")

[Link]( "when do u want to marry <input type=„text„ name=f2t2'><br>”)

// add forml/reql data ta dynamic form page as hidden box values

[Link]("<input type='hidden' name=='hname' value="+pname+">");

[Link]("<input type= „hidden‟ name=„hfname„ value="+pfname+">");

[Link]("<lnput type='hidden' name=„hms' value="+pms+">");

[Link](„<input type= 'submit' vaIue='submit'>“);

[Link]("</form>");

else{

[Link](“<form action =‟surl‟ method=‟post‟>”);

[Link](“<form action =‟surl‟ method=‟post‟>”);

[Link](“Spouse name <input type=‟text‟ name=‟f2t1‟><br>”);

[Link](“no. of childern <input type=‟text‟ name=‟f2t2‟><br>”);

//add form1/req1 data to dynamic form page as hidden box values

[Link](“input type=‟hidden‟ name=‟hname‟ value=”+pname+”>”);

[Link](“input type=‟hidden‟ name=‟hfname‟ value=”+pfname+”>”);

[Link](“input type=‟hidden‟ name=‟hms‟ value=”+pms+”>”);

[Link](“<input type=‟submit‟ value=‟submit‟>”);

ByteCode(IT Soluctions) Page 129


ByteCode(IT Soluction)

[Link]("</f0rm>");

//close the stream object

[Link]();

}//doGet(-,-)

public void doPost(HttpServletRequest req,HttpServletResponse res) throws


ServletException,IOExceptiorn

daGet(req,res);

}//class

[Link]
//[Link]

package [Link];

import [Link].*;

[Link].*;

import [Link].*;

import [Link].*;

publlc class SecondServlet extends HttpSeervlet

public void doGet(HttpServletRequest req,HttpServletResponse res) throws


ServIetException,IOException

// general code

PrintWriter pw=[Link]();

[Link]("text/html”);

// read farml/request! data ,

String name=[Link]("hname ");

String fname=[Link]("hfname ");

String ms=[Link]("hms");
ByteCode(IT Soluctions) Page 130
ByteCode(IT Soluction)

// readform2/request2 datb

String _f2val1=[Link]( "f2t1 ");

String f2voI2=[Link]( "f2t2 ");

// write form1/req1,from2/req2 values to DB table as record

try

[Link]( "[Link]");

Connection

con=[Link](“[Link]:@lacalhost:1521:xe","scott",
"tiger");

PreparedStatement ps=[Link](“insert into persontab values{?, ?, ?, ?.


?)");

[Link](1,name);

[Link](2,fname);

[Link](3,ms);

[Link](4,f2val1);

[Link](5,f2val2);

int result=[Link]();

if(result==1)

[Link]("<br>Record inserted<br>");

else

[Link](”<br> Record not inserted);

}//try

catch(Exception e)

[Link]();

// display request1/form1,request2/form2 data on the browser window


ByteCode(IT Soluctions) Page 131
ByteCode(IT Soluction)

[Link]("<br> form data is “+name+"... "+fname+".... "+ms);

[Link]("<br> f0rm2 data is "+f2vaI1+"...'+f2val2);

//close stream object

[Link]();

}//doGet(-,-)

public void doPost(HttpServletRequest req,HttpSen/IetRespanse res)


throws ServletExceptian,IOException{

daGet(req,res);

}//class

Advanggges and disadvantages of hidden form fields based session tracking technique:

Advantages

1. Basic html knowledge is sufficient to work with this technique.

2. Hidden boxes reside in the form page holding the client data across the multiple request‖
that means they do not allocate memory on server and don't give burden to server.

3. This technique works with all server side technologies like sen/lets, JSP, [Link], PHP and
etc.,

4. This technique works with both java and non-java servers.

Disadvantages

1. The hidden box value of form page can be viewed using source code of web page.
That means there is no security (data secrecy is not there)
2. Hidden boxes travel over the network along with the request and [Link]
indicates more network traffic.
3. We cannot store all kinds of java objects in hidden boxes except text/string values.
4. More hidden boxes should be added in each dynamic form page to preserve more
client data across the multiple requests.

Real world application examples of Session tracking

1. To remember user identity during the session of email-operations.


2. While developing shopping can applications in online shopping websites where items
selected by end user by generating multiple requests will be remembered.
3. To remember user identity during an e-commerce session.
4. To remember credit card/debit card details during a session while performing the web
based online transactions.
5. To remember player identity while playing online games.
ByteCode(IT Soluctions) Page 132
ByteCode(IT Soluction)

6. To remember customer identity while performing online stock trading


7. To remember end user choices and intrets towards look & appearance of web pages, if
website allows to customize the loolt and appearance of webpages.
8. To render direct advertisement in websites.

Point to Remember

The advertisement that comes based on the operations performed by end user in website is
called ―direct advertisement".

eg: if end user is searching for new 7 wonders in Googie search engine the Google website
displays direct advertisements talking about tours and travels.

ln session tracking, web application stores and remembers data across the multiple requests
only during a session. Once the session between client and web application ls completed the
web application forgets client‘s data. Storing client data in database table or in ServletContext
attributes across the multiple requests does not come under session tracking or session
management because they remember client data even after session completion and they do
not store data and specific to one client. '

What is the difference between session inanagenient/session tracking and state management?

Ans: In state management, web application remember client's data irrespective of the session
that is started and completed by using database table and ServletC0ntext attributes support. in
session 'management/tracklng, web application remember client's data only during the
session. Once session is completed this data will go off. For this hidden form fields, cookies,
Http session, url rewriting kind of session tracking techniques will be utilized.

The session started between browser and web application lS specific to each browser (client).
Multiple clients start multiple sessions with single web application on one per client basis.
Session and session related data always specific to one client. so only that client can use
session data across the multiple requests during that session.

Technque2 Http Cookies

Cookies are small textual informations which allocate memory at client side (client machine)
having the capability to remember client data across the multiple rgqdests during a session.
To work with cookies ' we need the protocol Http and the servlets of type
[Link]|[Link] travel over the network along with request and
response:

There are two tyes of cookies:

In memory/per session cookies

 No expiry time
 Allocates memory in the in ‗memory of browser
 Once browser window is closed, these cookies will be destroyed automatically

Persistent cookies

 Contains expiry time

ByteCode(IT Soluctions) Page 133


ByteCode(IT Soluction)

 Allocates memory in the files of client machine's file system


 Wili be destroyed automatically once expiry time is completed.
 Every cookie contains a name and allows one string value.
 Every cookie contains cookie id and also remembers the web application/domain
name for which it belongs to.
 Server side web components of web application create cookies and adds them to
response to send to client. So cookies allocate memory as String informations at client
side
 Cookies go back to web application along with the request from client (browser)
when browser gives request back to web application For which these cookies belong
to.
 Cookies come to client from server/web application along with the response ,as the
values of special response header called ―set-cookie".
 Cookies go back to the web application along with the request given by the browser,
as the values of special request header called "cookie". '
 At client side we can see multiple cookies belonging to different domain
Browser window CookeeApp2(Web application
[Link](Static form1 page)
FirstServlet
Name raja
Resquest 1 (2)
Father’s name fmadhu

continue SecoundServlet
Response 1

(6)
Inmemory cookies of

CokieApp name: madhu Writes


form1,form2
Fname:fmadh data
Resquest 5

Income of this year 100000 Database software

Tax: 2000 Response 8

Submit

Form data
madhu…fmadhu…Form2 data:
100000…2000

ByteCode(IT Soluctions) Page 134


ByteCode(IT Soluction)

With respact to the diagram

 The forml page gives request]. data to FlrstSenrlet Component of CookieApp2 web
application having forml/requestl data.
 Flrstservlet Component creates two In-memory cookies having forml/requestl data &
adds them to response.
 FirstServlet generates-response, having 2 inmemory cookies and form2 as dynamic
[Link] these lnmemory cookies becomes value of set-cookie response header.
 The two inmemory_cookies of response]. allocate memory in browser's In-memory
representing forml/requestl data and they also remember CookleApp2 as their domain
name/web application name
 Form2 genemtes request2 to the SecondServlet Component of CookieApp2 web
application. This request carries forml data and also carries the two cookie values of
CookieApp2 application [forml/requestl data) as the vaiues of requestHeader
"cookie".
 SecondServ|et reads form2/request2 data directly from request2 and also reads
forml/requestl data from the cookies of requestl That means SecondServIet
Component is able to use requestl/forml data while processing request2 (which ls
nothing but session tracking).
 Second Servlet Component writes forml/requestl data, form2/request2 data as record
to ndatabase table.
 SecondServlet Component generates dynamic web page having forml/requestl data
and form2/requestl data.

Cookie API (working with methods of ][Link] class)

To create cookig and to add them to responseln Servlet Component

1. Cookie ck1=new Cookie("ap",‖amaravathi");

//Cookie name must be String cookie value must be string

[Link](ck1),' //ckl acts as inmemary cookie

2. Cookie ck2=new Cookie("mh", "Mumbai"');

[Link](1800);

[Link](ck2);//ck2 is persistent cookie having 1800 secs as expiry


time

Every cookie must be added to response.

To modifi cookie value:

[Link]("hyd1");
[Link]("navi Mumbai");
To read cookie value
Cookie cks[]=[Link]();

ByteCode(IT Soluctions) Page 135


ByteCode(IT Soluction)

if(cks!=null)
{
for(Coakie ck:cks)
{
[Link]([Link]()+'--—-”+ck[].getValue())
}
)//if ——> gives op< --- > hyd
Mh< ----> Mumbai values
To delet cookies:

 We cannot delet cookies programmatically being form Servlet Components by using


Cookies API besause they allocate memory at client side.
 In memory cookies will be destroyed once browser window is close. Persistent cookis
will be destroyed once thrie expire time is reached or their related files are deleted or
modified explicity

To know maximum a e of cookies

inr time=[Link](); // -1 will come which is the default max age of inmemory
cookie

int time=[Link](); //1800 sec will come

To know domain name:

String s=[Link](),- //gives domain/web application name of cookie

String s=[Link]();

Note : [Link] is a direct concrete class.

ln yahoo, Gmail websites based login page there is a check box to remember username and
password in the computer. When that checkbox is selected It uses persistence cookies to
remember username and password on that computer.

Basic Example Agplication on Cookies:


[Link],

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;

public class SetCookies5ervIet extends HttpServlet {


public void doGet(HttpServIerRequest request,HttpServletResponse response)
throws ServletException,IOException {

ByteCode(IT Soluctions) Page 136


ByteCode(IT Soluction)

Cookie cookiel,cookie2,cookie3,cookie4;
// default maxage is -1, indicating cookie
//2 in-memery cookies applies only to current browsing session
cookie1 =new Cookiel "op ", "amaravathi ");
cookie2=new Cookie("ts"hyderabad");
[Link](cookiel);
[Link](cookie2);
// Cookie is valid for an hour, regardless of whether
//user quits browser, reboots computer or whatever
//2 persistent cookies
cookie3=new Cookie("kr", "Bangalore”);
cookie-==new Cookie("ml1", "mumbai");
[Link]-(3600);
[Link](3600);
[Link](cookie3);
[Link](cookie4);
//get PrinrWriter object
PrintWriter pw=[Link]();
[Link]("text/html");
[Link]{"Sucessful in setting cookies ");
[Link]( "Successful in setting cookies.... ");
}//doGet()
}//class
[Link]

// component to work with cookies


package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class ShowCookiesServlet extends HttpServlet {
public void doGet(HrtpServletRequest request,HttpServletResponse response)
throws Servletfxception,IOExceptlon {
[Link]("tex/htmI");
PrintWriter out=[Link]();
String title="Active cookies";
[Link]("<html> <head> <title>"+ title);
[Link]("</title> </head> <body>");
[Link]("<table border=1 align='center'>");
[Link]("<tr> <td> Cookie Nome</td>"),'
[Link]("<td> Cookie Value</td></tr>");
Cookie[] cks=[Link]();
if(cks!=null) {
for (Cookie ck:cks) {
[Link]("<tr><td>"+[Link]()+"</td>"
+"<td>"+[Link]()+"</td></tr> "); ,-
}//for

ByteCode(IT Soluctions) Page 137


ByteCode(IT Soluction)

[Link]("</tab/e></body></html>");
}//if
else {
[Link]("N0 cookies present.... ");
[Link]("<br><b>no cookies present..... ");
}//else
}//doGet()
}//class

ByteCode(IT Soluctions) Page 138

You might also like