Professional Documents
Culture Documents
Natraj Servlet2015
Natraj Servlet2015
Natraj Servlet2015
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
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)
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)
2015-04-14
To execute applet we need applet program we need applet viewer or
applet container.
What is 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:
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
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
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
javax.servlet,
javax.servlet.http,.
Servlet api 3.x pakgs
Javax.servlet,
javax.servlet.http,
javax.servlet.annotations,
Javax.servlet.descriptor,
2015-04-17
There are three way to develop servlet component/program.
Approach-1) Take a class implementing javax.servlet.Servlet(I) and
-----------------------------------------------------------------------------------------------------------------------------------------------
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
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
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,
<servlet-class>com.nt.DateSrv</servlet-class>--
<servlet-mapping>
<servlet-name>abc</servlet-name>--abc must match with
above
</servlet-mapping>
</web-app>
--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.
<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
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-
implicitly.
Can we place only parameterized constructor in our servlet class?
As) NO
Because ServletContainer creates our servlet class object using
0_paramer constructor.
<url-pattern>/abc/xyz/nit.cpp</url-pattern>
http://localhost:3030/DateApp/abc/xyz/nit.cpp
2015-04-23
Fgdgfd
The modification done in web.xml file will be recognized by
the existing object ( our servlet class object, request, response) object
and etc) will be destroyed.
Reloading web application is nothing but (stopping web application
Thread.
catch(Exception e)
{
}
e.printS
For every object jvm gives one unique value that is hashcode. To get
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
http features.
HttpServletRequest and HttpServletResponse object allow to use
those entire prog web.xml file having unique url pattern logical names.
By specifying different continent type (mime type) in servlet porg by
web application-2
Develop web application having multiple servlet prog to generate web
pages in different format?
http://localhost:3030/MIMEApp/exlurl
20-may-2015
For every request given to servlet program the servlet container creates
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>
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
21-May-15
ServletException,IOException
{
//getPrintWriter object
PrintWriter pw=res.getWriter();
try
{
Thread.sleep(30000);
}
catch (Exception e)
{
}
e.printStackTrace();
{
}
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
|HtmlSrv.java
|ExcelSrv.java
|WordSrv.java
|xmlSrv.java
|com.nt
|*.class(4)
103-60,88,115,143,160,165,170,175,
22-May-15
The super class method can be overridden in subclass either with same
nd
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
^
| implement
Javax.servlet.GenericServlet(Ac)
extends
Javax.servlet.http.HttpServlet(Ac)
extends
Extends servlet class
pattern
Html, jsp file will reside out side web-inf folder (public area0 so their
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
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.
outside of
Servlet prog cfg is web.xml is mendatory because it is place inside
Page.html.
<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
server.xml.
Instead of an exe file we can use zip file. when we use the zip file we
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
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>
>
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
http://localhost:3030/VoterApp/input.html<-- (a)
Input.html(b)
Submit(c)
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.
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>
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.
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>
<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)
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)
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
-4848 (admin)
--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.
container.
<GlassFish_home>\domains\GFNtAJ11\autodeploy folder.
Requested url: http://localhost:7788/VoterApp/input.html
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
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
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.
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
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
Event Listener
Event handling
Request
ServletRequestListen
requestInitilized(
ServletRequestEve
nt
er
-)
requestDestroyed
(-)
Session
HttpSeeionEvent
HttpSessionListener
sessionCreated(-)
sessionDestroyed(
-)
ServletConte
xt
er
contextDestroyed
(-)
long start,end;
start=System.curentTimeMillis();
end=System.currentTimeMillis();
HttpServletRequest req=(HttpServletRequest)sre.getServletRequest();
ServletContext se=sre.getServletContext();
request");
}
MySessionListener.java
public class MySessionListener implements HttpSessionListener
{
long start,end;
start=System.currentTimesMillis();
//write to log file
end=System.currentTimeMillis();
//write to log file
start));
start));
}
<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
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.
protocol tcp/ip
are H2p2.
H Http request method (GEG/POST/)
HHttp request headers (user-agent, referrer, accept,)
Prequest parameters( User =raja&pwd=rani)
----query string
Req Parameters
data.
(from data)
request parameters.
header values.
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);
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
Http response: When servlet prog gives output to browser window, it goes as http
When browser gives request the web server takes the request and
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 .
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.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.
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)
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.
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
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.
19-Jun-15
|--src
|--com.nt
|--DBsrv.java
|--webcontent
|--input.html
|--WEB-INF
|--web.xml
It is called global
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
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
ServletConfig cg;
this.cg=cg;
//use cg
}
//use cg
}
Approach-2)
public class TestSrv extends HttpServlet
{
public void init()
{
ServletConfig cg=getServletConfig();
//use cg
}
ServletConfig cg=getServletConfig();
//use cg
}
}
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();
Approach-3)
From Servlet 3.0 (recommended)
In servlet Prog
ServletContext sc=req.getServletContext();
Date:
20-Jun-15
{
public void init(FilterConfig fg)
{
//initializaion logic
}
{
...
....
...
....//Uninitialazation logic
...
3 types of ServletFilter:a.
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
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
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
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
Inside <servlet>------</servlet>
<servlet>
<init-param>
<param-name> </param-name>
<param-value> </param-value>
</init-param>
</servlet>
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
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>
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());
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.
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.
password: weblogic
Connection con=ds.getConnection();
Gets the con obj from jdbc conn pool.
Date
26-Jun-15
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
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.
this.sname=sname;
}
return sname:
}
}
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
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.
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
/:- is optional
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(-)
objects.
object.
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.
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
//general Setteings
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
//Generate non-
//colse stream
}
pw.close();
doGet(req,res);
}
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
Understanding rd.include(-,-):-
\
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>");
}
doGet(req,res)
...
...
//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()
doGet(req,res);
03-Jul-15
Date:
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
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
|---src
|---com.nt
|---webroot
|---SSrv.java
|---WEB-INF
|---web.xml
rd.include(-,-)
of RequestDispatching.
of RequestDispatching.
Discards the html output of source Does not discards the output of
prog.
source program.
Useful in errorServlet
communication.
destination 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.
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
In the above technique the end user has to click on hyper link 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
res.sendRedirection(-)
Perform SendRedirection
directly
browser window.
attribute.
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
and accessible in srv2 and srv3 but not in srv4 because sr1, srv2, srv3
program are using same request, response object.
req.setAttribute(name,raja);
req.setAttribut(age,30); Here age is attribute name and 30 is attribute
value.
To modify request attribute value
basis.
scope.
These attribute are visible in all the web resource prog of web
> 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
ServletContext Attribute/Application attribute:: These attributes allocate memory in servlet context object which is
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).
12-Jul-15
ServletWrapper:public interface Test
{
Adapter class:-
.
}
Public class MyResposne implements ServletResponse
{
//many method.
;;;;
}
To overcome the above problem we can use servlet Wrapper classes
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
09-Sep-15
26-Jul-15
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.
UploadBean
Allows to set Destination folder for file uploading and also file for
completing file uploading.
UploadingFile
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.