Web Application Development Guide
Web Application Development Guide
Servlet INDEX
1. Need of Web applications
19. Load-on~stanup
The application that contains two layer/component interacting with each other is called two-
tier application.
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.
b) .Net
Use java-jee environment (servlet, jsp technologies) to develop large scale and
complex web application (more then 30 pages).
eg: about us page, terms and conditions page, contact us page, and etc...
The content of web page changes based on the time of request generation or
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.
Every web application is collection of multiple web componets and other files like
images, audio/video files, java script files and etc...
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.
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
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
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.
List of web server software (to manage and execute web applications)
Tomcatfrom apache (java).
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...
PHPfrom Apache
Aspfrom Microsoft
[Link]from Microsoft
List of DB software.
Oracle from Oracle corp.
PostgreSQLfrom EnterpriseDB
Note : mangoDB, couchBase ,NOSQL, SqlLite and etc.. are light weight DB software
b. Choose 1 or more client side web technologies to develop client side web components.
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?
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.
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.
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.
To download software[Link]
a) <JAVA_HOME>\Jre location
a) User<tomcat_home>\bin\[Link] file
|--->bin
|---->……exe([Link])
|--->conf
|------>*.xml([Link],[Link]…)
|----->logs
|------>*.txt
|------->lib
|------>*.jar(servlet-api jar,[Link], [Link] ,jasper jar..)
|---->webapps
|---->dir1,dir2…
|----->*.war
|------>Work
|------>
|------>temp
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
->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]).
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...
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 -
=>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 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.
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:
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.
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
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.
[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.
Every Servlet Component/components is a java class that uses servlet API. This must
implement
Approaches 1
Take a class implements [Link](1) and provide definition for all 5 method.
Approach2 .
Service(-,-) methods.
Note. Not a recommended approach because it does not allow programming to work with
protocol htttp features like enabling auto refresh on webpage
Approach3:
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.
--------------
-------
First lava web application development as Servlet Component as the web component
1 request
Dynamic web page DateApp
2
DateServlet(Servlet)
Display date
5 response
and time
(3)
4
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...
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
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.
Value: D:\Tomcat9.0\|ib\[Link];.
0k(3).
E:\DateApp\WEB-INF\classes>javac -d . [Link]
<web-app>
<servIet>
</servlet>
<servlet-mapplng>
<servlet-name>date</servlet-name>
</servlet-mapping„;
</web-app>
Note To test whether [Link] file is correct file or not press ctrI+b in edit plus.
http: protocol
/Test1 url-pattern
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]
For Reloading:
I -----—~>Manager app------>
username; admin
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){
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
Req,res objectects
T1 dataServlet
Req,res objectects
Browser (b3)
T3
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
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
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.
|----------->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)
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. ‗
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
App2: Develop web application having multiple servlet and generating different MIME
types based web pages.
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]. *;
Servletfxcepfion, IOExceprion
// getPrintWriter
Printwriter pw=[Link]();
[Link]{ "text/htmI");
[Link]("<tabIe border='1„>“);
[Link]( "<tr><th>Player</th><th>Role</th></tr>");
[Link]{"<tr><td>$achin</td><td>AIl Raunder</td></tr>");
[Link](”</tabIe>");
//close stream
[Link]();
}//service(-,-)
}//class
-----—--———----—-—-[Link]------------------
//[Link]
package [Link];
import [Link].*;
import ][Link].*;
import [Link]. *;
// gerPrintWriter object
[Link]("application/msword");
[Link]("<tabIe border='0'>");
[Link]("<tr><th>Player</th><th>RoIe</th></tr>");
[Link]"<tr><td>Sachin</td><td>AlI Rounder</td></tr>");
[Link]("</table>"); ;_
[Link]();
)//service(-,-)
)//class
-------------[Link]-------------
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
// getPrintWriter object
PrintWriter pw=[Link]();
[Link]("text/xml ");
[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>");
[Link]();
}//service(~,-)
)//class
//[Link]
package [Link];
import [Link].*;
import [Link].*;
import [Link]. *;
ServletException, IOException
// getPrintWriter object
Prinrwriter pw=[Link]();
[Link]("application/[Link]-excel");
[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>”);
[Link]();
}//service(-,-)
}//class
Note:
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.
E:/MIMEApp/WEB-INF/cIasses>javac –d * java
<[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: 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.
E:/MIMEApp/WEB-INF/cIasses>javac —d . *.java
<[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>
<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>
Good morning
|---------->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.
import [Link].*;
import [Link].*;
[Link].*;
import [Link]*;
PrintWriter pw=null;
Calendar calendar=null;
int hour=0;
//Genaral Settings
pw = [Link]();
[Link](“text/html”);
calendar = [Link]();
'hour = [Link](Calendar.HOUR_OF_DAY);
if(n<=12)
else if(h<=17)
else if (h<=20)
else
[Link]("<br>><a href='[Link] );
[Link]();
//service(-,-)
//class
wé[Link]
<servlet>
<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> . ,
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.
a) GET mode:
Can carry limited amount of data along with the request (12kb-8kb)
POST mode:
ServletException,IOException
[Link] VoterAp
p
Name
VoterServlet
(2)
Age
(3)
Check
(1) (4)
voting
...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].*;
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>
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?
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)
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
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
-----------------
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);
}
}//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:
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
Eg:
processGet(req,res);
processPost(req,res);
Conclusion:
We can configure Servlet Component /jsp component/html file as the welcome file in
[Link]
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 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.
<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.
=>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:
(1) CountryApp
country India
(2)
Australia Us Country Servlet
(3)
Dynamic web page (4)
New Delhi
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
Submit
Reset
And etc...
Text box:
In form page:
In Servlet Component:
String s = [Link](”tname");
Password box:
In form page:
In Servlet Component:
Text area:
In form page:
In Servlet Component:
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:
In Servlet Component:
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.
In form page
In Scrvlet Component:
Multiple checkboxes:
In form page:
In Servlet Component;
hobbies[] contains 3 values in elements, if all the 3 check boxes are selected.
Hidden box:
In form page:
In Servlet Component:
String s1 = [Link]("'h1");
Select box/combobax/choicebox;
In form page:
</select>
In Servlet Component:
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:
In Servlet Component:
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:
</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>
</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];
Int age=0;
PrintWriter pw=null;
pw=[Link]‟);
[Link]("text/html");
age =[Link]([Link]("tage”));
ms=[Link]("ms ");
addrs=[Link]("taddress");
qlfy=[Link]("qlfy”)
hb[]=[Link]("hb");
if(gender. equalsIgnoreCase("M")) ;
{ if(age<=5)
else if(age<=12)
else if(age<=l9)
else if(age<=35)
else if(age<=50);
else
else if([Link]("F"))
if(age<=5)
else if (age<=12)
else if(age<=50)
[Link](“<br>name=”+name);
[Link]("<br>age= "+age);
[Link](“<br>Gender= "+gender);
[Link]("<br> Qualification="+qlfy);
[Link]("<br> Hobies"+[Link](crs));
[Link]("<br> Hobies"+[Link](hb));
doGet( request,responsej;
}//class
Widow menu—) preferences-) server-) runtime environment ----->add ---> apache tomcat 9
Stpe3: create dynamic web project in eclipse IDE having name form app
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.
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
->This hyperlink does not carry data along with the 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.
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>
fr-FR
de-DE
Local locales[]=[Link]()
Returns [Link] class object array having all the locales of this world.
Locales[]
Locale
0
Locale 1
Locale 2
<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>
//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
Browser
[Link]
Web server
request
Value1
ProcessApp
Value2
(1)
S1 S1 ProcessServlet
S1 (2)
=>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]
Example Application
[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
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.
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
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
=>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.
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.
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
What happens when Servlet Component gets then 1" request from browser?
Servlet Container creates one set of ServletRequest, ServletResponse objects for current
request.
If available, Servlet Container locates that object and performs e toi steps of 1st request.
//[Link]
package [Link];
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
[Link]("LcTestServlet:static block");
System,[Link](LcTestServlet: init(ServletConfig) );
[Link](“LcTestServlet:service(-,-)‟);
[Link](“text/html”);
PrintWriter pw=[Link]();
// write response
//close stream
[Link]();
//service(-,-)
[Link]("LcTestServlet:destroy()");
//class
}//destroy()
<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>
</servlet-mapping>
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.
Servlet instantiation(0-
param constructor)
Servlet instantiation
(init(-) method)
response
Service(-,-) request processing
Servlet uninitailization
destroy()
Servlet desinstantition
garbage calector
end
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>
if <load-on-startup>is enable.
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
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
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.
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.
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.
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.
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:
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
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
………….
}
}
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
->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".
Approach 1:
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.
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.
=>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]();
}
}//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.
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.
weblogic <weblogic_home>\user_project
\domoins\<domain name>\lib
folder
Glashfish <Glassfish_horne>\dornian
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).
To perform dynamic request response of web components like servlet filter and
etc (servlet 3.0)
Ans: 10-3 = 7.
Ans: 10
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.
//use cg
ServletConfig cg = getServletConfig();
A) ServletConfig cg = getServletConflg():
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:
[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();
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:
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
String s1 = [Link]("dbuser―);
Approach
while([Link]()){
[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.
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>
ServletContext sc = getServletContext();
String s1 = [Link]("dbuser‖);
Example Application:
[Link]
<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>
</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()
{
}//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.
Approch1:
String s1 = [Link]("dbuser‖);
Approach 1
while([Link]()){
[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.
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.
ServletContext sc=getServletContext();
ByteCode(IT Soluctions) Page 78
ByteCode(IT Soluction)
// Tomcat 9.0
//3.1
// D:\Tomcat 8.0\webapps\DBApp
// D.-\Tomcat 8.0\webapps\DBApp\[Link]
//text/html
//(catlina/localhost)(4.0)
Glassfish
[Link](JavaBean)
……
}
[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
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]
DTO class
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
……
….
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
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
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
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.
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 .
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]
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;
[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];
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 ");
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]
<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
Jboss:
Type. Application server software
Click on <jboss_home>\bin\[Link]
Username: jbossuser
Password: userjboss
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]
Using
Using Hyperlink
[Link]()
res
res res res
d
Forwarding request
Including response
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
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
In source servlet
RequestDispatch rd = [Link](“/s2url”);
[Link]([Link]);
Or
[Link]([Link]);
In source servlet:
ServletContext sc =getServletContext();
RequestDispatch rd = [Link](“s2”);
[Link]([Link]); or
[Link]([Link]);
In source servlet:
ServletContext sc =getServletContext();
RequestDispatcher rd = [Link](“s2”);
[Link]([Link]); or |--->Logical name of
dests Servlet comp
[Link]([Link]);
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)
Key points:
ByteCode(IT Soluctions) Page 93
ByteCode(IT Soluction)
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.
[Link]
try{
catch(Exception e){
RequestDispatcher rd=[Link]("/eurl");
[Link]([Link]);
}//doGet(-,-)
doGet(req,res);
)//class
……….
}//class
Important points:
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.
Important points
Understanding [Link](-,-)
Servlet 1(Source)
browser
Request (1) rd=[Link](“/s2url”);
……..
……[Link](-,-); Servlet 2(Dest)
(2)
3
Response (7)
(4)
Problem
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.
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)
DBApp2
|—>java resources
|---->src
|---->[Link]
|--~>[Link]
|-—>[Link]
| ---->[Link]
|——>web content
|--->WEB-INF
|-->[Link]|
|-->[Link]
| --->[Link]
[Link]
<br><br><br><br><br>
<b><i><center> © All rights reserved </center></i></b>
[Link]
package [Link]
import [Link];
import [Link];
impart [Link];
import [Link];
import [Link];
//general settings
[Link]("text/html");
PrinrWriter pw=[Link]();
ServletException,IOException{
}/,/[Link]
doGet(req,res);
}//class
[Link]
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
Connection con;
PreparedStatement ps;
String driver=null,dbser=null,dbpwdpwd=null;
try{
ServletContext sc=getServletContext();
driver=[Link](“driver”);
url=[Link](“url”);
dbuser=[Link](“dbser”);
dbwd=[Link](“dbwd”);
[Link](driver);
con=[Link](url,dbuser,dbpwd);
ps=[Link](GET_EMP_DETAILS_BY_NO);
}//try
catch(CIassNotFoundException cnf){
[Link]();
catch(SQLException se){
[Link]();
catch(Exception e){
[Link]();
}//init)
throws Servletfxception,IOException
PrintWriter pw=null;
int no=0;
ResultSet rs=null;
RequestDispatcher rd=null,rd1=null,rd2=null;
try{
. rd1 =[Link]("/headurl);
[Link](req,res);
pw=[Link]();
[Link](“text/html“);
no=[Link]([Link](“teno"));
[Link](1,no);
rs=[Link]();
if([Link]()){
[Link]("<br>Emp no:“+[Link](1));
[Link]("<br>Emp name:”+[Link](2));
}//if
else{
//add hyperlink
rd2=[Link](“/[Link] ");
[Link]();
//close stream
[Link]();
}//try
catch(Exception e){
[Link](req,res);
}//doGet(-,-)
doGet(req, res);
try{
if(ps!=nuIl){
[Link]();
cutch(SQLException se){
[Link](),
try{
if(con!=null){
[Link]();
}//try
[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];
[Link]{ "ErrorServlet:doGet(-,-)");
[Link](req,res); */
// general settings
PrintWriter pw=[Link]();
[Link]("text/htmI");
//close stream
[Link]();
ServletException, IOException{
[Link]("ErrorServlet:doPost(-,-)");
. doGet(req,res);
}//class
-[Link].
<web-app>
<welcome-file-list>
< welcome-fiIe>[Link]</welcome-file>
</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>
[Link](-,-) [Link](-,-)
lmportant Points:
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.
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:
[Link]
</form>
[Link]
package [Link];
import [Link];
impart [Link];
import [Link];
import [Link];
Import [Link];
Import [Link];
import [Link];
@Override
//general settings
PrinrWriter pw=[Link]();
[Link]("text/html ");
//readform data
int val=[Link]([Link]("t1"));
int square=val*vol;
[Link]("<br>FirstServlet:SQuare :"+square),
ServletContext sc1=getServletContext();
ServIetContext sc2=[Link]("/WATwo");
RequestDispatcher rd=[Link]("/s2urI");
[Link](req,res);
//close stream
[Link]();
}//doGet(-,-)
@Overrid
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];
import [Link];
import [Link];
import [Link];
@Override
//General setting
PrintWriter pw=[Link]();
[Link](“text/html”);
Int val=[Link]([Link](“t1”));
Int cube=val*val*val;
//display
[Link]("SecondServlet:Cubevalue "+cube);
}//d0Get(-)
@Override
[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
Limitations on RequestDispatching(Requestdispatcer);
Sending Redirection:
Using hyperlink
Using [Link](-) method.
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.
(2)
[Link]([Link]
Dynamic webpage
WebServer2/AppServer2
(web logic)WA2(web
(6)final applicaton)servlet(Dost)
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:
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.
Eg:
In Servlet1:
In Servlet2:
String sl = [Link](‖sno");
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]
Search
………(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]
[Link]
</form>
[Link]
package [Link];
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
@Override
String ss=null;
String engine=null;
String urI=null; . -
//readform data
ss=[Link]("ss”);
engine=[Link]( "engine");
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]
[Link](url);
RequestDispatcher rd=[Link](“[Link]”);
[Link](req,res);
[Link](“After SearchServlet:sendRedrirct(-)”);
}//doGet(-,-)
@override
goGet(req,res);
[Link]—
<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>
[Link]:-
Example Application
Using [Link](-) method to get interaction b/w web resourse prgs of two diff server
(tomcat,web logic)
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)
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
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>
[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
{
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”):
Important points:
[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.
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.
Name: Raaj
Age: 23
Marital Status:
Spouse Name:
No. of Childern:
Submit
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
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. -
[Link]
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]
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class Servletl extends HttpServlet
{
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.
Browser window
Age 23
continue
Response 1
Submit
When to marry:
Why to marry:
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). -‗ ‗
[Link]
package [Link];
import [Link].*;
Import [Link].*;
// general code
PrintWriter pw=[Link]();
[Link]("text/html");
String pname=[Link]("tname”);
String pname=[Link]("tfname");
String pms=[Link]("ms”);
if([Link]("single“))
[Link]("</form>");
else{
[Link]("</f0rm>");
[Link]();
}//doGet(-,-)
daGet(req,res);
}//class
[Link]
//[Link]
package [Link];
import [Link].*;
[Link].*;
import [Link].*;
import [Link].*;
// general code
PrintWriter pw=[Link]();
[Link]("text/html”);
String ms=[Link]("hms");
ByteCode(IT Soluctions) Page 130
ByteCode(IT Soluction)
// readform2/request2 datb
try
[Link]( "[Link]");
Connection
con=[Link](“[Link]:@lacalhost:1521:xe","scott",
"tiger");
[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
}//try
catch(Exception e)
[Link]();
[Link]();
}//doGet(-,-)
daGet(req,res);
}//class
Advanggges and disadvantages of hidden form fields based session tracking technique:
Advantages
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.,
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.
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.
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:
No expiry time
Allocates memory in the in ‗memory of browser
Once browser window is closed, these cookies will be destroyed automatically
Persistent cookies
continue SecoundServlet
Response 1
(6)
Inmemory cookies of
Submit
Form data
madhu…fmadhu…Form2 data:
100000…2000
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.
[Link](1800);
[Link]("hyd1");
[Link]("navi Mumbai");
To read cookie value
Cookie cks[]=[Link]();
if(cks!=null)
{
for(Coakie ck:cks)
{
[Link]([Link]()+'--—-”+ck[].getValue())
}
)//if ——> gives op< --- > hyd
Mh< ----> Mumbai values
To delet cookies:
inr time=[Link](); // -1 will come which is the default max age of inmemory
cookie
String s=[Link]();
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.
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
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]
[Link]("</tab/e></body></html>");
}//if
else {
[Link]("N0 cookies present.... ");
[Link]("<br><b>no cookies present..... ");
}//else
}//doGet()
}//class