Vous êtes sur la page 1sur 148

2015-04-10

Normal java application will be executed manually from command


prompts. Whenever there is a need.
The web resource program of web application will be executed by web
server software dynamically whenever request is given to those web
resource programs. From client nothing but browser window, this
indicates web resource programs will not be executed manually they
will be executed dynamically by webserver software like tomcat.

Web server s/w automates web application and its web resource
program execution.
It listens to client request passes them to web resource program
execute web resource program gather output form web resource
program sends that output to client (browsers) as response in the
form of web pages.
E.g. Tomcat, IIS, AWS AND etc.
IIS-internet information service
AWS Apache web server

The process of keeping developed web application in web server is


called deployment and reverse is called un-deployment.

With
respect to
diagram
(1) Browser
gives
request to web application
(2) Webserver listen client requests continuously take the request and
passes the request to appropriate web resource program (like servlet
program)
(3) The web resource program in web application executes
dynamically
(4) If needed, the web resource program interacts with database s/w.
(5) The output generated by the web resources programs gives to web
server.
(6) Webserver sends output to browser as response in the form of web
page.
In one web application we can have one or more web resource
program.
In one web application we can deployed one or more web
application (web sites)

We can develop web application as two tier application( without


database software or as three tier application (with database s/w)
When web application developed as two tier application it looks
like thin client-fat server application

2015-04-13
Based on content they generate there are two types of web resource
1. Static web resource programs(Generate static web program)
2. Dynamic web resource program (generate dynamic web program)
Based on the place where web resource program execute there are two
types of web resource program
1. Server side web resource program
These program executes in web server itself when request is given
Eg servlet program, jsp program end etc.
2. Client side web resource program
These programs go to browser window from web server for execution
when requested.
Eg- html program, javascript program and etc.

Note: Generally all dynamic web resource programs are server side web
resource program and static web resource program are client side web
resource program.
Note: Decide whether web resource program are server side or not
based on the location where they execute, not based on the location
where they reside.
List of browser s/w
IE from micro soft
Navigator --> Netscape
Safari -Apple
Firefox Mozilla
Hot Java Red Hat
Chromefrom Google (1)
Opera from Opera soft
List of server side web technology to develop server side web resource
program
Servlets From sun Ms(oracle corp) (java)(1)
Jsp From sun Ms(oracle corp) (java)(2)
(Non-java)
Asp----from Microsoft
Asp.net - from Microsoft (3)
Asp.net MVC-from Microsoft (2)
SSJS----------from Netscape (server side java script)

PHP--------from Apache (4)


ColdFusion----- from Adobe.

List of client side technology ( to develop client side web resource


programs)
Html from W3C
Java scriptfrom Netscape + sun Ms
VB script from Micro Soft
Ajax -- from Adaptive path
Jquery
DOJO
AngularJS
And etc
List of Webserver s/ws
Tomcat ---------- from Apache (java) (1)
JWS ------------ from Sun microsystem (java)
Resin---------- from Resin soft (java) (4)
Jetty---------- from Adobe (java)
IIS --------From Microsoft (non-java)(2)
PWS---------from Microsoft (non- java)
AWS------- from Apache (non-java) (3)
NFTS(Netscape first track server) from Netscape
Etc
List of Application server software

It is enhancement of web server software.


Weblogic--from BEA systems (oracle corporation) (1)
Websphere -- form IBM(3)
GlassFish --- from sun Microsoft(2)
Jboss----- from Apache(RedHat)(4)
Oracle10g IAS -- from Oracle Corporation
Jrun----------from Adobe
PAS-------- FROM Pramathi soft
(PAS:Pramathi Application server)
List of DB s/w
Oracle ---- from oracle corporation
DB2-----from IBM
SQL Serverfrom Micro Soft
Post greSQLEnterprise DB
Mysql-devx (sunms) (oracle oracle)

2015-04-14
To execute applet we need applet program we need applet viewer or
applet container.

To execute html program we need html interpreter.

To execute servlet program we need servlet container

To execute jsp program we need jsp container.

Both servlet container and jsp container internally uses


jvm/jre.

Applet viewer also internally uses jvm/jre.

Every servlet program is a java class having code to process


request and to generate response.

We need not to arrange servlet container separately, they


come automatically along with web server s/w installation
(java based)

What is container?

Container is s/w program /application that takes care of whole


life cycle of given resource (birth to death) (object creation to
object destruction)

Servlet container takes care of servlet program life cycle and


jsp container takes care of jsp program life cycle.

Container is like aquarium taking care of the whole life cycle


of given fishes.

(web resource programs)

The additional, optional and configurable (allows enabling or


disabling) logics on our apps to make our application more
perfect are called middleware services. These are not main

logics in application development. These are additional and


optional logics to apply on our applications..

When servlet program is requested it goes to servlet container


for execution.

jsp container internally uses the support of servlet container

Tomcat
Type: java based web server.
Version :8.x(compatible with jdk 1.7+)
7.x (compatible with jdk 1.6+)
Vendor: Apache
Open source s/w (free ware)
Default port no: 8080
Creator : Mr. David Doncuson
Servlet container: CATALINA
Jsp container: JASPER
To download s/w apache-tomcat-7.8.exe from www.apache.org

2015-04-15
While installing Tomcat server we need to supply the following details;
a) Jre location <The one that is parallel to jdk.>
b) http port no:2525 (default 8080)
c) Tomcat installation folder:D:\Tomcat8.0(<tomcat_home>)
d) Administration details: UserName: admin
Password: admin
Note: install in other than c:
To start Tomcat Server:

Go<Tomcat_home>\bin directory use tomcat8.exe file


When server is started one daemon process will be created listening to
client request continuously.
To see home page of Tomcat
In browser window type url
Http://localhost:2525 (host name and port no of tomcat)
To Change port number of Tomcat after installation
Go TO <Tomcat_home>\conf\server.xml file and modify the port
attribute value of first <connector> tag and restart the server.
Understanding installation Directories of Tomcat
D:\Tomcat8.0
|-bin

|*.exe (tomcat8.exe), *.bat (startup.bat ,shutdown.bat)


|conf
|-*,xml(server.xml( server.xml, tomcat-users.xml,.)
|lib
|-*.jar(servlet-api.jar, jsp-api.jar, catalina.jar, jasper.jar,.)
|-logs
|*.txt files
|webapps
|dir1, dir2,.
|*.war files
|temp
|misc files
To deploy all java web application in tomcat server we can place them
in <Tomcat_home> \webapps folder either in the form of directors or
war files.
War files: web application archieve.
<Tomcat_home> \lib\servlet_api.jar represents servlet api (pkgs)

Jsp_api.jar represents jsp api (pkgs)

Catalinar.jar represents (servlet container)

Jasper.jar represents (jsp container)

Web container = servlet container + jsp container..

Responsibilities of web server


Takes request from client by listening client request continuously for
this it start Daemon process.

Passes the request to container for request processing


Provides containers (like servlet/jsp containers) to execute server side
program.
Provides middleware services(like security)
Provides environment to automate. The web application and its web
resource program execution.

Provides environment to deploy, un-deploy, start, stop and reload web


application.
Takes results from container and sends them to browser window as
responses.
Sends the code of client side web resource program to browser window
for execution and etc

Responsibility of containers: Takes request form web server and executes server side web
resource program dynamically.
Takes care of server side porg life cycle birth to death.
Takes care of communication between web resource progs.
Performs various activities related to request handling and response
generation.

Type of containers

url, uri,urn

2015-04-16
Servlet, jsp, ejb, jms and etc jee module technologies.
Technology is not installable s/w because they just give rules and

guideline to develop s/w. These s/w are installable working with these
s/w are nothing but working with technology.
Web server /application server s/ws are given based on jee technologies

Installing.
This server s/w and working with these server s/w is nothing but

working with JEE module.


Eg. Installing tomcat, web logic s/w and using them is nothing but
JEE module
Based on the technology we use there are following container:

a) Servlet container:Based on Servlet Technology


b) Jsp container: Based on JSp technology.
c) EJB container Based on EBJ Technology.

Based on physical existence of container with respect to server there are


3 type of containers
a) Standalone container
Here server and container together comes as single piece of program
b) In-Process container :

Here container inside the server as separate piece of code Servlet


container /jsp container of Tomcat Server is called In-Process
container.
c) Out-Process container:
Here container resides outside server but will be attached to server
externally the servlet /jsp container attached with IIS server
externally is called Out-Process container.

Thread is a sub-process or light weight process.

Transferring control between process or threads through scheduling is

called context switching or control jumping this takes more time for
process and less time for threads.
When we start the execution of java application one process will be

started having two default threads (main thread, garbage collector


thread).

Server side web technologies

If multiple request given to servlet program (thread based server side


technology ) then the servlet container creates only one object of our
servlet class but starts multiple threads on that object for multiple
request since control jumping between thread takes less time the
performance of web application will be good even though number of
request are increase or decrease this makes our web application as
scalable

2015-04-17
Definition of servlet
1. Servlet is java based server side web technology to develop dynamic web
resource program or component having capability to generate dynamic
web pages.
2. Servlet is java based web technology whose web resource program can
extend the functionality of web server or Http server.
3. Servlet is java based technology that allows to develop single instance
multiple threads based server side web component in java web application
having the capability to generate dynamic web pages(Refer pervious
diagram)
4. Servlet is a JEE module technology/specification that gives api for vendor
companies as rules and guideline to develop servlet container s/w (part of
webserver s/w) and also gives same api for programmer to develop server
side/dynamic web resource program in java web applications
Note: Every Servlet program is java class using api. The whole life cycle of
this java class will be taken care by Servlet Container birth (object creation)
to Death(object destruction))
For various features of servlet refer page no:- 80,82
For basic of servlet container refer page 76 to 82.

Portability
(java applications are WORA (write once run anywhere (any
platform)
Java web application are WODA (write once deploy anywhere (any
java server)
Powerful

Efficiency
Reliable
Safety
Integration
Inexpensive
Extensibility
Every technology gives one api. The servlet technology api versions are

servlet 2.3,2.4, 3.0,3.1.


In java api comes in the forms of packages having classes interfaces,

enum(special class), annotations(special interface) and etc


Servlet api 2.5 pkgs.

javax.servlet,
javax.servlet.http,.
Servlet api 3.x pakgs

Javax.servlet,
javax.servlet.http,
javax.servlet.annotations,
Javax.servlet.descriptor,

In tomcat server <Tomcat_home>\lib\lib\servlet-api.jar file

represents servlet API.


Three import re

2015-04-17
There are three way to develop servlet component/program.
Approach-1) Take a class implementing javax.servlet.Servlet(I) and

provide implementation for all the 5 methods of that interface.


Limitation: Providing implementation to 5 methods even though
there is no need is always complex.

In our servlet class we place logic to process request and logic to


generate response in the service(-,-) method. This response goes to
browser window as webpage.
Approach-2) take class extending from

javax.servlet.GenericServlet(AC) and provide implementation for


service(-,-) method.

Limitation: We cannot work with all the features of protocol http


because GenericServlet is not any specific protocol.
GenericServlet allows to work with all protocols but does not allow
to use any protocol for 100%.
Approach-3) Take a class extending from

javax.servlet.http.HttpServelt(AC) and override 1 of the 7 doxxx(-,-)


methods and 1 of 2 service(-,-) methods.

Note: this best approach to develop servlet prog because it allows to


us to use all the features of protocol http.
Servlet container recognized as java pro as servlet porg only when it

implments javax.servlet.Servlet(I) directly or indirectly.

How many type of servlets ?


There is possibility of developing n types of servlets like Http servlet,

ftp servlet, smtp servlet and etc.but we prefer developing servlet as


http servlet because entire web/internet and server are designed based
on protocol http.
GenericServlet is not a separate type of servlet. It is a common super

class multiple protocol specific servlet classes. As of now there is only


sub class for GenericServlet that is HttpServlet.

Web application is collection of web resource prog like servlet, jsp,


html prog having capability to generate web pages. Web application
also contain some helper resources like image, audio, video files and
etc.. These programs cannot generate web pages but they help other
program towards generating web pages.

Jvm beings application execution with main method so we place main

method in java application.


Servlet

container executes our servlet program. This container

call service(-,-) method of servlet prog to process the request, so


we place service(-,-) method in servlet program having request

processing logic and response generation logic.


first java web application Development having Servlet prog as web resource
program.

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

Step-1) Create Deployment directory structure of web application.

This Deployment directory structure is packing mechanism of keeping

web resource prgs in java web application.


This structure is common in all server and not specific any server. This

is designed by sun ms as part of server specific, so all server recognizes


the directory structure based web application deployment.
The web

root folder name is user defined, after deployment this

name is become name of the web application.


Step-2) develop the servlet prog(DateSrv.java)
*************pmd plugin************
Vikash.bitcs@gmal.com

2015-04-10
Our servlet class(DateSrv) hierarchy is javax.servlet.Servlet Interface

javax.servlet.Servlet
^
| implements
Javax.servlet.GenericServlet(AC)

^
| extends
Com.nt.DateSrv(c )
Our servlet program class must be taken as public to make our class

ready for instantiation through SevletContainer because only public


classes are visible outside the container.
Servlet container create object of our servlet class and calls service

methods on that object to process the request.


For every request given to servlet program servlet container create one

additional set of object request, response object and these objects are
visible in our servlet porg as the parameter service(-,-) methods.
In service(-,-) method we use request object to gather data that comes

along with the browser generated request and response object is useful
to send output to browser through web server.
Res.setConentType(text/html) gives instruction to browser through

web server to display received contend as html code based text


document.(webpage)
PrintWriter pw=res.getWriter(); use access to PrintWriter object that is

there in response object i.e we get PrintWriter stream objet that points
to response object to destination.

Pw.println(<b> Hello<b>);
This method writes given msg(<b> hello<b>) to response object,

response object writes that msessage to webserver. Webserver writes


this message to browser as the content of webpage.
pw.close() closes the PrintWriter Stream that mean we cannot write

further content to response object form servlet program. This is


nothing but committing the response.
Step:3) our servlet program is using servlet api, But is not part of jdk.
Tomcat server gives servlet-api.jar having servlet api, so add that file
to classpath.
Mycomputerpropertiesadv systemsettingenv
variablesuser/system variable variable name
Variable name=classpath
value: D:\Tomcat 8.0\lib\servlet-api.jar;.
(ok)
Step:4)compile the servlet prog (DatSrv.java)
E:\Javaprogramming\ServletN\DateApp\WEB-INF\classes
Step:5) configure servelt prog in web.xml file
Passing details of servlet program in web.xml file to make servlet
container recognizing ther servlet prog is called servlet pro
configuration. Based this cfg only servlet container locates servlet
prg that is there in WEB-INF\classes folder of web application.
<web-app>
<servlet>

<Servlet-name>abc</servlet-name>--abc is logical name

<servlet-class>com.nt.DateSrv</servlet-class>--

com.nt.DateSrv is fully --qualified name acting serlet


programming
</servlet>

<servlet-mapping>
<servlet-name>abc</servlet-name>--abc must match with

above

</servlet-mapping>

</web-app>

--every servlet programmg is identified with its url-pattern to


generate --request

--it is not identified with its logical name or its real class name
-- all the servlet prog web application must be cfg in web.xml
file so it is called web application cfg file.

-- the moment we deploy web application in webserver the servlet


container reads the web.xml file, so it is also called deployment
descriptor file(DD file)
Step6) start tomcat web server
User<Tomcat8.0_home>\bin\tomcat8.exe file

Step7) deploy the web application (DateApp)


Copy e:\DateApp folder to <Tomcat_home>\web app
Step8) talks about deployment of web application
Step9) Test the web application
Request url in browser window: http://localhost:3030/DateApp/test1

<url-pa

Htttp: is protocol.
localhost:3030 host name and port name
test1 is url pattern of servlet

2015-04-22
The modification done in servlet program of deployed web application

will be reflected only after recompilation of servlet prog and reloading


of web application.
For recomplication
D:\Tomcat8.0\web apps\DateApp\WEB-INF\classes>javac d .
DatgeSrv.java
For reloading
<Tomcat_home>page-Manager appusername:admin and
password:adminsubmit
Tomcat web application manager windowDateAppreload
The message of system.out.println(_) goes to server console as log

messages/confirmation messages.
The messages of pw.println() goes to browser window as the content of

web page.
ServletContainer instantiate our servlet prog calss obj by using 0-

param constructor so we must make sure that 0-parameter constructor


is available in our servlet porg directly(*1) or indirectly(*2).

*1 placed by the programmer manually.


*2Defaut 0-parameter constructor generated by the javac compiler

implicitly.
Can we place only parameterized constructor in our servlet class?
As) NO
Because ServletContainer creates our servlet class object using
0_paramer constructor.

With respect to diagram.


1) Programmer deploys Dateapp web application in Tomcat webserver
2) The ServletContainer of Tomcat reads, verifies web.xml file and stores the
content of web.xml at RAM level in HashMap as in-memory
MetaData.(The information like servlet program details and other more
details.)
3) End user gives request to servlet program by typing request url in the
browser address bar.
4) Based on localhost:3030 of request url the request goes to Tomcat
server.
5) Based on DateApp of request url the Tomcat passes the request to the
deployed DateApp web application.
6) Based on /test1 of request url the servlet container gets logical name
(abc), class name(com.nt.DateSrv) from in memory MetaData.
7) ServletContainer create 1 set of request, response object for current
request.
8) ServletContainer loads com.nt.DateSrv class from WEB-INF\classes
folder for object creation and completes all initialization formalaties.
9) ServletContainer calls service(-,-) on DateSrc class object having req, res
object as the arguments.
10) Service(-,-) processes the reque4st and sends the generated output to
browser as response through web server to display in the form dynamic web
page.
-> servlet program is not identified with its class name because if class name is
exposed in request url that make idea to hackers regarding the technology used

in web site development.


To avoid this problem url pattern is introduced to hide servlet class name from
end users. This also gives chance to have multiple url pattern one servlet
program. (Palce multiple <url-pattern> tags under <servlet-mapping> tage for
this)
Example:
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/nit.c</url-pattern>

<url-pattern>/abc/xyz/nit.cpp</url-pattern>

Requested urls: http://localhost:3030/DateApp/nit.c

http://localhost:3030/DateApp/abc/xyz/nit.cpp

2015-04-23
Fgdgfd
The modification done in web.xml file will be recognized by

understanding servlet container automatically because it internally


reloads the web application.
When server stopped or when web application is stopped/reloaded all

the existing object ( our servlet class object, request, response) object
and etc) will be destroyed.
Reloading web application is nothing but (stopping web application

)+(starting web application)

our porg is single instance multiple threads component that is if our

servlet prog get 10 requests from same or different clients (browser


windows) then
a) Servlet Container creates only object of our servlet prog class.
b) Servlet container creates 10 threads representing 10 request on our
servlet class object.
c) Servlet container creates 10 sets of request, response object for 10
responses on 1 set per request basis.

To demonstrate above diagram practically place following code in

service method of servlet program in as shown below.


try{
}

Thread.

catch(Exception e)
{
}

pw.println("<br>hascode of request obj"+req.hashCode());

e.printS

pw.println("<br>hascode of response obj"+res.hashCode());


pw.println("<br>hascode of our servlet class
object"+this.hashCode());

pw.println("<br>hascode of current thread


obj"+Thread.currentThread.hashCode());

For every object jvm gives one unique value that is hashcode. To get

this hashcode value use objref.hashCode() (method belong to


java.lang.Object class)
For every request given to web resource program the servlet container

creates 1 thread and 1 set of request, response objects represent that


request and same will be destroyed once request related response goes
to browser from server.
In some servers if more (huge) request are given to servlet program the

servlet container may create more than one object to our servlet
container.( it is exceptional case.)

Javax.servlet.ServletRequest(I)
extends

Javax.servlet.http.httpServletRequest(I)

Javax.servlet.ServletResponse(I)

extends
Javax.servlet.httpServletResponse(I)
Q) How can we say request, response are objects when ServletRequest,
ServletResponse are interface?
Ans) _ request object means it is the object of underlying servlet container
supplied java class that implements javax.servelt.ServletRequest(I) directly or
indirectly.
response object means it is the object of underlying servlet container supplied by
java that implements javax.servlet.ServletResponse(I) directly or indirectly.
Programmers nerve expose these the class name of these objects in

their Servlet porg because the class names changes server to server or
container to container. This helps to develop servlet program as server
independent program(portable program)
Tomcat server request object class name

org.apache.catalina.connector.RequestFacade
And response object class name
org.apache.catalina.connector.ResponseFacade
Refer- <Tomcat_home>/lib/catalina.jar file

2015-04-24
Generic servlet gives only service method that is

public void service(servletRequest req, ServeltRespose res) throws SE ,


IOException
HttpServlet gives two method(-,-) methods

1st service(-,-) |public service (-,-) mehtods


2nd service(-,-) |protected service (-,-) methods
protected void service(HttpServletRequest req, HttpServletResponse res)

thrwos SE, IOException


ServletRequest and ServletResponse obj dont allow to use protocol

http features.
HttpServletRequest and HttpServletResponse object allow to use

protocol http feature.


If web application contains multiple servlet programs we must have

those entire prog web.xml file having unique url pattern logical names.
By specifying different continent type (mime type) in servlet porg by

using res setContentType(-) we can make browser window to display


web pages in different format.
MIME:- Multipurpose intent mail extension

Ex:- text/html, application/mswork, app/vendor.ms-excel and etc.


To get these MIME types we can regedit tool.
StartregeditHKEY_CLASSES_ROOT choose extension to know mine type.

web application-2
Develop web application having multiple servlet prog to generate web
pages in different format?

Step-1) creates deployment directory structure.


E:\MIME App
|----WEB-INF
|----classes
|web.xml|----*.java(4)
|----com.nt
|----HtmlSrv.class
|----ExcelSrv.class
|----WordSrv.class
|----XmlSrv.class
Develop the Servlet progs (refer application -1 of pages 102 to 106)
Step-3) ake sure that servlet-api .jar is placed in classpath.
Step-4) compile the servlet program
E:\MIMEApp\WEB-INF\classes> javac d . *.java
Step-5) Develop web.xml having 4 servlet configuration refer page105,106
Step-6) Start Tomcat server.
Step-7) Deploy the web application
Copy E:\MIMEApp folder to <Tomcat_home>\webapps
folder.
Step-8) Test the web application.
Request urls
http://localhost:3030/MIMEApp/hturl
http://localhost:3030/MIMEApp/wdurl
http://localhost:3030/MIMEApp/docurl

http://localhost:3030/MIMEApp/exlurl

20-may-2015
For every request given to servlet program the servlet container creates

1 set of ServletRequest, ServletResponse object and calls service(-,-)


method of our servlet program having those object as the arguments.
Understanding partial flow of execution from request arrival to req
generation using the dateapp application
D: Tomcat 8.0
|webapps
|DateApp
|WEB-INF
|classes
|web.xml|DateSrv.jvaa
|com.nt
|DateSrv.class

web,xml
<web-app>

<servlet>
<s-n>abc</s-n>
<s-c>com.nt.DateSrv</s-c>

</servlet>
<servlet-mapping>
<s-n>abc</s-n>
<u-p>/test</u-p>
<servlet-mapping>
</web-app>

a) programmer deploys the DateApp web application in Tomcat server

b) Tomcat Server makes ServletContainer to verify web.xml entries, if they


are valid the ServletContainer reads web.xml entries and stores in Hash

Map obj at RAM in Memory MetaData.


c) End-user (visitor) gives request by typing request url in the browsers
address bar.
d) Based on localhost:3030 of request url the Tomcat server takes the request.

e) Based on DateApp of request url server passes the request to DateApp web
application.
f) Based on /test of request url the container uses web.xmls in memory
MetaData and get servlet class name com.nt.DateSrv.
g) Servlet container creates 1 set of ServletRequset, ServeletResponse obj for
current request.
h) ServeltContainer checks the availability of our servlet class object if not
Available (DateSrv obj) then it load DateSrv class to create object also
complete all the formalities of instantiation.
i) Servlet Container calls service(-,-) of DateSrv having ServletRequest,
ServletResponse object as arguments.
j) The service(-,- ) method generates output goes to browser window through
we server and browser window displays that output as web page based on
the received continent tape.

Javax.servlet.ServletRequest(I)
extends

Javax.servlet.http.httpServletRequest(I)

Javax.servlet.ServletResponse(I)
extends

Javax.servlet.http.httpServletResponse(I)

sunMicro system/oracle gives servlet api as common api for all the

vendor companies having lots of interfaces. Every vendor company


gives ServletContainer, jsp container having more implementation class
of servlet api interfaces. These implementation will change server to
server, so we never place these implementations classes in our servlet
program to make our servlet prog as server independent(WODA)

21-May-15

if 10 request are given to our servlet program then servlet container


a) create 1 object of our servlet porg
b) statrt 10 thread on our servlet class object representing 10 request
c) create 10 set of request and response obj for 10 req on 1 set per
reqest basis.
To prove the above statement practically place the following code
with the service method of any servlet program and give multiple
req form multiple browser window simultaneously.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

class DateApp implements HttpServlet


{
public void service(HttpServletRequest req,HttpServletResponse res) throws

ServletException,IOException
{

//getPrintWriter object
PrintWriter pw=res.getWriter();

try
{

Thread.sleep(30000);
}

catch (Exception e)
{
}

e.printStackTrace();

pw.write("<br> our servlet class object hashcode"+this.hashcode());


pw.println("<br> req obj hash code "+req.hashCode());
pw.println("<br>res.hashcode"+res.hashCode());
pw.println("<br>current thread is "+Thread.currentThread().hashCode());

{
}

Jvm gives unique identity value for every object to get that value

hashcode() method.
To access currently running thread use Thread.currentThread()
method.

MIME Type
Res.setContentType(-) method given instruction to browser window to

display received in different format of webpages.


The content type/MIME Types are: Text/html application/msword, application/vmd,ms-excel, text/xml,
tesxt/plain and etc.
MIME: multi purpose internet Main Extension
To know MIME types we can use regedit tool of windows

StartrunregeditHKEY_CLASS_ROOTchoose MIME type.


Javax.servlet.http.HttpServlet(AC) is having two service(-,-) methods

1. 1st service(-,-) /public service(-,-) method


Public void service(ServletRequest req,ServletResponse res) throws SE,IOE
2. 2nd service / protected service(-,-) method
Protected void servce(HttpServletRequest req,HttpServetlResponse res)
throws SE,IOE
2nd servie (-,-) is recommended to use because it allows us to work with
the second feature of protocol http.

Procedure to develop web having 4 servlet program generating 4


different format webpages.
Step-1) creates deployment directory structure.
E:\MIMEApp
|WEB-INF
|classes
|web.xml

|HtmlSrv.java
|ExcelSrv.java
|WordSrv.java
|xmlSrv.java
|com.nt
|*.class(4)

Setp-2) Develop Servlet program of web application.


Refer-application 1 of 103 to 106

Note: ServletRequest and ServletResponse object doesnt allow working


with protocol http.

Note :-HttpServletRequest and HttpServletResponse obj allow us to


work with protocol http feature.
Step-3) compile the source code of the servlet program
E:\MIMEApp\WEB-INF\classes>javac d . *.java
Step-4) develop web.xml file having 4 servlet program configurations.
Step-5) refer 105 and 106

To configure multiple servlet programs we need to use multiple servlet


tag and multiple servlet-mapping tag having unique logical name and
unique URL patterns.
Step-5 ) deploy the web application in tomcat server. (make sure tomcat
server is in running mode)
Copy: E:\MIME to tomcat webapp folder.
Step-6) Test the web application
http://locahost:3030/MIME/sturl

103-60,88,115,143,160,165,170,175,

22-May-15
The super class method can be overridden in subclass either with same

modifier or with excess modifier.


The protected method of super class can be overridden with either

same protected modifier or extra public modifier.


The protected service(-,-) /2

nd

service(-,-) of HttpServlet class can be

overridden our servlet prg class either with same protected modifier or
with extra(excess) public modifier.
Always identify service(-,-) method based on its parameter types not

based on its modifiers (public/protectd)


Javax.servlet.Servlet(I)

^
| implement
Javax.servlet.GenericServlet(Ac)
extends
Javax.servlet.http.HttpServlet(Ac)
extends
Extends servlet class

Html, jsp files will be placed outside of WEB-INF folder.


We can use html prog to generate static web pages and jsp prog to

generate dynamic web pages


WEB-INF and its sub folder is called private area of the web application

i.e outsiders clients cannot use content of that folder directly.


Due to this cgf in web.xml file is mandatory ot access them through url

pattern
Html, jsp file will reside out side web-inf folder (public area0 so their

cfg in we-inf file is optional (nor required ) because they can be


accessed by client directly.
Web-inf and its content can only be used by underlying

server/container so it is called private area of the web application.

Html to servlet communicate


on:

Html prog/files /pages are given to generate static web pages. This
program can also be use to provide user interface (GUI) to end user

(Visitor) to submit request to other web resource program like servlet


pgra/jsp progs

Since end users are non-technical people they cannot give direct
request to server./jsp program by typing request url in browser window
to overcome this problem we can use html program based hyperlink
form submition to generate request.

Html to serve communication can be done on three way using


a) Hyperlink (cannot carry end user supplied data)
b) Using form submission(can carry end user supplied data)
c) Using java script (allow any component to submit the request)

Note: For this the request url of servlet prg as href.

Html pgr cfg in web.xml is not required because it is there placed

outside of
Servlet prog cfg is web.xml is mendatory because it is place inside

Page.html.

<h1> Click here to ger wish message</h1>

<a href="http://localhost:3030/WishApp/wishurl">
(wishurl is wishsrv servlet prog)
wish Message
</a>

In window operating system they has provided a feature UAC( user account
control). It will verify whether user is authorized or not.
To disable UAC control

We have to modify enable lue value to


We can change this value from the following location of registry.
To change the port no we use config folder in that we use a file

server.xml.
Instead of an exe file we can use zip file. when we use the zip file we

use startup.bat file to run tomcat.

Note:- to run the tomcat we need to set java_home in environment variable.

23-May-15
EVERY web resource pagr of web application like servlet prog/jsp
prg/html prg will have 1 request url, we need to use that request url in
order to send request to that we resource prog.
The web resource program like servlet program that is placed in WEBINF

and its sub folders (private area ) must be configure in

web.xml file to access from clients


The web resource program like html prog that is placed outside WEBINF folder can be access directly from client so its configuration in
web.xml file is not required.

Note: - form data of form page is goes to as request parameter names, values.
The name of form components will become req parameter name and the
values of form components becomes req parameter values.
Input.html
<h1>chck u r voting eligiblity</h1>

<form action="http://localhost:3030/VoterApp/vturl"<!--action url-->


<!--vturl--<it is url pattern of votersrv--> method="get"
<!--(get) is request mode -->

>

<!--it carry data 2 kb to 8 kb only-->

Person name: <input type="text" name="pname"/> <br>


person age: <input type="text" name="page"/><br>

<input type="submit" value="check voting eligibility"/>


</form>

To make the form page generated request going to servlet pr place the request url
of servlet prog as action url of servlet prog as action url (action attribute value of
<form> tag)
When form submits the requests the request goes to that web resource
prog whose request url is placed as action rul in the form pages.
The form pages can send either GET or POST mode request to servlet
prog.
The GET mode request can carries limited amount of data(2K-8K) ,
whereas the POST mode request can carry unlimited amount of data.
When form is submitted the form data is goes to server as request
parameter values like pname=raja&page=30. We can read these values
in our servlet prg by using req.getParameter(-) method.
String s1=req.getParamter(pname);//gives raja
String s2=req.getParameter(page);//gives 40.
In our servlet prog it is recommended to write request processing logic
in doxxx(-,-) methods , not in service(-,-) methods

The 7 doxxx(-,-)allows us to process requests in 7 modes, they are like


doGet(-,-) , doPost(-,-),doPut(-,-),doDelete(-,-) doTrace(-,-), doHead(-,), doOptions(-,-).
The form page can generated either GET or POST request, so use
doGet(-,-), or doPost(-,-) in servlet prg to process the request.
Prototypes of doxxx(-,-) methods.
Protected void doxxx(HttpServletRequest req,HttpServletReponse res)
throws SE, IOE
(7 methods like this)
Web.xml
Configure com.nt.VoterSrv prg with /vturl pattern and voter
logical name.
Request url: http://localhost:3030/VoterApp/input.html<-- (a)
execution flow of this application

http://localhost:3030/VoterApp/input.html<-- (a)
Input.html(b)
Submit(c)

Action attribute (d)


Web.xml(e )

VoteSrv.class( f)
doget(g)

http://localhost:3030/VoterApp/vturl?pname=raja&page=20
<---request url---------------- query string----
Query string contains que parameter name and its parameter value.

Application that take persion name age geneder as input and check
is it eligible for merrage or not.

24-May-15
Every servlet program is identified with its url pattern. It helps
programmers to hide technology that is used to develop the web
application.
According to servlet specification there are three types of url pattern.
a) Exact match url pattern
b) Directory match
c) Extension match
For every servlet url pattern configuration is mandatory.

All servlet / ServletContainer / jsp container are designed based on

common servlet, jsp specification so they recognized only three types of


url pattern.

Exact match
Must begin with / symbol and must not contain * symbol
Can have one or more letters/words separated with / symbol.
Ex- <url-pattern>/test1</url-pattern>

Request Urls http://localhost:3030/DateApp/test1 (valid)


http://localhost:3030/DateApp/test1.c (invalid)
http://localhost:3030/DateApp/test1.xyz (invalid)
Note: the one we have used so far comes under Exact match
url pattern.
Other exact match url pattern

1) Eg1- <url-pattern>/test1.c</url-pattern>
2) Eg2- <url-pattern>/abc/xyz/test2.c</url-pattern>
3) Eg3- <url-pattern>/nt/nt1/test.aspx</url-pattern>
Note: - the regularly used url pattern of real time is exact
match.

Directory Match Url pattern


Must begin with / symbol and must end with * symbol.
Can have multiple letter or word separated with / symbol.
Eg:- <url-pattern>/images/books/*</url-pattern>
Request urls:

http://localhost:3030/DateApp/images/books/hello.c (valid)
http://localhost:3030/DateApp/images/abc.c (invalid)
http://localhost:3030/DateApp/books/images /hello.c (valid)
http://localhost:3030/DateApp/images/books (valid)
other examples
eg1:- <url-pattern> /abc/xyz/*</url-pattern>
eg-

<url-pattern> /x/y/*</url-pattern>

eg-

<url-pattern>/y/* </url-pattern>

eg-

<url-pattern>/nt/it/Tech/* </url-pattern>

Extension Match url pattern


Syntax: *.<extension>
Eg- eg-

<url-pattern>*.do</url-pattern>

Request urls
http://localhost:3030/DateApp/abc.do (valid)
http://localhost:3030/DateApp/xyz/abc/x.do (valid)
http://localhost:3030/DateApp/abc.x (invalid)
http://localhost:3030/DateApp/abc.do/xyz.c invalid
http://localhost:3030/DateApp/.do (valid)

Other example:Eg1:- <url-pattern>*.c</url-pattern>


Eg1:- <url-pattern>*.nit</url-pattern>
Eg1:- <url-pattern>*.htm</url-pattern>
The servlet that takes all requests having different request urls and
delegates the request other web resource pgors is called Front

controller servlet. While configuration this servlet we need to use


either directory match or extension match url patterns.
<url-pattern>/test1/test2.c</url-pattern>
(it is exact match url pattern)
<url-patterm>/x/y/*.do</url-patterm> (invalid url pattern
formation)

If clash comes between exact match and directory match url pattern
the priority will be given to exact match url pattern.
Srv1 rul pattern: /xyz/* (Directory match)
Srv2 url pattern : /xyz/test.c (exact match)
http://localhost:3030/DateApp/xyz/test.c
here (srv2 will execute)
If clash comes between extension match and directory match url
pattern the priority will be given to Directory match url pattern.
Srv1 rul pattern: /xyz/* (Directory match)
Srv2 url pattern : *.c (extension match)
http://localhost:3030/DateApp//xyz/test.c
(Srv1 will execute)

If clash comes between extension match and exact match url pattern
the priority will be given to Directory match url pattern.
Srv1 rul pattern: /test.c (exact match)
Srv2 url pattern : *.c (extension match)
http://localhost:3030/DateApp//xyz/test.c
(Srv1 will execute)

If clash comes among all the 3 url patterns the priority will be given
to Exact match.

Note: in tomcat 8 server if two servlet prog having same url pattern
exception will be raised.
If multiple servlet prog are having directory match pattern and if clash
is coming between them the priority will be given to more nearer
matches.

If multiple servlet porg are having same logical name then last servlet in
the list gets higher priority.

25-May-15
Radio Button:
Gender: <input type=radio name=gen value=M>Male
: <input type=radio name=gen value=F>Female
In servlet program gender=req.getParameter(gen);
//Gives either M or F.
To group multiple radio buttons into single unit give same name
them (allow to select 1 radio button at a time)
Radio button the value kept in value attribute as req parameter
value.
(M) or (F)

In web application develop and to make web application as WODA


application and to support WODA behavior of application we should
prefer working with relative url instead of relative url.
Page.html
< a href=http://localhost:3030/wishurl> wish Msg</a>
-absolute url----------------------------------
< a href=wishurl> wish Msg</a>
-relative url----------------------------------
Input.html
< a href=http://localhost:3030/vturl> wish Msg</a>
-absolute url----------------------------------

< a href=vturl> wish Msg</a>


-relative url----------------------------------
in absolute url we need to specify port no , host name and etc. details if they
are changed while hosting the website or moving the web application from 1
machine to another machine or 1 server to another serer then we get problems in
web application execution, so always prefer relative urls.

Develop web application that takes employee details like number,name

salary, and give grows salary and net salary value.

09-Jun-15
For understanding all the seven request methodology refer-101, 102.

10-Jun-15
GlasssFish
Server: application s/w
Version: 4.x(compatible with jdk 1.6)
Vendor: sun Ms(oracle corp)
Open source

Allows to create domains. Default domain name ->domain1


Domain1 username: admin
Password: adminadmin
Domain1 default ports: - 8080 (http)

-4848 (admin)

To download s/w : download s/w as zip file

To install s/w extract the zip file.


For help www.glassfish.org
Procedure to crate user defined domain in Glassfish 4.x server
<Glassfish4.x_home>/bin>asadmin create-domain --adminport=4646

--user=testuser GFNtAJ11
4646 is admin port number
testuser admin user name
GFNtAJ11domain name
Enter admin password: testuesr
Renter admin password: testuser
.
.
.
.
Domain GFNtAJ11 created.
Domain GFNtAJ11 admin port is 4646.
Domain GFNtAJ11 admin user is "testuser".
Command create-domain executed successfully.

To change http port no of the above domain server:


Go to
<GlassFish4.x_home>\domains\GFNTAJ11\config\domain.xml
And modify port attribute value of first <network-listener> tag.

Procedure to deploy web application in GFNtAJ11 domain


server through console deployment process.

step-1) keep voterApp.war file ready.


step-2) start GFNtAj11 domain server of GlassFish4.x
<GlassFish4.x_home>\bin>asadmin start-domain GFNtAJ11
For server console we can server.log file of domain floder
step-3) Open admin console
http://localhost:4646
Username: testuser
Password: testuser
step-4) deploy the web application.
Admincosle application deployee brows okdeployee launch
Glassfish server internally users the tomcat server supplied jsp, servlet

container.

To perform hard deployment of web application in


GFNtDomain server GlassFish 4.x copy either directory
either directory (VoterApp) or war file(VoterApp.war) to

<GlassFish_home>\domains\GFNtAJ11\autodeploy folder.
Requested url: http://localhost:7788/VoterApp/input.html

To stop domain server

<GlassFish4.x_home>\bin>asadmin stop-domain GFNtAJ11

Jboss
Type: Application server s/w
Vendor: Apache / RedHat
Upto Apache- 5 it belong ot Apache and after 5 it belongs to RedHat
Version : 7.x (compatable with jdbk 1.6)
Open source up to version-5
and latter it is commercial.
Default port no:-8080(http)
Allows to create domains
To download s/w: download as zip file from www.jboss.org website
(jboss-as-7.1.1.Final.zip)
| Extract it for installation
Supports only console deployment
internally user Tomcat server
To change http port no of jboss7.x
Go to <jboss7.x_home>\standalone\configuration\standalone.xml
file a <socket-binding name=http port =8899/> tag.
To create username and password required admin console:
User <Jboss7.x_home>\bin\add=user.bat file

Choose Management user


Username : testuser
Password: usertest
Reenter password: usertest;
.
.
.

To perform console deployment of the web application


1. Prepare war file (VoterApp.war)
2. Start server
<Jboss7.x_home>\bin\standalone.bat(run as administrator)
3. Open admin console
http://localhost:8899/console/App.html
4. Deploy the web application (VoterApp.war)
Deployements Manage Deploymentsadd content brows
(voterApp.war) nextsaveenable and now test the
application.
http://localhost:8899/VoterApp/input.html
localhsot:8899/voterApp

11-Jun-15
Procedure to configure various networks with eclipse ide:Note: -eclipse gives built in plugin to integrate tomcat server for other
servers we need to download plugin (adopter separately.

Procedure to configure Tomcat8 server with Eclipse Luna:Procedure to cfg NtAj11 domain server of weblogic 12c with eclipse Luna:S-1)Download adapter of weblogic 12c
Window preferenceserverruntime enviromentadddownload
additional adapteroracleweblogic toolnextaccept terms and
conditionsfinish
Step-2) restart eclipse IDE

JavaeeTestWeb1in web contentindex.html


<h1> welcome Eclispse ide?</h1>

Procedure to configure GFNtAJ11 domain server of GlassFIsh 4.x with


Eclipse kepler
Step-1) Download GlassFish server adapter

windowpreferecesnextruntime serverruntime
enviadddownload additional server adapterglassfish
toolsaccepts lisence agrementokrestart eclipse ide
step-2) configure glassfish domain server
windowpreferencesserverruntime
enviaddglassfishglassfish4.0nextchoose installation folder of
glassfish folder(D:Glassfish4.x)finish
Right click on project select run on server
Domain Directory: till GFNtAJ11
Id : testuser
Password testuser
Finsh
Q can we modify the content of web page by using the view source
option of web page?
Ans: Not possible, because that modification takes place at client side but
not in the web resource program in the web application so when we
press refresh button request goes to server and web pages comes based
on old content of web resource program.

13-jun-15
Tools in Eclipse: http://www.eclemma.org/
Dropins folder:
Download Eclemma plugin from internet in form of zip file extract it
and past under eclipse/dopein folder and plugins folder then restart ur
eclipse.

It perform code coverage


Findbugs Eclipse plugins:-

Ctrl+shif+j= documentation
Ctrl+shift+f=format
Code coverage
Codeformatter (.xml) file
Alt+shif+j=document
Ctrl+w-close
Strl+shif+w=close
Ctrl+shift+t= see jar file name of a class
C+s+R=rename methods

Ctrl+shift+l- for listing all shorted

Servlet Listeners(Event handling in servlet programming)


Evnent is an action performed on the component or object. To perform

event handling we need event listeners which given event handling


methods.
The components of envent handling
a) Source object Button
b) Evnet class ActionEvent
c) Event Listener ActionListener
d) Event Handling method actionPerformed(-)

From servlet api2.3 event handling can be done on request,

servletcontext and HttpSession objects.


Events handling on request object allow us to keep track of when

request obj is created and destroyed and also useful to keep track when
request attribute is added /modified/removed. Based on this we can
know request processing time each request.
Even handling on session obj allows us to keep track of when Session

object is created/ destroyed and also useful to keep track of when


session attribute is added /modified /removed. Based on this we can
know the session duration.
Event handling ServletContext obj allows keeping track of when

ServletContext obj created/destroyed and also useful to keep track


when ServletContext attribute is added/modified/ removed. Based on
this we can also know the deployment and unemployment of web
application.
Source object Event class

Event Listener

Event handling

Request

ServletRequestListen

requestInitilized(

ServletRequestEve
nt

er

-)

requestDestroyed
(-)

Session

HttpSeeionEvent

HttpSessionListener

sessionCreated(-)

sessionDestroyed(
-)

ServletConte
xt

ServletConextEven ServletContextListen contextInitlized(t

er

contextDestroyed
(-)

Procedure to develop and configure ServletListener:


a) Keep SessionApp application ready
b) Develop the following 3 listener classes developed in com.nt
MyRequestListener.java
public class MyRequestListener implements ServletRequestListener
{

long start,end;

//execute when req obj is created

public void requestInitialized(SevletRequestEvent sre)


{
}

start=System.curentTimeMillis();

//execues when req ob is destroyed


public void requestDestroyed(ServletRequestEvent sre)
{

end=System.currentTimeMillis();

HttpServletRequest req=(HttpServletRequest)sre.getServletRequest();
ServletContext se=sre.getServletContext();
request");
}

sc.log(req.getRequestURI()+"has taken"+(end-start"+"ms to process

MySessionListener.java
public class MySessionListener implements HttpSessionListener
{

long start,end;

//executed when session obj is created

public void sessionCreate(HttpSessionEvent hse)


{

start=System.currentTimesMillis();
//write to log file

hse.getSession().getServletContext().log("session started at "+new


Date());
}

//when Session obj destroyed/invalidated

public void sessionDestroyed(HttpSessionEvent hse)


{

end=System.currentTimeMillis();
//write to log file

start));
start));
}

hse.getSession().getServletContext().log("sesssion ended at"+(endhse.getSession().getServletContext().log("session duration"+(end-

c) Configure the above two listener classes in web.xml file.


<listener>

<listener-class>com.nt.listeners.MyRequestListener</listener-

class>

</listener>
<listener>

<listener-class>com.nt.listeners.MySessionLIstener</liistener-

classes>

</listener>

d) Run the app and absorb the log file in tomcat_home/logs folder
Servleconter create the object of servletlistener either during server

startup or during the deployment of the webapplication.


servletListener are not given to perform the regular request , response

model it is given to enabling monatring the with out touching the web
resource application of application.

15-jum-15
understanding protocol http: The Hypertext Transfer Protocol (HTTP) is an application-level protocol for
distributed, collaborative, hypermedia information systems. This is the foundation
for data communication for the World Wide Web (i.e. internet) since 1990. HTTP is
a generic and stateless protocol which can be used for other purposes as well
using extensions of its request methods, error codes, and headers.
This tutorial is based on RFC-2616 specification, which defines the protocol
referred to as HTTP/1.1. HTTP/1.1 is a revision of the original HTTP (HTTP/1.0). A
major difference between HTTP/1.0 and HTTP/1.1 is that HTTP/1.0 uses a new
connection for each request/response exchange, where as HTTP/1.1 connection
may be used for one or more request/response exchanges.

http is application protocol that runs over network

protocol tcp/ip

defining set of rules to transfer hypertext between browser to


webserver and vice-versa.
Normal text allows sequential reading.
Hypertext allows non-sequential reading because of hypertext links.
The request URL generates http request containing multiple details they

are H2p2.
H Http request method (GEG/POST/)
HHttp request headers (user-agent, referrer, accept,)
Prequest parameters( User =raja&pwd=rani)
----query string

httpRequest with example content

what is difference between request headers and req parameters?


Req Header

Req Parameters

-Names are unique

Names are not unique

Carries browser supplied implicit

Carries end user supplied data

Names are fixed and unique.

Names are user-defined.

data.

(from data)

Every request contains headers.

Request may or may not contain

We must use HttpServletRequest

We can use any ServerRequest or

obj to read header values.

HttpServletRequest obj to read

request parameters.

header values.

All the values of httpRequest will we taken by server and passes to

container. This container creates request obj having all the details of
client generated request.
Different way of reading request params being from servlet program
Note: we can use ServletRequest or HttpServletRequest obj for this
Request url:
http://localhost:3030/DateApp/test1?sno=101&sadd=hyd&sadd=vzag
Approach-1)
String s1=req.getParameter(sno)//given 101
String s2=req.getParameter(sadd);//gives hyd
Note: we must know req parameter name and only the first value will
come if req param contains multiple values.
Approach-2)
Enumeration e=req.getParameterNames(); //only names of the req
parameter
While(e.hasMoreElement)
{
String name=(String).nextElement();//gives each name
String value=req.getParameter(name); gives each values
Sop(name+-+value);

Gives all request parameter names and values. If request parameter


contains multiple values then it gives only first values.
Approach-3)
String s[]=req.getParameterValues(sadd);
S[] gives hyd,vizag as element values.

String s1=req.getParameterValues(sadd)[1];//gives vizag


Approach-4)
Map paramMap=req.getParameterMap();//gives map having req parame
names(as keys)
//Get all request parameter names(keys) as Set collection
Set names=paramMap.KaySet();
//Display req parameter names, values
(for(Object name:names)
{
Pw.println(<br>+name+<---->+req.getParameter((String)name));

Map<String,String[]>paramMap=req.getParameterMap();
String val1[]=paramMap.get(sno);
Pw.println(sno required parameter value=+Array.toString(val1));
String val2[]=paramMap.get(sadd);
pw.println(sadd request paramValues+Array.toString(sadd);

file:///D:/Tomcat%208.0/webapps/SrvConfigApp/ServletConfigApp.java

16-jun-15
Different way of reading request header values:-

Approach-1)
String s1=req.getHeader(user-agent);//gives IE

String s2=req.getHeader(accept-language);//gives en-US


Appraoch-2)
Enumeration e=req.getHeaderNames();//Gives all req header names
While(e.hasMoreElements())
{

String name=(String)e.nextElement();//Gives name


String value=req.getHeader(name);//gives value.
Pw.println(name+--+value);
}

Displays all the request header names and values.

Note:- we need HttpServletRequest obj to read request header values.


Servlet program can use request header values to know about current

browser using which the request is generated so servlet program can


generated the response according to that browser settings.
List of request headers

accept, accept-language, cookie, referrer, accept-encoding, accept-charset,


host, connection, keep-alive, max-age, user-agent and etc.

For related info on request (ServletRequest, HttpServletRequest,


RequestHeader, and etc. refer page no-84 to 87. And also refer page no171-181

Http response: When servlet prog gives output to browser window, it goes as http

response and that contains multiple details like SCH details.


Sresponse status (100-599)
100-199information
200-299success
300-399Redirection
400-499-incomplete
500-599-server Error
CResponse content (response body)
The messages placed in pw.println(-) method.
H response headers.
(ContentType, contentLength,Localtion, referesh and etc) and
Miscellaneous info.
Response status codes and response status headers help browsers to

display web page in different formats to display error pates.


For various response status code refer page no-179 to 180

Note: the default status code for servlet is 200.

When browser gives request the web server takes the request and

passes that req to the container .The container creates request ,


response object for every request, Request object contains a lot of
information given by client along with the request.
Response obj contains headers with default values and default status

code but these values can be changes in our servlet program.

How can we make our web page getting refreshed automatically?


Ans:- use refresh Header as shown below

In servlet prog
res.setHeader(refresh,10);
(or)

Res.setIntHeader(refresh,10);
This response header makes browser window to autorefresh the
displayed webpages for every 10 seconds .

This concept is useful while displaying live Game Scores, Stock


market share values in web pages.
List of response headers
Content-Lenght, content-Type, location, refresh, lastModified, server,
Connection, Server, date, content-diposition, cache-control, pragma and
etc.

(cache-control, pragma are used for enabling cache/buffering in


browser)
severlet response , httpservlet response and response header refer-page87 to

17-Jun-15
Cache-control or pragma:(response header) Buffer/cache is temporary memory that holds data for temporary period. In client
environment the buffer at client side holds server supplied result and uses them
across the multiple times for same requests to reduce network round trip between
client and server.
Every browser window contains Buffer and it maintains web resource program
supplied results (given by server) and uses those result across the multiple same
requests to reduce network round-trip.
If web resource program is changing its output dynamically for every request then
it is recommended to disable buffer or cache of browser window otherwise
browser window may show old output. (old result collected from buffer/cache).
To disable buffer or cache of browser window we need to place following code in
servlet program,
res.setHeader(cahch-control,no-cache);
(or)

res.setHeader(pragma, no-cache);
Because of the above code every request comes to servlet program and output will
not be collected from buffer.
Eg: the servlet program show live game score should be executed by disabling buffer of
browser window.

Eg:- the servlet program that shows seven wonders of world (fixed content) is
recommended to execute by enabling the buffer of browser.
To set header value/modify header vlues:Res.setHeader(Headername,value);

Res.setIntHeader(Header Name,numeric value);


Res.SetDateHeader(Header name, Date value);
To add header
res.addHeader(Headername,value);
Res.addIntHeader(-,-);

Res.addDateHeader-,-);
To set response status code
res.setSatus(numeric status code);
To send Error message
res.sendError(statuscode,Error message);
Direct method to set specific header values
res.setContentType()
res.setContentLength(-)

res.setCharacterEncoding()
Note:- To set buffer size
res.setBufferSize(-);
If multiple threads are acting on single object/variable concurrently then the data
of that obj may corrupt.
This indicates that obj/variable is not thread safe by default. To achieve thread
safety use synchronization concept.
Our servlet program is single instance multiple threads component, so the instance
variable of servlet prog is not thread safe where the local variables placed in
service(-,-) methods are thread safe by default.
Multiple threads acts on single copy of instance variable whereas every thread gets
its own copy of service (-,-) method local variable.

public class TestSrv extends HttpServlet


{
private int a;//instance
public void service(-,-) //doxxx(-,-) throws SE,IOE
{
int b;
--------}
}

Servlet to DB s/w communication:


To save inputs coming to servlet program in database s/w and to generate the
results generated by the servlet prog in Database s/w and to gets inputs required
for servlet prog from DB s/w we need to go for servlet to DB s/w communication .
for this we need to place persistence logic in servlet pro like jdbc code, hibernate
code and etc.
There are multiple approaches to place jdbc code in servlet prog
Appraoche-1)
Create connection object in the init() method.
Use connection obj in the service(-,-)//doxxx(-,-) method.
Close connection object in the destroy() method
Advantage :-

All requests coming to servlet prog will use single connection to interact with
database s/w, so it gives good performance.
Disadvantage: Here Connection objects is instance variable in our servlet class, so it is not
thread safe by default.
Appraoche-2)

Create jdbc connection object in service(-,_)/doxx(-,-) method


Use jdbc connection object in service(-,-) /doxxx(-,-) method
Close jdbc connection object in service(-,-) /doxxx(-,-), so it is thread safe by
default.
Advantage: Here connection object is local variable in service(-,-) //doxxx(-,-), so it is
thread safe by default.
Disadvantage:

Every request given to DB s/w will open one connection with DB s/w i.e multiple
requests will open multiple connections with DB s/ws from servlet prog. This
degrades the performance.
Approache-3)
Get jdbc connection obj from jdbc connection pool begin from service(-,-)
/doxxx(-.-) method.
Use jdbc connection object in service(-,-) /doxxx(-,-) methods.
Return jdbc connection obje back to jdbc connection pool being from service(-,)/doxxx(-,-) methods
Advantage:a. Connection pool gives reusability of jdbc connection obj, so with min connection
objs we can make max clients talking with DB s/w.

b. Creating connection objects, closing connection obj will be taken care by jdbc
connection pool. So the programmer is free from that process.
c. Given good performance compare to Approach2.
d. Here the reference variable that holds connection obj of jdbc connection pools is
local to variable so we can achieve thread safety.
Jdbc connection pool is factory that contains set of readily available jdbc
connection obj before actually being used.
Approache-4:DAO: - The java class that have separates persistence logic from other logics of the
application makes that logic as reusable logic and flexible logics to modify is called DAO
Class.
Create DAO class having persistence logic
Note: - This DAO class can use direct jdbc connection jdbc or connection pool connection
object.
Create DAO class obj in servlet pros service (-,-) /doxxx(-,-) and use the
persistence logic of DAO class.
Conclusion : use approach-1 for small application
Use approach -3, 4 in large scale application.
Date:

18-Jun-15

Normal java application compilation and execution takes from cmd prompt.
Servlet prg compilation takes place from cmd prompt and execution takes place
from servlet container of the server.

If normal app uses third party api (like oracle thin driver) then that api related jar
file (ojdbc14.jar) should be added to classpath.
If servlet pro uses third party api then third party api related jar file should be
added to classpath and should be added to WEB-INF\lib folder. Here jar file added
to classpath will be used during the compilation servlet prog and jar file added
WEB-INF\lib folder of web application will be used during the execution of servlet
pog.

Note:-jar files in classpath: ojdbc14.jar, servlet-api.jar


Page-113 application-5

In multiple web application deployed in a server are using same third party api
then instead of placing that third party api jar file in WEB-IN\lib folder of every
application we can place in only one time in server lib folder to use in multiple web
applications.
Server

Server library folder

Tomcat

<Tomcat_home>\lib folder

NtAj11Domain of

<weblogic_home>\user_project\domain\NtAj1(domain

weblogic

name)

GFNtAj11Domain of

<GlassFish_home>\user_pojects\domains\GFNtAJ11\lib\ext

GlassFish4.x

folder

JBoss7.x

<jboss_home>\standalone\lib\ext folder..

Working with server library folder to keep the jar file is not recommended, because
when we move web application from one server to another server or from one
machine to another machine. We need to move the jar files separately.
Servlet container tries to recognized the api used in servlet program in multiple
places and in the following order.
a. In the WEB-INF/classes folder of current web application.
b. In the jar files added to WEB-INF\lib folder of the web application.
c. In the jar files added to server library folder.
Date
DBApp web application for Eclipse Project.

DBApp(Eclispe Dynamic web project)


|--java resources

19-Jun-15

|--src
|--com.nt

|--DBsrv.java

|--webcontent
|--input.html
|--WEB-INF

|--web.xml

Jar file: Servlet-api.jar ,ojdbc14/6.jar


The jar files added to build path are not visible in WEB-INF\lib folder directly.
For that we need to perform deployment Assembly operation.
Right click on project --buildPath --cfg built path --deployment
assembly --built path entries --select jar file --finish

What is different between ServletContext and ServletConfig?


It is one per our class object so it is called right hand to our servlet class object.
Servlet container creates this object right after our servlet class object creation
and destroys this object right after our servlet class object destruction.
It is an object of underlying ServletContainer supplied class that implements
javax.servlet.SerletConfig(I).
This obj is useful to know about servlet porg (like getting logical name and to
pass additional info to servlet prog).
Useful to read <init-param> values form web.xml file to servlet program.
Useful to access ServletContext object being from servlet prog.

ServletContext: ServletContext object is one per web application.

It is called global

memory of the web application because data placed in

this object is visible and accessible in all web resource programs of web
application.
It is the object of underlying ServletContainer supplied java class that
implements javax.servlet.ServletContext interface.
ServletContainer creates this object either during

deployment of the

web application or during server startup.


ServletContainer destroyed this object when web application is stopped or
reloaded or undeployed.
Using this object
a. We can get server info.
b. We can get servlet API version.
c. We can get path of resource.
d. We can get input stream pointing to a resource.
e. We can get MIME type of resource.
f. We can get Global init params/context params from web.xml.
g. We can write messages to current days log file.

In a server total 10 web application are deployed in that 7 web application are there
in running mode and 3 are in stopped can u tel me how many servlet context object
are currently available in the server.
Ans: - (10-3)=7
In a web application there are 10 servlet program in that 5 servlet programs are
already request and another two servlet program are enable with load on startup
can you tell me how many ServletConfig objects are currently available in we
application.
7 servletConfig object are crated.
ServletConfig obj, ServletContext obj, our servlet class obj, request object and
response object are the ServletContainer crated object. That means we cannot crate
those object but we can access those object in our servlet program.
this operator/keyword to access our servlet class object.
Override service(-,-)/doxxx(-,-)to accesss req, res objs

Different way accessing ServletConfig obj

Approach-1) (not recommended to use)


public class TestSrv extends HttpServlet
{

ServletConfig cg;

public void init(ServletConfig cg)


{

this.cg=cg;
//use cg
}

public void service(-,-) //doxxx(-,-) throws SE,IOE


{

//use cg
}

Approach-2)
public class TestSrv extends HttpServlet
{
public void init()
{

ServletConfig cg=getServletConfig();
//use cg
}

public void service(-,-) //doxxx(-,-) throws SE,IOE


{

ServletConfig cg=getServletConfig();
//use cg
}
}

Different ways of accessing ServletContext object:Appraoch-1) Not recommended


//access ServletConfig obj

ServletConfig cg=getServletConfig ();


//getServletConfig() it is public method of GenericServlet can be access

directly without class name.


//Access ServletContext obj

ServletContext se=cg.getServletContext();
Note:- To access ServletContext obj we need ServletConfig obj directly or indirectly.

Approach-2) Recommended
In Servlet prog
ServletContext se=getServletContext();

// getServletContext it is a public method of GenericServlet which


internally use servletConfig object to access ServletContext object.

Approach-3)
From Servlet 3.0 (recommended)

In servlet Prog
ServletContext sc=req.getServletContext();
Date:

20-Jun-15

ServletFilter: ServletFilter is special web resource program that can we use as an


intercepting filter having ability to trap request and to trap response.
ServletFilter contain pre-request processing logic and post-response
generation logic.
ServletFilter can be mapped with other web resource prog of web
application to add additional functionality in web application
without modifying the source code of exiting web source prog

With respect to above diagram:-

(2) ServletFilter traps the request and executes pre-request processing


logic.
(4) Servlet executes the request processing logic.
(6) ServletFilter executes post-response generation logic.
ServletFilter can be mapped/ applied on one or more web resource prog

of the web application.


We can take multiple ServletFilter as a chain to apply on 1 or more web

resource prog on a web application.


Basic of ServletFilter : ServletFilter is java class that implements javax.servlet.Filter(I) and
provides definition for 3 methods.
a) inti(FilterConfig ) for instantiation
b) doFilter(ServletReqeust req, ServletResponse res,FilterChaning fc)

FilterChain for Trapping request, response.


c) destroy() for destruction event.
The above 3 methods are life cycle methods of ServletFilter.
FilterConfig obj is right hand obj to our Filter class obj. we can use
this obj to access ServletContext obj and to access filter init-params
from web.xml file.

There is no FilterContext obj in web application.


ServletContainer creates our Filter class obj either during server is
startup or during the deployment of web application.
ServletContainer destroyed our Filter class obj when the web
application stopped/reloaded/undeployed.
Every Server filter prog must be configured in web.xml file using
<filter>, <filter-mapping> tags.
To map 1 filter with 1 servlet prog the url pattern of servlet prog
must be taken as the url pattern of filter prog.
To map filter with all the web resource prog of web application use
/* as the url pattern.
ServletContainer create the following objs either during server
startup or during the deployment of the web application.
a. ServletContext obj
b. ServeltListener objs
c. ServletFilter obj
d. Servlet obj on which <load-on-startup> is enable.
Sample Filter prog:public class MyFilter implements Filter

{
public void init(FilterConfig fg)
{

//initializaion logic
}

public void doFilter(ServletRequest req,ServeltResponse res,FilterChain fc)throws


IOE,SE

{
...
....

...//pre-request processing logic

chain.doFilter(req,res);//sends the request to the next filter in chain


or

destination servlet/jsp program


...

....//post response generation logc


}

...

public void destroy()


{

....//Uninitialazation logic
...

3 types of ServletFilter:a.

Request filter (contains only pre-request processing logic)


Eg:- AuthenticationFilter, AuthorizationFilter, RequestDumperFilter and
etc

b. Respone filter (contains only post-response generation logics)


Eg.- compressionFilter, contentTranslationFilter, SignatureFilter and etc

c. Request-Response filter (contains both pre-request processing & postresponse generation logics)
Eg. PerformanceTestFilter
Mapping servlet filter with servlet/jsp program:1. Mapping 1 filter with 1 servlet program

Srv1(servlet) url pattern : /s1url


Frv1(Filter) url pattern: /s1url
2. Mapping 1 filter with 2 servlet program
Srv1(servlet) url pattern : /s1url
Frv1(filter) url pattern: /s1url
Frv2(filter) url pattern: /s1url
3. Mapping 1 filter with all web-resource prog:Frv1 url pattern:/*
4. Mapping 2 Filter with all the web-resource program:
Frv1, Frv2 url pattern : /*
5. Mapping certain multiple Filters with certain Servlet program
Srv1 URL pattern: /x/s1url
Srv1 URL pattern: /x/s2url
Srv3 URL pattern: /y/s3url
Srv4 URL pattern: /y/s4url
Frv1 URL pattern: /x/* (will be mapped with srv1, srv2)
Frv1 URL pattern: /y/* (will be mapped with srv3 and srv4)
Example on request Filter:-

(Perform servlet side from valid action using filter)

Note:- In the above diagram ServletFilter is having inputs validation logic to


validate the input given to the servlet prog.
FilterChain obj is the objects of the class that implements FilterChain
Interface.

This objects holds information about next filter to execute in chain or


the target servlet or jsp prog to execute.

21-jun-15
FilterApp1

|--WEB-INF

|--classes

|--web.xml |--MyFilter.java

|--MyServlet.java
|--com.nt

|--*.class(2)

For above code based example application refer page- 161 and 162 (application)

When filter is mapped with servlet the filter and servlet program uses

same request and response object.


Tomcat server generates 1 log file per day in <tomcat_Home> \log

folder.
To write log message this log file we need to use following code.
ServletContext se=getServletContext();
Sc.log(Hellow how are u);

When multiple Filters are cfg on 1 servlet then they trap request of

servlet prog in the order they of their configuration and response on


the reverse order by their configuration.
Applying authentication filter and Performance Test filter on Servlet
prog:-

2?---> AuthFilter checks weather user and passwords are correct or not
3E--> if not correct launches one.html asking usr, password again
4---> Tracks req trapping time
8---> Tracks the response trapping time to know the time taken for request
processing( Performance

test)

Page-162 to 165

23-Jun-15
Jdbc driver class, URL, username, password and etc are called jdbc

properties.
For better servlet development do not hard code input value inside the

servlet prog gather such value outside the servlet program.


There are two ways to gather input values for servlet prog from outside

the servlet prog


1. Request parameters (Form data)

User this to gather non-technical input values from end-user


(client side) like name, address, age and etc.

2. Servlet init parameters:o

Use this to gather technical input values from programmer


through web.xml file like driver class name, url, and etc..

User request obj (like req.getPrameter(-)) to read request


parameter values.

Use ServletConfig obj (like cg.getInitParameter(-)) to read servlet


init parameter values from web.xml file.

To make the jdbc code of servlet prog as flexible code to modify, it


is recommended to gather jdbc properties from programmer
through web.xml files as parameter values.

To place servlet init parameter in web.xml file

Inside <servlet>------</servlet>
<servlet>

<init-param>

<param-name> </param-name>
<param-value> </param-value>

</init-param>

</servlet>

To read init param values in servlet porg.


ServletConfig cg=getServletConfig();
String s1=cg. getInitParameter();

For improved DBApp application that uses servlet init parameter to

make jdbc code as flexible code to modify.


App-6 page-114

770 to 776reading and using servlet init parameter values

getServletName

java.lang.String getServletName()

Returns the name of this servlet instance. The name may be provided via server
administration, assigned in the web application deployment descriptor, or for an
unregistered (and thus unnamed) servlet instance it will be the servlet's class name.
When servlet container create our servlet class object.it uses logical

name given in web.xml as the object identity (reference variable name)


to get this logical name being from servlet prog use.
o cg.getServletName();
Servlet container internally maintain our servlet class object and their

logical name as the key value pairs of HashMap obj elements.


In tomcat server ServletConfig obj is the obj of

org.apache.core.StandardWrapperFacade class that impements


javax.servlet.ServletConfig(I)
o pw.println(ServletConfig obje class name +cg.getClass);
Q:- Can we place jdbc properties in properties files to make the jdbc code of
servlet program as flexible code to modify?
o Yes we can do, but not recommended
Reason :- web.xml file is quiet mandatory in web
application development so it is recommended to pass jdbc
properties from that file instead of taking one extra file
properties.
Different ways reading init parameter values from web.xml
Appraoche-1)
String s1=cg.getInitParameter(dbUser);

Note:- we must pass the name of the init parameter.


Approache-2)

Enumeration <String> e=cg.getInitParameterNames();


//gives all init parameter names.
While(e.hashMoreElements())
{

String name=e.nextElement();
String value=cg.getInitParameter(name);
Pw.println(name++value);
}

If multiple servlet porg want to use same init params then do not place

them in every servlet prog cfg of web.xml, place them only for 1 time
in web.xml as context params so that they can read in all servlet porg
of web application by ServletContext obj.
To place context param in web.xml
Outside <servlet>,<servlet-mapping> mappings
<context-param>

<param-name>dbuser</param-name>
<param-value>scott</param-value>

</context-param>

To read context param values.


ServletContext sc=getServletContext();
String str=sc.getInitParameter(dbuser);
Context params are also called as global init paramer
Page117--862 to 881(context param having jdbc properties) 910-

920 (reading and using jdbc properties as context param values


through servlet config object.

24-Jun-15
With respect to Tomcat 8:

If we give same name for multiple init params then the first values in
that list will be taken.
If we give same name for multiple context params then the last value
in that list will be taken.
Q can we give same name for init-param and context param in
web.xml file?
Ans: Yest possible, Reason is
We can read init param value by using ServletConfig obj and
we can read context param value by using ServltContext obj.
To find class name
servletContextobj.getClass();
servletContextobj.getMajorVersion()
servletContextobj.getMinorVersion()
servletContextobj.getServerInfo();
type of input.html Mime
servletContextobj.getMimeType(/input.html);
path of input.html
servletContextobj.getRealPath(input.html);
context path of web application ->
servletContextobj.getContextPath()
wring in log file:- servletContextobj.log(new Date().toString());

We can use ServletContext obj to gather additional info about current

current web application and its web resource progs://getServletContext obj


ServletContext sc=getServletContext();
pw.println(<br> server info +servletContextobj.getMajorVersion());
o pw.println(<br>server into minor
version+servletContextobj.getMinorVersion())
o pw.println(<br> server into+servletContextobj.getServerInfo();
o pw.println(<br>type of input.html Mime
+servletContextobj.getMimeType(/input.html);
o pw.println(<br>path of input.html +
servletContextobj.getRealPath(input.html);
o pw.println(<br>context path of web application
+servletContextobj.getContextPath());
o pw.println(<br>path of web apliation
servletContextobj.getContextPath(/));
Q:- what is the difference b/w placing logic in constructor and pacing
logic in init() method?
Ans:-- Container creates ServletConfig object after executing our
servlet class object and before executing init() method. So servlet
config object is not visible in constructor but visible in init() method.
We cannot access ServletContext object without serlvetConfig obj. i.e
we cannot use ServletContext obj in constructor but it can be used in
the init() method.
Due to the above reason we cannot use init params and context
params in the constructor, but they can we use in the init() method.

Note:-- it always recommended to write initialization logics in the


init() method.

Connection pool: There are two types of jdbc connection pools

a) Client side connection pool


Useful in standalone application
b) Server side connection pool.
Useful in server side apps like web applications
All the connection obj in the connection pool represents the

connectivity with same DB s/w.


o Eg> jdbc connection pool for oracle means all connection obj
represents connectivity with same DB s/w.
T.L /P.L creates jdbc connection pools and reaming members will use

that jdbc connection pool.


Jdbc DataSource obj represents jdbc con pool, for global visibility this

DataSource obj will be placed in jndi registry having nick name or jndi
name.
For global visibility we can place or object reference in jndi registry.
Every server gives one built-in jndi registry.

Eg. Rmi registry, GlassFish registry, COs registry, weblogic


registry etc..
Note:- every jdbc conn obj from conn pool should be access through jdbc
DataSource object.

With respect to the dig


1. Pl/tl makes server to use type -1/2/3/4/5 driver to create jdbc connection
pool having set of jdbc connection object.
2. & 3. TL/PL create data source object pointing to connection pools and keep
that object reference in jndi registry having nick name or alias name or
jndi name.
4 . refer diagram.
5.&6&7&8 refer diagram.
9. refer diagram
10. refer diagam

25-Jun-15

Date :

Jdbc connection object represents the connectivity b/w java app and DB

s/w and we can use jdbc code to perform insert, update, delete and
select operations on DB s/w.
InitialContext obj represent the connectivity b/w java app and jndi

registry and we can use this jndi code to perform bind, rebind, unbind,
and lookup operation on the jndi registry.

o bind keep obj/obj ref in jndi registry with jndi name


o rebind modifying obj/obj ref of jndi registry.
o unbind removing obj/ obj ref from jndi registry
o lookup searching and getting obj/obj ref from jndi registry.
Sample code for lookup operation:InitialContext ic =new InitialContext();//connects to jndi registry

DataSource ds =(DataSource)ic.lookup(Dsjndi);//gets the DataSource obj ref


Procedure to create server managed jdbc connection pool for oracle,
DataSource in NtAj11Domain Server of 12c.
Step-1) Start NtAJ11 domain server of weblogic and open its admin
console
o D:\OracleWebLogic12c\user_projects\Domain\NtAj11\startweblo
gic.cmd
o http:/localhost:7070/console usename: weblogic
o

password: weblogic

step-2) create jdbc connection pool for oracle


adminconsole service Datasourcgeneric datasourcjndi
datasource DSjndi
Database type:-oracle
Service conection
testconfiguration NEXTCHECK BOx ADMIN
SERVERFINISHLAUNCH Ds1CONNECTION POOL TABINITILA
CAPACITY =5MAX CAPACITY300MIN
CAPACIYT=10SAVEADVANCEDSTRINK
FREQUENCY1000save

1000DESTROY the ideal connection of connection pool for every


1000 seconds
In the above process the jdbc DataSource object that is pointing to jdbc
connection pool will be registered with jndi registry automatically.

For above diagram based application refer application-10 of page


no-121
How many types of connection are there?
a. Direct connection (created by the programmer manually)
Class.forName(---);
Connection con=DriverManager.getCOnnection(----);
b. Pooled jdbc connection

Connection con=ds.getConnection();
Gets the con obj from jdbc conn pool.
Date

26-Jun-15

Procedure to create jdbc connection pool for oracle in GFNtAj11domain sever of


GlassFish4.x
Step-0) place odbc14/6.jar file in <Glassfish_home>\domain\GFNtAj11\lib\ext
folder.
Step-1) start GFNtAj11 server
<GlassFish_home>\bin>asadmin start-domain GFNAj11
Step-2) open admin console
http://localhost:4646
user name
password
step-3) create jdbc connection pool for oracle
step-4) crate jdbc datasource pointing to the above jdbc con pool.
Adminconsole->resources >jdbc>jdbc connection
pool>new>poolname=pool1>resource type=java.sql.datasource>driver
vendor>oracle>next>pool size=10 (min) >max pool size=100>pool
Crating datasource:

Admin console>jdbc>
Jdbc resources (datasource) >new >jndi name(Dsjndi)>pool name=pool1>ok
To deploye poolapp(App10) in the server export war file from eclipse IDE to
----<GlassFish_home>\domains\GFNtAj11\autodeploy folder.
TO test the application:http://localhost:7788/PoolApp/index.html

Procedure to create jdbc connection pool in Tomcat 8 server


step-1) make sure that tomcat-jdbc-.jar file is available in <Tomcat_home>\lib
folder if not available arrange it.
Step-2) place ojdbc14.jar/6.jar file in <Tomcat_home>/lib folder.
Step-3) place <Resource> tag under <context) tag under
<Tomcat_home>\conf\Context.xml file.
<Resource name="DsJndi" type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="oracle.jdbc.oracle.OracleDriver"
url="jdbc:oracle:thin:@localhost:1522:orcl"
usernaem="scott"
password="tiger"
initialSize="10"

/>//Dsjndi is jndi name


DataSourcFactory is factory class that return data source object.

Step-4 start the server.

DataSource ds=(DataSource)
To deploy poolApp (App10) in Tomcat server
a) Change jndi name at lookup(-) as shown below.
InitialContext ic=new InitialContext();
DataSource ds=(DataSource)ic.lookup(java:/comp/env/DJndi); (refer 1232 of
page no-123)
-------b) Deploy the web application
Export Eclipse project (war) to Tomcat server.
c) Test the application
http://localhost:3030/PoolApp.

While working with tomcat that is configured with eclipse ide we can place
content in xml file by using project explorer\server\Tomcat8\context.xml file.

JavaBean:-It is java class that is developed with set of rules


a) Should be public class should not be abstract or final class.
b) May or may not implements serializable interface(I).
c) Member variable must be private and non-static

d) Should have zero parameter constructors directly or indirectly.


e) Every properties have accessor method (setter and getter method)
Note:-setter method is useful to write data from bean properties.
And getter method is useful to read data from bean properties.
Example:public class Student
{

private int sno;


private String sname;

public void setSno(int sno)


{
this.sno=sno;
}

public void setSname(String sname)


{

this.sname=sname;
}

public int getSno()


{
return sno;
}

public String getSname()


{

return sname:
}
}

Note:- we always use java Bean as helper classes in projects.


1) The java Bean class whose object can hold
end user/client supplied data is called VO
class(value object)

2) The java bean class whose obj holds data as


required for Persistence
operations/business operations is called
BO-class /Domain class(Business Object)
3) The java bean class whose obj can be used
to transfer data b/w two components or
layer is called DTO class (Data Transfer
Object).
This class implements Serilizable interface.
If one component want to pass huge amount of data from one layer to another
layer dont pass the data as multiple individual values, always pass that data in
the form of object.(java bean) from one layer to another layer.

27-Jun-15
DAO: The java class that separated persistence logic from other logic of the
application to make persistence logic as flexible to modify and
reusable logic is called DAO.
In real-time one project contain multiple DAO one per table strategy.

The java class that contains business logic is called service logic.
The java class that contains persistence logic is called DAO class.

29-Jun-15
Servlet communication : It is all about knowing how servlet prog gets requests and how servlet

prog pass the request to other servlet porgs/ jsp prog/ web resource
progs.
Sometimes the request given to servlet prg takes the support of another

servlet prog to process the request. This demands servlet to servlet


communication.
We can see servlet communication in multiple models.

Web components communications/servlet to servlet


communication/servlet changing

When source servlet passes the request destination servlet or jsp

program the servlet container perform all life cycle activities on


destination program.
There are two ways of servlet to servlet communication/Servlet

chaining.
1. Forwarding request
2. Including response

1. Forwarding request
Source servlet program forwards the request to destination program
and discards the output of source program and sends only the output
of destination prog as response.

A---forwards to--B, output: - B output

2. Including response: Source servlet program include the output of destination program
and sends both outputs together as response to browser.
A---include-B output: A output and B output.
In servlet chaining the source servlet program uses object to locate and

interact with destination program either by forwarding request or by


including response.
RequestDispatcher object mean it is object of underlying server

container supplied java class that implements


javax,servlet.RequestDispatcher(I).

Different approaches of creating request dispatcher object:-Approach=1) using request object.


In source servlet program:RequestDispatcher rd=req.getRequestDispatcher(/s2url);
destination servlet/jsp prog.

Here /s2url is url patter of

/:- is optional

rd.forward(req,res);performs forwarding request


(or)

rd.include(req,res); performs including response.


Approach-2) using ServletContext object.
In Source servlet program:
ServletContext sc=getServletContext();

RequestDispatcher rd=sc.getRequestDispatcher(/s2url);here / is
mendatory
rd.forward(req,res);
(or)
rd.include(req,res);
Note:- a) if the destination is jsp prog then pass jsp file name or url
pattern as argument.
B ) if the destination is servlet prog then pass the url pattern as
argument
C ) if the destination is html file then pass the filename as
arguments.
Approach-3) Using ServletContext:
In source servlet prog
ServletContext sc=getServetContext();
RequestDispatcher rd=sc.getNameDispatcher(s2);
//Here s2 is logical name given in <servlet-name> tag for
destination servlet prog /jsp prog.
rd.forward(req,res);
(or)
rd.include(req,res)
Different between getRequestDispatcher and getNamedDispatcher(-)
method.

getRequestDispatcher(-)

getNamedDispatcher(-)

In-vocable on ServletContext, request

Invokable only on ServletContext

objects.

object.

Takes url pattern or file name of


destination prog as argument.

Allow the html file as destination prog.

Takes the logical name of destination


prg given in web.xml using<servletname> tag as argument.

Does not allow, because we cannot


provide logical name for html file.

Q) What is difference between creating RequestDispatcher obj by using


request obj or by using ServletContext object.

The request obj based on RequestDispatcher allow keeping the


source and destination web components in the same web
application.
The ServletContext object based RequestDispatcher allows to keep
the source and destination prog either in same web application or in
two different web application of same server. But not in two different
web application of two diff server(for this use SendRedirection
concept)

30-Jun-15

The html output of source prg (srv1) will be discarded and only html
output of Destination prog(srv2) prog goes to browser window as
response.
Key points
rd.forward(-,-) performs the forwarding request mode of Request
Dispatching.
The source servlet prog and destination prog uses same request and
response obj so the request data coming to source prog(srv1) is
visible and accessible in Destination prog(srv2)
To pass additional data b/w source prog and destination prog use
request attribute.
Srv1 and srv2 prog can be there in same web application or can be
there in two diff web application of same server.

Srv2 can be a servlet prog or jsp prog or html file.


All the statements placed in before and after rd.forward(-,-) execute
but their output will be discarded.
Final response contains only the html output of des prog (srv2) and
this goes to browser though source prog (srv1)
rt.forward(-,-) is very useful to configure error servlet in web
application.
Q- What is error servlet?

The servlet prog that executes only when exception is raised in other
servlet prog is called Error servlet.
This error servlet prog is use to display non-technical guiding error
messages to end user when exceptions are raised in main servlet
prog.
Note: - it is always recommended to place rd.forward(-,-) in
source prog as a conditional statement to execute.
Sample code to add ErrorSrv support to DBApp web application

Step-1) keep DBApp web application ready


Step-2)Develop ErrorServlet
ErrorSrv.java
package com.nt;

public class ErrorSrv extends HttpServlet


{

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


{

//general Setteings

PrintWriter pw=res.getWriter();
res.setContentType("text/html");

//Generate non-

//technical guiding message.

pw.println("<font color='red'> internal porblem try again</font>");


pw.println("<a href='input.html">Home</a>");

//colse stream
}

pw.close();

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


{

doGet(req,res);

Configure com.nt.ErrorSrv pog in web.xml file with /eurl url


pattern.
Step-3) develop main servlet prog to forward request to
ErrorServlet when exception is raised.
public class DBSrv extends HttpServlet
{
public void init()
{
....
....

}
public void doGet(0,0) throws SE,IOE
{
try
{
::::::::::::::
:::::::::
//code that may raise exception
::::::::::::
:;;;;;;;;
}
catch (Exception e)
{

RequestDispatcher rd=req.getRequestDispatcher("/eurl");
rd.forward(req,res);
}
}//doGet()
public void doPost(-,-) throws SE,IOE
{
doGet(req,res);
}//doPost()
public void destroy()
{
:::::
::::::::
::::::
}//destroy
}//class

01-Jul-15
What happen if we place multiple rd.forward(-,-) mehods in one source
servlet porg?
AnS: java.lang.IllegalStateException : cannot forward after response has been

committed will be raised.


Though exception comes on the server console, but the first

rd.forward(-,-) related webpage will be displayed on the browser


window.

Understanding rd.include(-,-):-

Key points: rd.include(-,-) performs including response mode of request


dispatching.

Both source and destination program use same request, response


object. So the requested data coming to source prog is visible and
accessible in destination prog.
We can pass additional from srv1 prog to srv2 prog in the form of
request attributes .
Srv1, srv2 can be there in same web application or can be there in
two different web application of same server.
Sr2 can be a servlet prog/jsp prog /html prog.
All the statement srv1,srv2 progs executed and their output goes to
browser window as final response.
Srv2 output will be included to the output of srv1 porg in the
place where rd.include(-,-) method is called.
Useful to include the output of common logics(header and footer) in
the main web resource prog of the web application.

\
Sample code:
Headersrv.java(HeaderServlet)
public class HeaderSrv extends HtttpServlet
{
public void doGet(-,-) throws Se.IOE
{

//general setting
.....
.....
pw.println("<h1><marquee> H C L Technologies<.marquee></h1>");
}

//do not close stream

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


{
}
}

doGet(req,res)

configure "com.nt.HeaderSrv" in web.xml file with "/headurl" url


pattern
Footer.html
<br> <br><br>
<b> <center><i> &copy; all right reserved</i> </ecnter></b>

public class DBSrv extends


{

public void init()


{

...
...

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


{

//general setting
............
........

.........

try
{

//header content

RequestDispatcher rd=req.getRequestDispatcher("/header.html");
rd.include(res,req);

.....
.......

//body content

catch (Exception e)
{

RequestDispatcher rd3=req.getRequestDispatcher("/eurl");
rd.forward(req,res);

e.printStackTrace();

}//doGet()

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


{

doGet(req,res);

For complete example- refer application -13 of page-127 to


131.
pw.close() method commit the response and does not allow the
programmer to add further content to response object.
While working with rd.inclde() dont palce pw.close() in destination
servlet prog because it doesnot allow to add further content to
response object.
Dont place pw.close() before rd.include() or rd.forward() because it
fails request dispatching by throwing illegal state exception
if multiple rd.inclue() mehod in place in one source servlet program.
The output of multiple destination programs will be included to
source.

If we place both rd.forward() and rd.include() in one servlet program


the effect of rd.include() will not be there because rd.forward()
discard not only the html output of source prog it also discard the
included html output.

03-Jul-15

Date:

Request Dispatching between two different web applications of same


weblogic server:

In the above application both web application

In FSrv.java
ServletContext sc1=getServletContext();//gives sc of WAOne
ServletContext sc2(it is a foreign context)=sc1.getContext(WATwo);//gives sc
of WATwo
ResponseDispatcher rd=sc2.getRequestDispatcher(/s2url);//gives rd

obj

//pointing to SSrv prog of WATwo


rd.include(req,res);

Here the source FSrv prog and dest SSrv prog use same request, response objs so
the form data coming to FSrv prog is visible and accessible in SSrv prog.
WAOne(Eclipse dynamic web project)
|---src
|---com.nt
|---FSrv.java
|---webroot
|---Form.html
|---WEB-INF
|---web.xml

WATwo(Eclipse dynamic webpage)

|---src

|---com.nt

|---webroot

|---SSrv.java

|---WEB-INF
|---web.xml

Deploy both WAOne, WATwo web application in weblgics NTAj11 domain


server;
Resource urls: http://localhost:7070/WAOne/Form.xml
The ServletContext object of different web application that is
accessed from ServletContext object of current application is called
foreign context.
The above application cannot be execute in tomcat web server
because the getContext() method will not work directly by
Tomcat, GlassFish, jboss due to this NullPointerException will
be raised but same method is implemented properly in web
logic server so we can execute the above application in
weblogic server.
What is the difference b/t rd.forward(-,-) and rd.include(-,-);
rd.forward(-,-).

rd.include(-,-)

Perform forwarding request mode

Perform including response mode

of RequestDispatching.

of RequestDispatching.

Discards the html output of source Does not discards the output of
prog.

source program.

Final response contains only the

Final response contains the html

html output of destination prog.

output of both source and

Useful in errorServlet

Useful in including the common

communication.

logic of application.(header, footer)

destination prog.

Limitations with request Dispatching


1. The source and destination program must be there in same web
application or can be there in two different web application of
same server.(only in web logic) that means the source and
destination program cannot be remote web resource programs.
2. The destination program cannot be taken as ASP .net prog or php
program, it must be taken as jsp, html, and servlet prog.

03-jul-15
Note:- To make getContext(-) method working in Tomcat server add
corssContext=true in <Context> tag of <Tomcat_home>\conf\Context.xml file.
To overcome this problem use SendRediretion mode of servlet
communication.
In send redirection the source servlet program communicates with
destination prog after having one network round trip with browser
window.

2 ways of send redirection:-

a. Using Hyperlink (not recommended)

b. Using response.sendRedirect(-) (Recommended)

In send Redirection the source servlet prog talks with Dest prog

through browser window due to this the destination prog can be local
or remote prog and can be there in any technology.
In RequestDispatching based communication source prog talks with

destination prog directly.

SendRedirection through Hyperlink:-

In the above technique the end user has to click on hyper link to

redirect request to other web application if he forget to do then no


redirection takes place.

Configure com.nt.searchSrv prog in web.xml file with /search url pattern


Run the application
http://localhost:3030/SRDApp1/Form.html

To overcome the problem of hyperlink based sendRediretion use


res.sendRedirect(-) method.

Understanding res.sendRedirect(-) method:-

1. With respect to the diagram browser gives initial request to srv1


2. All the statements of Srv1 executes including res.sendRedirect(-)
Due to this srv1s output will be discarded.

3. Srv1 sends implicit response to browser having the url placed in


res.rendRedirect(-) method. This response status code is 300 to
399 asking browser window to perform redirection.
4. Based on received url browser window gives implicit request ot
srv2 prog.
5. & 6 All the statements of Srv2 execute and final response goes to
browser.
This response status code is 200.
res.sendRedirect(/s2url); //relative url
res.sendRedirect(http://M2:7070/WA2/S2url); // absulate url
KeyPoints:
Perform sendRedirection mode servlet communication.

No need of working with any hyperlinks.


Srv1 talks with srv2 through browser window.
Srv1 and srv2 can be there in either in same web application or in
two different web applications of same or different servers.
Srv2 can be a servlet, jsp, html or php, Asp.net or any web prog.
If Srv2 is local of srv1 then pass relative url otherwise pass absolute
url.
Srv1 and srv2 does not use same req, resp object so req data coming
from srv1 is not visible to srv2.
To pass additional data from srv1 to srv2 append query string to

All the statement place before and after send method will execute but
their output will be discarded.
To redirect one website request to another website this
response.sendRedirect method is useful.
Example: IBM has acquired rational company so request
given to reational.com goes to ibm.com.
Using send redirection we can not include the response in any angle.

04-Jul-15

For above application refer page -138 to 39.

Important Points: If we commit response by calling pw.close() before


res.sendRedirect(_) method then IllegalStateException will be raised
If we call multiple res.sendRedirect method in one source servelt
program then exception will be raised (IllegalStateException)

If we place both rd.forward and response.sendRedirect in one servlet


program then exception will be raised.
If we place rd.include(-,) and response.sendRedirect(-) in one source
servlet program then the effect of rd.include(-,-) will not be there.
What is the different between rd.forware(-,-) and res.sendRedirect(-)
method?
rd.forward(-,-)

res.sendRedirection(-)

Perform forwarding request.

Perform SendRedirection

Source prog talks with destination

Source prog talks with destination through

Source and destination program use

Source and destination prog doesnt use same

The req data coming from source prog

Not visible and accessible.

directly

same request, response object.

browser window.

request, response object.

is visible and accessible in destination


program.

To pass additional data from source

To pass additional data use append Query

prog to destination prog use req

string to url of res.sendRedirect() method .

Does not change the url in browser url

Changes the url

Useful when source and program are

Useful when source and destination prog are

Useful for error servlet communication.

Useful to redirect the req coming to one

attribute.

while forwarding the request.


local to each other.

remote to each other.

website to another website.

In servlet programming Attribute is a logical name that holds value. It is


no way related to xml/html tag attributes.
How to pass Data b/w the web resource prog of the web application
If source and destination prog are there in same web application:

a) Request attributes
(when source and dest prog use same request object)
b) Session attributes
o (When source and desti prog get request from same browser.
c) Application attributes/ServletContext attributes
o (when source and prog and not using same request obje and not
getting request from same browser)
If source and destination are not there in same web application
a) Append query String to url of response.sendRedirect(-) method.
o response.sendRedirect(rul?<queryString>

Date: 06-Jul-15
These attributes allocate memory in request object.
These attribute scope is request scope means attribute is specific to each

request.
These attribute is visible to throughout request cycle that means if

multiple web resource programs are involves in request processing the


request attribute created in 1 web resource prog is visible and
accessible in other web resource program.

In the above program request attributed created in srv1 porg is visible

and accessible in srv2 and srv3 but not in srv4 because sr1, srv2, srv3
program are using same request, response object.

To create request attribute

req.setAttribute(name,raja);
req.setAttribut(age,30); Here age is attribute name and 30 is attribute
value.
To modify request attribute value

req.setArrtribute(age, 40);//auto boxing takes place here


req.setAttribute(name, king);
Note:- set attribute method create attribute method if that attribute is not already
available modifies the existing value if that attribute is already available.
Note: Name should must be string and value should be object. (it internally auto
casted into values)
To read request attribute value
String name=(String)req.getArribute(name);

int age(auto unboxing takes place here )=(Integer)req.getAttribute(age);


Note:- The process of converting simple values into an object(wrapper class
object) is called auto boxing and revers is called auto unboxing.
To remove request attribute:
req.removeAttribut(name);
req.removeAttribute(age);
Session Attribute: HttpSession object allocates memory on server on

basis.

one per browser

HttpSession object is the object of underlying container supplied java

class that implements javax.servlet.http.HttpSession(I)


All window of browser s/w that are opened in a machine will be treated

as same Client. Browser tabs are also part of browser window.


Session attributes allocates memory in session object having sessions

scope.
These attribute are visible in all the web resource prog of web

application irrespective of request, response object they are using, but


they must get request from that bowsers for which HttpSession object
and session object created.

> session attribute is crated in srv1 program by getting request from browser is
visible and accessible in other web resource program irrespective of req, res
object they are used but they must also get request from same browser b1.
-> To crate Session attribute

HttpSession ses=req.getSeesion(); //create locate Session object.


ses.setAttribute(user,ravi);
To modify session attribute
ses.setAttribute(user,Ramesh);

To read Session attribute values:String un=(String)ses.getAttribute(user);

To remove session Attribute


ses.removeAttribute(user);

ServletContext Attribute/Application attribute:: These attributes allocate memory in servlet context object which is

global memory of web application.


Attributes scope is application scope that mean they are visible in all

web resource prog of web application irrespective of any condition.(i.e


irrespective of request, response object they are using and irrespective
of browser window from which they are getting request)
The ServletContext attribute created in srv1 prog is visible and

accessible for all conditions (Global attributes)

To crate servletContext attribute:

ServletContext sc=getServletContext();//access the servlet context object


Sc.setArrtibute(email,bhartinarendra0@gmail.com);
To read ServletContext attribute value

String mail=(String) sc.getAttribute(email);


To modify ServletContext attribute value:

Sc.setAttribute(email,natraz.in);
To remove Servlet attribute value:

Sc.removeAttribute(email);
For example application of the above three attribute refer app-18 of
page no=139to141.
This diagram shows rendering dynamic form pages and stateless behavior of the we application

09-Jul-15
Session tracking/session Management Techniques

10-Jul-15
Http Cookies (Technique-2)
Df

11-Jul-15
Placing jdbc code in servlet program is not recommended process. It is

always recommended that code in DAO class and sends data from
servlet prog to DAO class. In the form of VO class or BO class object.
(java bean).

NOTE: SERVLET RAPPER

12-Jul-15
ServletWrapper:public interface Test
{

public void x();


public void y();
public void z();
}

public TestImpl implements Test


{

public void x(){}


public void y(){}
public void z(){}
}

Here TestImpl will be forced to implements all the 3 mehods of Test(i)

and we cannot just one method.


o Solution: Adapter class
public class TestADapter implemnts Test
{

public void x(){}


public void y(){}
public void z(){}
}

Adapter class:-

The class that implements interface and provides empty definitions


for method (null methods) is called Adapter class.
If our class implements interface directly then our class should
provide definition for all the methods of interface.
Instead of that we can make our class extending from adapter class
so that we can override that method, in which you are interested one.

Need of Servlet Wrapper


Wrapper that is surrounding new item that is surrounding an
existing item. i.e core java every Wrapper class surrounds simple
data type.
If want to additional content to existing request content or response
content we should not use serlvletContainer supplied req, res object,
we need to develop our custom classes to create req, res objs. To
Crete custom request class take a class implementing
ServletRequest(I)/HttPServletRequest(I) but it is complex process
because these interfaces process more methods to implements.
Similarly to create custom Response class take a class implementing
ServletResponse(I)/HttpServletResposne(I) but it is also complex
process.
Eg: Public class MyRequest implements ServletRequest
{
//many methods

.
}
Public class MyResposne implements ServletResponse
{
//many method.
;;;;
}
To overcome the above problem we can use servlet Wrapper classes

given form servlet api 2.3 they are:

Note:- if we develop Custom Request, CustomResponse classes by


extending from the above wrapper classes(Adapter classes) then we
can override that method in which we are interested in.
Example:
UseCase-1: Adding @gmail.com if domain name in not given
(RequestWrapper)
USeCase-2: Adding signature response at the end of response
(ResponseWrapper)
Note: - To custom Request, response object to our servlet prog we use ServletFilter
support. This filter creates Custom Request obj over normal req obj and Custom
response object over normal response objs calls fc.doFilter(-,-) to pass them to
servlet prog.

WrapperApp(EDWP)
|--java resourecs
|--src

|--com.nt.filter

|--LoginFilter.java

|--com.nt.servlet

|--LoginServlet.java

|--com.nt.Wrappers

|--MyRequest.java

|--MyResquest.java

|--webcontent
|--Login.html
|--WEB-INF

|--web.xml

Date:

13-Jul-15

Session Management content in book only.

09-Sep-15

Abstact class with abstract method.

o Abstract class with no abstract method.


GenericService Support only hidden form field technique

o http support all the four technique of session


tracking.
Working with ServletOutputStream=>
The servlet porg can use either PrintWriter (character stream) or
ServletOuputStream(byte stream) to write ouput content to response
object.
Use PrintWriter use when there is need of writing more character
data and less binary data (image).
PrintWriter pw=res.getWriter();
pw.println(<b>Hello</b>);
Use ServletOutputStream where there is need of writing more binary
data and less character data.
ServletOutputStream sos=res.getOutputStream();
Sos.println(<hello>);
We can use only stream at a time to write the content to response
object.

26-Jul-15

File uploading and downloading


The process of selecting file from client machine file system and sending that file to
server machine file system is called file uploading and reverse is called downloading.
In the development of Matrimony application, job portal apps and etcThese file
uploading and downloading concept are quite required.
To allow end user to performing file uploading use file uploading component by using
<input type=file>.

To receive uploaded file from servlet use request.getInputStream() method and write to
server machine file by using OutputStream support. This is very complex process.
To minimize this complexity we use third party api called javazoom api(download jar
file from www.javazoom.net)
o Javazoomapi jars
o Struts.jar, cos.jar,
(dependent jar file)

uploadbean.jar
(main jar file)

If java application uses third party api then we need to add both main and jar files of
that third party api to class path.
If servlet component uses third party api then we need to add both main and dependent
jar file of third party api to WEB-INF \lib folder.

Important classes of java.zoom api.


MultiPartFormDataRequest

Wrapper on request object having capability to hold the multiple


MIME types based data like text, audio, video and etc..

UploadBean

Allows to set Destination folder for file uploading and also file for
completing file uploading.

UploadingFile

Represents each file that is uploaded.

File downloading
Two Types of file downloading:a> Response downloading
Here the output of we resource prog (like servlet porg/jsp prog) goes to
browser as downloadable file.
b> Resource downloading
Here the entire content of resource belongs to web application or
server machine file system like audio files, video files will be
downloaded.

By adding following two lines of code in any servlet program or jsp program, we
can make output (response) of those program as downloadable.

In a servlet/jsp prog
res.addHeader(content-disposition,attachment;filename=Title1.doc);
res.setContentType(application/ms-word);
The above code takes the output of servlet/jsp prog and gives instruction to browser to
provide form downloading dialog box to download the file.

Vous aimerez peut-être aussi