natraj servlet2015
TRANSCRIPT
-
8/17/2019 Natraj Servlet2015
1/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
programsends 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
-
8/17/2019 Natraj Servlet2015
2/148
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)
-
8/17/2019 Natraj Servlet2015
3/148
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 twotypes 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.
-
8/17/2019 Natraj Servlet2015
4/148
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
FirefoxMozilla
Hot Java Red Hat
Chromefrom Google (1)
Operafrom Opera soft
List of server side web technology to develop server side web resource
program
ServletsFrom 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)
-
8/17/2019 Natraj Servlet2015
5/148
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
-
8/17/2019 Natraj Servlet2015
6/148
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.
-
8/17/2019 Natraj Servlet2015
7/148
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
-
8/17/2019 Natraj Servlet2015
8/148
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
-
8/17/2019 Natraj Servlet2015
9/148
2015-04-15
While installing Tomcat server we need to supply the following details;
a) Jre location
b) http port no:2525 (default 8080)
c) Tomcat installation folder:D:\Tomcat8.0()
d) Administration details: UserName: admin
Password: admin
Note: install in other than c:
To start Tomcat Server:
Go\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 \conf\server.xml file and modify the “port”
attribute value of first tag and restart the server.
Understanding installation Directories of Tomcat
D:\Tomcat8.0
|-bin
http://http//localhost:2525%20%20%20(hosthttp://http//localhost:2525%20%20%20(hosthttp://http//localhost:2525%20%20%20(host
-
8/17/2019 Natraj Servlet2015
10/148
|*.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 \webapps folder either in the form of directors or
war files.
War files: web application archieve. \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.
-
8/17/2019 Natraj Servlet2015
11/148
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
-
8/17/2019 Natraj Servlet2015
12/148
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 :
-
8/17/2019 Natraj Servlet2015
13/148
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).
-
8/17/2019 Natraj Servlet2015
14/148
Server side web technologies
-
8/17/2019 Natraj Servlet2015
15/148
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
-
8/17/2019 Natraj Servlet2015
16/148
2015-04-17
Definition of servlet
Servlet is java based server side web technology to develop dynamic web1.
resource program or component having capability to generate dynamic
web pages.
Servlet is java based web technology whose web resource program can2.
extend the functionality of web server or Http server.
Servlet is java based technology that allows to develop single instance3.
multiple threads based server side web component in java web application
having the capability to generate dynamic web pages(Refer pervious
diagram)
Servlet is a JEE module technology/specification that gives api for vendor4.
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.
-
8/17/2019 Natraj Servlet2015
17/148
-
8/17/2019 Natraj Servlet2015
18/148
In tomcat server \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.
-
8/17/2019 Natraj Servlet2015
19/148
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”.
-
8/17/2019 Natraj Servlet2015
20/148
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.
-
8/17/2019 Natraj Servlet2015
21/148
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. Thisis 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************
2015-04-10
Our servlet class(DateSrv) hierarchy is javax.servlet.Servlet Interface
javax.servlet.Servlet
^
| implements
Javax.servlet.GenericServlet(AC)
-
8/17/2019 Natraj Servlet2015
22/148
^
| 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 textdocument.(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.
-
8/17/2019 Natraj Servlet2015
23/148
Pw.println(“ Hello”);
This method writes given msg( hello) 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 variablevariable 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.
abc--abc is logical name
-
8/17/2019 Natraj Servlet2015
24/148
com.nt.DateSrv--
com.nt.DateSrv is fully --qualified name acting serlet
programming
abc--abc must match with
above
--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\bin\tomcat8.exe file
Step7) deploy the web application (DateApp)
Copy e:\DateApp folder to \web app
Step8) talks about deployment of web application
Step9) Test the web application
Request url in browser window: http://localhost:3030/DateApp/test1
http://localhost:3030/DateApp/test1http://localhost:3030/DateApp/test1http://localhost:3030/DateApp/test1http://localhost:3030/DateApp/test1
-
8/17/2019 Natraj Servlet2015
25/148
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 applicationwill 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
page-Manager appusername:admin and
password:adminsubmit
Tomcat web application manager window DateAppreload
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).
-
8/17/2019 Natraj Servlet2015
26/148
*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.
-
8/17/2019 Natraj Servlet2015
27/148
-
8/17/2019 Natraj Servlet2015
28/148
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 webpage.
-> 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
-
8/17/2019 Natraj Servlet2015
29/148
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 tags under tage for
this)
Example:
abc
/nit.c
/abc/xyz/nit.cpp
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)
http://localhost:3030/DateApp/nit.chttp://localhost:3030/DateApp/nit.chttp://localhost:3030/DateApp/abc/xyz/nit.cpphttp://localhost:3030/DateApp/abc/xyz/nit.cpphttp://localhost:3030/DateApp/abc/xyz/nit.cpphttp://localhost:3030/DateApp/nit.c
-
8/17/2019 Natraj Servlet2015
30/148
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{
}
catch(Exception e){
}
pw.println("
hascode of request obj"+req.hashCode()); -
8/17/2019 Natraj Servlet2015
31/148
pw.println("
hascode of response obj"+res.hashCode());pw.println("
hascode of our servlet classobject"+this.hashCode());
pw.println("
hascode of current threadobj"+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)
-
8/17/2019 Natraj Servlet2015
32/148
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- /lib/catalina.jar file
2015-04-24
Generic servlet gives only service method that is
-
8/17/2019 Natraj Servlet2015
33/148
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 don‖t 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?
-
8/17/2019 Natraj Servlet2015
34/148
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 page-
105,106
Step-6) Start Tomcat server.
Step-7) Deploy the web application
Copy E:\MIMEApp folder to \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
-
8/17/2019 Natraj Servlet2015
35/148
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
-
8/17/2019 Natraj Servlet2015
36/148
abc
com.nt.DateSrv
abc
/test
-
8/17/2019 Natraj Servlet2015
37/148
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 browser‖s
address bar.
d) Based on localhost:3030” of request url the Tomcat server takes the request.
-
8/17/2019 Natraj Servlet2015
38/148
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.xml‖s 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
-
8/17/2019 Natraj Servlet2015
39/148
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)
-
8/17/2019 Natraj Servlet2015
40/148
21-May-15
-
8/17/2019 Natraj Servlet2015
41/148
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("
our servlet class object hashcode"+this.hashcode());pw.println("
req obj hash code "+req.hashCode());pw.println("
res.hashcode"+res.hashCode());pw.println("
current thread is "+Thread.currentThread().hashCode()); -
8/17/2019 Natraj Servlet2015
42/148
{
}
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 todisplay 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
Start — run — regedit — HKEY_CLASS_ROOT — choose 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”.
-
8/17/2019 Natraj Servlet2015
43/148
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 doesn‖t allow workingwith 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
-
8/17/2019 Natraj Servlet2015
44/148
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(-,-) /2nd 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)
http://locahost:3030/MIME/sturlhttp://locahost:3030/MIME/sturlhttp://locahost:3030/MIME/sturl
-
8/17/2019 Natraj Servlet2015
45/148
^
| 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
patternHtml, 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 communicateon:
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
-
8/17/2019 Natraj Servlet2015
46/148
(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”.
-
8/17/2019 Natraj Servlet2015
47/148
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.
Click here to ger wish message
(wishurl is wishsrv servlet prog)
wish Message
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.
-
8/17/2019 Natraj Servlet2015
48/148
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 WEB-
INF 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 WEB-
INF folder can be access directly from client so its configuration in
web.xml file is not required.
-
8/17/2019 Natraj Servlet2015
49/148
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
chck u r voting eligiblity
method="get"
-
8/17/2019 Natraj Servlet2015
50/148
>
Person name:
person age:
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
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
-
8/17/2019 Natraj Servlet2015
51/148
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
-
8/17/2019 Natraj Servlet2015
52/148
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.
-
8/17/2019 Natraj Servlet2015
53/148
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- /test1
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- /test1.c2) Eg2- /abc/xyz/test2.c
3) Eg3- /nt/nt1/test.aspx
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:- /images/books/*
Request urls:
http://localhost:3030/DateApp/test1http://localhost:3030/DateApp/test1http://localhost:3030/DateApp/test1.chttp://localhost:3030/DateApp/test1.chttp://localhost:3030/DateApp/test1.xyzhttp://localhost:3030/DateApp/test1.xyzhttp://localhost:3030/DateApp/test1.xyzhttp://localhost:3030/DateApp/test1.chttp://localhost:3030/DateApp/test1
-
8/17/2019 Natraj Servlet2015
54/148
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:- /abc/xyz/*
eg- /x/y/*
eg- /y/*
eg- /nt/it/Tech/*
Extension Match url pattern
Syntax: *.
Eg- eg- *.do
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:- *.c
Eg1:- *.nit
Eg1:- *.htm
The servlet that takes all requests having different request urls and
delegates the request other web resource pgors is called Front
http://localhost:3030/DateApp/images/books/hello.chttp://localhost:3030/DateApp/images/books/hello.chttp://localhost:3030/DateApp/images/abc.chttp://localhost:3030/DateApp/images/abc.chttp://localhost:3030/DateApp/books/images%20/hello.chttp://localhost:3030/DateApp/books/images%20/hello.chttp://localhost:3030/DateApp/images/bookshttp://localhost:3030/DateApp/images/bookshttp://localhost:3030/DateApp/abc.dohttp://localhost:3030/DateApp/abc.dohttp://localhost:3030/DateApp/xyz/abc/x.dohttp://localhost:3030/DateApp/xyz/abc/x.dohttp://localhost:3030/DateApp/abc.xhttp://localhost:3030/DateApp/abc.xhttp://localhost:3030/DateApp/abc.do/xyz.chttp://localhost:3030/DateApp/abc.do/xyz.chttp://localhost:3030/DateApp/.dohttp://localhost:3030/DateApp/.dohttp://localhost:3030/DateApp/.dohttp://localhost:3030/DateApp/abc.do/xyz.chttp://localhost:3030/DateApp/abc.xhttp://localhost:3030/DateApp/xyz/abc/x.dohttp://localhost:3030/DateApp/abc.dohttp://localhost:3030/DateApp/images/bookshttp://localhost:3030/DateApp/books/images%20/hello.chttp://localhost:3030/DateApp/images/abc.chttp://localhost:3030/DateApp/images/books/hello.c
-
8/17/2019 Natraj Servlet2015
55/148
controller servlet. While configuration this servlet we need to use
either directory match or extension match url patterns.
/test1/test2.c
(it is exact match url pattern)
/x/y/*.do (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.
http://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.chttp://localhost:3030/DateApp/xyz/test.c
-
8/17/2019 Natraj Servlet2015
56/148
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: Male
: 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)
-
8/17/2019 Natraj Servlet2015
57/148
In web application develop and to make web application as WODA
application and to support WODA behavior of application we shouldprefer working with relative url instead of relative url.
Page.html
< a href=”http://localhost:3030/wishurl”> wish Msg
-absolute url----------------------------------
< a href=”wishurl”> wish Msg
-relative url----------------------------------
Input.html
< a href=http://localhost:3030/vturl> wish Msg
-absolute url----------------------------------
http://localhost:3030/wishurlhttp://localhost:3030/wishurlhttp://localhost:3030/wishurlhttp://localhost:3030/wishurlhttp://localhost:3030/wishurlhttp://localhost:3030/wishurlhttp://localhost:3030/wishurl
-
8/17/2019 Natraj Servlet2015
58/148
-
8/17/2019 Natraj Servlet2015
59/148
-
8/17/2019 Natraj Servlet2015
60/148
To install s/w extract the zip file.
For help www.glassfish.org
Procedure to crate user defined domain in Glassfish 4.x server
/bin>asadmin create-domain --adminport=4646
--user=testuser GFNtAJ11
4646 is admin port number
testuser – admin user name
GFNtAJ11 — domain 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.
http://www.glassfish.org/http://www.glassfish.org/http://www.glassfish.org/
-
8/17/2019 Natraj Servlet2015
61/148
To change “http” port no of the above domain server:
Go to
\domains\GFNTAJ11\config\domain.xml
And modify port attribute value of first 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
\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 ok deployee 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
\domains\GFNtAJ11\autodeploy folder.
Requested url: http://localhost:7788/VoterApp/input.html
http://localhost:4646/http://localhost:4646/http://localhost:7788/VoterApp/input.htmlhttp://localhost:7788/VoterApp/input.htmlhttp://localhost:7788/VoterApp/input.htmlhttp://localhost:7788/VoterApp/input.htmlhttp://localhost:4646/
-
8/17/2019 Natraj Servlet2015
62/148
To stop domain server
\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 \standalone\configuration\standalone.xml
file a tag.
To create username and password required admin console:
User \bin\add=user.bat file
http://www.jboss.org/http://www.jboss.org/http://www.jboss.org/http://www.jboss.org/
-
8/17/2019 Natraj Servlet2015
63/148
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
\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 contentbrows(voterApp.war)nextsaveenable and now test the
application.
http://localhost:8899/VoterApp/input.html
localhsot:8899/voterApp
http://localhost:8899/console/App.htmlhttp://localhost:8899/console/App.htmlhttp://localhost:8899/VoterApp/input.htmlhttp://localhost:8899/VoterApp/input.htmlhttp://localhost:8899/VoterApp/input.htmlhttp://localhost:8899/console/App.html
-
8/17/2019 Natraj Servlet2015
64/148
-
8/17/2019 Natraj Servlet2015
65/148
-
8/17/2019 Natraj Servlet2015
66/148
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 objectButton
b)
Evnet class ActionEvent
c) Event Listener ActionListener
d) Event Handling methodactionPerformed(-)
-
8/17/2019 Natraj Servlet2015
67/148
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 handlingRequest ServletRequestEve
nt
ServletRequestListen
er
requestInitilized(
-)
requestDestroyed
(-)
Session HttpSeeionEvent HttpSessionListener sessionCreated(-)
sessionDestroyed(
-)
ServletConte
xt
ServletConextEven
t
ServletContextListen
er
contextInitlized(-
)
contextDestroyed
(-)
-
8/17/2019 Natraj Servlet2015
68/148
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();
sc.log(req.getRequestURI()+"has taken"+(end-start"+"ms to process
request");
}
}
MySessionListener.java
public class MySessionListener implements HttpSessionListener
{
long start,end;
//executed when session obj is created
-
8/17/2019 Natraj Servlet2015
69/148
public void sessionCreate(HttpSessionEvent hse)
{
start=System.currentTimesMillis();
//write to log filehse.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
hse.getSession().getServletContext().log("sesssion ended at"+(end-
start));
hse.getSession().getServletContext().log("session duration"+(end-
start));
}
}
c)
Configure the above two listener classes in web.xml file.
com.nt.listeners.MyRequestListener
com.nt.listeners.MySessionLIstener
-
8/17/2019 Natraj Servlet2015
70/148
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 foundationfor 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.
-
8/17/2019 Natraj Servlet2015
71/148
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.
HHttp request method (GEG/POST/…)
HHttp request headers (user-agent, referrer, accept,…)
P request parameters( User =raja&pwd=rani)
----query string
httpRequest with example content
-
8/17/2019 Natraj Servlet2015
72/148
what is difference between request headers and req parameters?
Req Header Req Parameters-Names are unique Names are not unique
Carries browser supplied implicit
data.
Carries end user supplied data
(from data)
Names are fixed and unique. Names are user-defined.
-
8/17/2019 Natraj Servlet2015
73/148
-
8/17/2019 Natraj Servlet2015
74/148
-
8/17/2019 Natraj Servlet2015
75/148
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.
http://d/Tomcat%208.0/webapps/SrvConfigApp/ServletConfigApp.javahttp://d/Tomcat%208.0/webapps/SrvConfigApp/ServletConfigApp.javahttp://d/Tomcat%208.0/webapps/SrvConfigApp/ServletConfigApp.java
-
8/17/2019 Natraj Servlet2015
76/148
For related info on request (ServletRequest, HttpServletRequest,
RequestHeader, and etc. refer page no-84 to 87. And also refer page no-
171-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.
-
8/17/2019 Natraj Servlet2015
77/148
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.
-
8/17/2019 Natraj Servlet2015
78/148
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.
-
8/17/2019 Natraj Servlet2015
79/148
(cache-control, pragma – are used for enabling cache/buffering in
browser)
severlet response , httpservlet response and response header refer-page-
87 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.
-
8/17/2019 Natraj Servlet2015
80/148
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.
-
8/17/2019 Natraj Servlet2015
81/148
-
8/17/2019 Natraj Servlet2015
82/148
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.
-
8/17/2019 Natraj Servlet2015
83/148
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 pro‖s 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
-
8/17/2019 Natraj Servlet2015
84/148
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.
-
8/17/2019 Natraj Servlet2015
85/148
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 \lib folder
NtAj11Domain ofweblogic
\user_project\domain\NtAj1(domainname)
GFNtAj11Domain of
GlassFish4.x
\user_pojects\domains\GFNtAJ11\lib\ext
folder
JBoss7.x \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 19-Jun-15
DBApp web application for Eclipse Project.
DBApp(Eclispe Dynamic web project)
|-- java resources
-
8/17/2019 Natraj Servlet2015
86/148
|--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 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.
-
8/17/2019 Natraj Servlet2015
87/148
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 day‖s log file.
-
8/17/2019 Natraj Servlet2015
88/148
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
-
8/17/2019 Natraj Servlet2015
89/148
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
-
8/17/2019 Natraj Servlet2015
90/148
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 applicationwithout modifying the source code of exiting web source prog…
-
8/17/2019 Natraj Servlet2015
91/148
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)
-
8/17/2019 Natraj Servlet2015
92/148
FilterChainfor 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
, 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 is enable.
Sample Filter prog:-
public class MyFilter implements Filter
-
8/17/2019 Natraj Servlet2015
93/148
{
public void init(FilterConfig fg){
//initializaion logic
}
public void doFilter(ServletRequest req,ServeltResponse res,FilterChain fc)throwsIOE,SE
{
...
...//pre-request processing logic
....
chain.doFilter(req,res);//sends the request to the next filter in chainor 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…
-
8/17/2019 Natraj Servlet2015
94/148
c. Request-Response filter (contains both pre-request processing & post-
response 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)
-
8/17/2019 Natraj Servlet2015
95/148
Note:- In the above diagram ServletFilter is having inputs validation logic tovalidate 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-15FilterApp1
|--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)
-
8/17/2019 Natraj Servlet2015
96/148
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 \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:-
-
8/17/2019 Natraj Servlet2015
97/148
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 time8---> 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)
-
8/17/2019 Natraj Servlet2015
98/148
-
8/17/2019 Natraj Servlet2015
99/148
770 to 776 — reading 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 anunregistered (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 tomca