| 2016-
Java Servlets | 7/5
Batch
Non-persistent cookie
Itis valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
Itis valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state
2. Cookies are maintained at client side,
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie) constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 15/41Java Servlets
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds
expiry)
public String getName() Returns the name of the cookie, The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void sctName(String _ changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
‘Other methods required for us
1g Cookies
For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface
is used to add cookie in response object.
2. public Cookie] getCookies():method of HttpServletRequest interface is used
to return all the cookies from the browser.
How to create Cookie?
Let's see the simple code to create cookie,
1 Cookie ck-new Cookie("user","sonoo jaiswal");//ereating cookie object
2 response.addCookie(ck)y/adding cookie in the response
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 16/41Java Servlets
How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Cookie ck=new Cookie("user","");//deleting value of cookie
cksetMaxAge(0)i//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
How to get Cookies?
Let's see the simple code to get all the cookies.
Cookie ck{=request.getCookies(); for(int
i-O;i
"+ ck(i].getName()" "+ck{i].getValue());
printing name and value of cookie
‘Simple example of Servlet Cookies
In this example, we are storing the name of the user in the cookie object and accessing it
in another servlet. As we know well that session corresponds to the particular user. So if
you access it from too many browsers with different values, you will get the different
value,
Servlet2
Wekome, User
Hello, User
“hie ie is under
caxstrvtion
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 17/41201
Java Servlets | 7/5
Batch
index.html
1
FirstServlet,java
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet_http.*;
4
5.
6 public class FirstServlet extends HttpServlet {
7.
8 public void doPost(HttpServletRequest request, HttpServletResponse response)
{
9 trys
10.
u. response.setContentType("text/htm!");
12, PrintWriter out = response. getWriter();
13,
14. String n-request.getParameter("userName");
15. out print("Weleome "+n);
16.
17, Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck)y/adding cookie in the response
19.
20. Hereating submit button
ai. out.print("""
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 18/41201
Java Servlets | 7/5
Batch
24,
28, out.close);
26.
21. }jeateh(Exception e) {System.out printin();}
28. }
29. }
SecondServiet,java
1 import java.io.*;
2 import javax.servlet.*;
3. import javax.servlet.http.*;
4
5. public class SecondServlet extends HttpServlet {
6
7. public void doPost(HittpServietRequest request, HttpServletResponse response) {
8 try{
9
10. response.setContentType("text/html”);
u PrintWriter out = response.getWriter();
12.
13 Cookie ck{}=request.getCookies();
M4 out print("Hello "tek{0].getValue();
15.
16, out.close(;
17.
18, }Jeateh Exception e) {System.out.printhn(e);}
19, }
20.
ai.
22, }
web.xml
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 19/41een aAneawn
ul
12.
13,
14.
15,
16.
17.
18,
19.
20.
21.
22.
23,
Java Servlets
s|
FirstServlet
s1
/servlet |
s2
SecondServlet
s2
/servlet2
SUMMARY
After going through this unit you will understand the role of Servlet in big picture
of J2EE. AS soon as the Web began to be used for delivering services, service providers
recognized the need for dynamic content. Applets, one of the earliest attempts toward this
goal, focused on using the client platform to deliver dynamic user experiences. At the
same time, developers also investigated using the server platform for this purpose.
Initially, Common Gateway Interface (CGI) scripts were the main technology used to
generate dynamic content, Though widely used, CGI scripting technology has a number
of shortcomings, including platform nd lack of scalability. To address the
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 20/41Java Servlets
tations, Java Servlet technology was created as a portable way to provide dynamic,
user-oriented content.
Servlet request & response model. Servlet life cycle. Servlet scope objects. Servlet
request and response: Status, Header, Body and Error Handling. Servlet from the
standpoint of J2EE architecture, that is, what role Servlet plays in a multi-tier web-based
application. Servlet is basically a web technology in which HTTP request is being
received and handled and then proper HTTP response is being created and then returned
to the client
KEY TERMS
Java Servlets : Servlets are the Java platform technology of choice for
extending and enhancing web servers
+ ServletRequest: Defines an object to provide client request information to a
servlet.
‘* ServletResponse: Defines an object to assist a servlet in sending a response to
the client
* init() — Invoked once when the servlet is first instantiated
© service () - This method gets called every time there comes a new request.
‘* destroy) — Invoked before servlet instance is removed
* Http response header: It contains a status line, response headers, and a
blank line, followed by the document
* Cookie : Its a bit of information sent by a web server to a browser that can
later be read back from that browser
QUESTIONS
1 Mark Questions (Multiple choice based)
LA isa server side program.
aserviet —b. JSP ©. EJB d, Java
2. The HTTP Request Header is used by a browser to identify the client to the
java servlet whenever a protected web page is being processed.
a.Accept b, Accept_Charset c. Accept_Language d.Authorization
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 21/41Java Servlets
3. The HTTP Request Header identifies the browser that made the request.
a. IfModified-Since b. IfUnmodified-Since ¢, Referer d. User-Agent
4, ‘The HTTP Response Header is a parameter for the connection header.
a. close —_b. Content-Encoding ¢. Content-Language —_d._ Content-Length
5. Java servlet remains alive after the request is fulfilled. This is called
apersistence . reliability. Integrity d._ robustness
6. The ‘method is called automatically when the java servlet is created.
it) b. setContentTypeQ) ¢. doGet() d. doPost()
7. The HTTP Response Header indicates page encoding
a. close b, Content-Encoding ¢. Content-Language d. Content-Length
8. HTTP version uses the Keep-Alive message to keep a connection open.
alt bo 12. 13 a4
9. A cookie is composed of pieces.
a2 b3 od as
10, is IITTP information that is generated by the client rather than the user.
a. Explicit data _b. Implicit data. CGI . Browser
2 Mark Questions:
1. Define Java Servlet.
Differentiate CGI and Java Servlet.
List the advantage of Java Servlet.
Define any three HTTP1.1 Status Codes
Define Cookies.
What is Tracking Session?
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE
Write a simple program using Java Servlet to display "Hello" message
Page 22/41201
Java Servlets | 7/5
Batch
8 Mark Questions
1. Exp
the anatomy of Java Servlet in detail.
2. Describe in about Servlet request and response with suitable example.
3. Exp!
4. Write a java Servlet program to reading data from a client.
about Servlet Classes and Interfaces.
5. Write program using java Servlet to send data to a client.
Prepared by Dr.S.Manju Priya, Assoc.Prof, Dept of CS,CA & IT
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 23/41quat]> aq 01 worreuoyUT SuIpuas ay) you St porsaut
Orseaop| -Arouiour two4y panour st 1014295
Oonsap Okonsap (ootares Quy | _ eaefe yo aouerst we uy partes st poyats aq
ani9s gam aq oF apeur st 1ayras eae]
(aataras Orsoaop | _Oi2D0P (aotares Onur | eyp soy sanbas e renaueyas pales st poysau agg
pateaso st 191405
Ontar Orsogop | _Qremop | YadK yrusHW0>%08 Onur | eset om ays Aqpeoneuomne pores st pomaut agg
‘voneunsosat sapeay LL adé3ua405|
Oodewuowogies | _Orsogop (P| _O1eD0p | ods UoUOSTOs Oupuud 24p oj aNyeA 4p 198 0} pasn st poyou 4].
‘afedqam & uo sivadde|
ey1 IX} Se Yons erEp aoHdxa Buroino pus o4 roHULIULN|
Qupaud | Qrsogop (| _O12H0p | ade zu HUST Oupuud yu woroUnfizon ur pasn st poyrou ———— 94,
\dxa] aaoge|
pur Ayonduar | ay jo ou0N words ondary eiep _Sapnpour prep Suraoou
z s 1 ¢| z -squounise —— saumnbas pompaur (nsodop 21.
z s + g z sitouniize ——— sartnbax powpaur (1250p a4 |afiendu] ssonbal]
eT xdoooy| oq) apeus yeap 29838029 amp &q pasn 9g uD yeIR STAs sOIDEIRYD|
wesey"desoy | wonezHomnY asreygTMdovoy wdaoay aq) sayjpuepl —___sapeayy sanbay A L1H AU
aiendu| sonbai|
eT xdoo0y ‘yp apeu yey 298009 op &q poypuey aq weD eM Prep Jo]
xdssoy_ | wonezuomny sosreqgido9oy wdoooy | 9dd1 aWWTIN am SouTApI — — — Jopeop wonboy ELLE our
z s + A q sitiattodiuos ———— sureyaoa oro # wouy ssanbas |
Os Osonye| s|
sume yuaaueregi98) rorouereg193| atuen rorounese ga ‘uoneraunus ue suamyaa|
Oisogop Quoyoureregia8 pie uouniire ue artnbas ou saop pouyaut ou
Os Qsanye|
ane qsoroursegia8| soaureregi9a| suaumiie ou jajaurered ayy ureiwo9 jousaop rut
Onsogop Orpop [Ouiourerees | om way parrooar you 8 summyar pore 943,
sone]
Awrourereg3| poyaur
Queue gna Orsogop Orapop |Oxrouesea nas | op SurTeo Xq rops298 wall w oj peas st juDHTO w Aq JOS BIEL
Ls04|
sod aaoge} 40 149] 9]a208 ear
so. 2qN19 | _awpsoouoN | so sqo tg0d | _ Ato rap |e or moneuosuy ssed 01 pompour ap sosn quay9 y
anoge| 1p]A198
aweurajaies | ayyjosuoy | wered-y ssejiayaras | ouea-yayaas | evel aup ssaoae 0} pasn aureu aup sutejuoo au.
stuomjaqns
¢ g + g 2] Wer uau9po r9],08 & urEHOD plnoys wawIa}9 dde-qam au]sours sous asonbor aqp apear yea
waves | quads | sarajou | -poyipowuns | -paupowst | _sesmorg au soynuapr sap eayy wanboy LLM UL
sours; saurs| -osmoug aqp ur paceydsip Aqruszmo st eq aed gam arp
sargey | amaBysiesq | somyoy | -pornpoumn- | -pampowe | Jo Tan 2 sures sapeay asonboy aL LET ou
‘uep payoads w ueqn|
sours) sours sours] aapyo st evep aqn jt Aquo parsing aq pmnoys sisanbar s sasmorq|
-payipouup-s | awaBy-sasq | sarayjoy | -paumpouuacy | -paupow-ai 2) yey) souudis ——____sapeayasonbay (L1H 4
‘upp paiyjoads w asus patueyp|
sour sous sey evep 241 1 Aquo porngtHy aq pinoys sisonbar s sosmorq|
aouts-paypowsi| waByaiesq | sage | -poyrpowun-n | -peutpow-t| au yeIp sous rapeayy wonboy dL.LH 4
“RAN [eULTI0 axp Jo p04
180H 10H | 21009] _wBuofUa | _uonssuIOD | pur yoy amp surEIUOD ———— 1opeopA ISOMbO dLLH OH
powpaut Lg ay Huish paywustten are reyp sardq wt erep|
aupp-yu9009 wsoH | aP|009 | _mpRuapwoHED | _uonoamoy | ayp so azis om Sure) JOPROH ISOM A.L.LH 94,
‘aouaystsiad sv 01 paniajar sy
pty x{908 owes ayp Busn sayy a}dryfMUL DAdizTON ED 1osMOLg|
wonaamm09 won | _apf009 | _qpSuapmomog | _uonsouuo> | e zompou soxnmop! —_____s9peaqy sonbow L1H OL
afiendu| passoooid furaq st aBed|
eT do09y| om parnarord e soxouiay yopA198 wav amp oF TuDT|9 aM AFTUDPY
vonezuomny | uonezoyny asreygTdovoy wdaooy_| 01 sasioug e £q pasn si ____sapvag wanbay ALL UL
sional
aftonsue idoaoy) eT ido09y| -r9smoug amp £q pasn aze yyy soRensiu]
vonezuomny
spsreqgido00y
xdoooy
pauiayard ayp sargtoads —_—sapeayy sanboy .LH 4 |paydde st
puoq] Benue Suypoous sojonsey> kue a1ojaq afessous ay) ut soy Jo Joquinu
wuatauamoy | wary | -waruoy | Supoous-yuaqu0; aso auy soveorpur —____Japeay asuodsay ALL a4,
wSuoq] ofensu0y quoumoop aqp Jo afen ur]
sfensaeyymoywoy | -ywawo3 | _-auaiw05 | ampooug-wayo.y aso uy soyeaipul —_sopeayy osuodsoy A. 24
Surpooua| Susy] ofendu0y Suspooua|
awaywog | wae | waren | aupoous-ywoqu03 aso aed soyeoypuy apa asuiodsoy aLLH =u
suey] oBensuey apeay worrsauu0d oxp|
asoja | __-yuowog | -yuoqu0e | fuypoous-quayw0>) asoja | 40) zojourezed v s1 —— sopeayy asuodsoy Qu.H ou
On
anoge| aupaypues -resmong|
Qvoupoypuss | _ayp 40 au0N, Quourapuos | _Osmersios | __ 94p oy sopeay wone0] # syuusuen pomrsur ug
Ox]
aaoge| aupoypues pauingao sey 10.29
Qsouspuas | om yo ouon Qrosrapues ‘we yea yuDy]9 m1 AFOW o1 pas st poxpou 94.
On|
aaoge| aupoypuos sao{go asuodsoq 1o)\19§dnH 91p Jo pourou ap]
Osmyeisios | amp yo ouoy, Qrosrapuos | _Osmergios | Sima Aq sopeoy asuodsas q.L.1H 241 01 HEN RD 19]AI08 BAR Y
ssonbos yu9q9
z s | ¢| 2{_v on sondasrajaios eaele yous wt shea aur anny
uuado woroout09 o
1 vr el z 11] dooy 7 ofessou santy-dooy amp sosn uolsion LH7 g + ¢| q saqayd ———— yo pasodiutoa sy aryooo |
aryoo9| ‘addy uonezuoyine|
YVAN “1S sayry-AnOY wsagoU aq Soveoipt] ——— sapeay asuodsoy ALL UL,
areonuaginy] —ap{oo3| ‘aed ayp 209
a1yoog 19g “AANA, “19 sayy-snay sayey | a1yooo ap senept Japeay asuodsay L1H au
‘aqpyseAvUN s1 aa1A5
areonuaginy] — ap{003| aq Jf ‘sataros Bupsonbas azogaq ies 01 spuooas Jo soquuny
royy-knoy “MAAN, “95 sayy Anew ysoueu ayy soyearpul peop astodsoy LL 4
areonuaginy] —aryoog| ‘avepdn aifed v soy Buryse a1oyaq tem 01 spuosas Jo sequin
ysoujou rn “15 sayy-énoy | _ ys ayy somarput —____Jopeoy asuodsoy ALL SUL “E81
pourpoyy| suauinsop ayy Jo wone20]
uOnRD0T wonra07 “Ase sondxg | adky-uoq09 aq soyearput spe asuodso a.L.LH 94
pourpoyy| ‘poueyp sem quounaop 249 aun
poyrpowea wonR907 “aseT sondxg | adky-ruam03 | ase] axp soveoxpur —___rapeaqq aswodsoy A,LH 941
pourpoyy| sn-aqep Jo Mo St UOKEMDOP yA spuosast | M
sandxg woneo0T “81 sandy | adKy-ruawog | au ay sejiseds ———sapeay asuodsoy LLM UL
PoUrDoHy uoumoop astodsas arp jo adh
ad y-wow0.9 wonea0y “se sondxg | odK-suawo3 | aWIA au) soveanpur Jopeay asuodsoy {L1H 41 |99{qo anyo09 aup Jo poyrsur aq Sursn|
Conyeares | _Oapjoogrg| Oanye tos Qarjeogppe | _Ganjoogres | _Aq sarjoos Bunspxa ue Jo anjea oxp AsIpoU Wea 1OpAI0s eal |
Qarjoosie8 | _ arjoonies| Oomeares Qarjeogppe | _Oanfoog¥8 siaa{qo apjoo9 Jo eure we swinyau pomyaut au
‘squowinitie — 39alqo ar4o0o oxy
g 1 ¢ 2{__ so uonannsuos oy Hurssed £q a1joo9 k somuas J9]AIOS Bakl Y
soyouresed| lav
anypa aryo09 ary03] _27¥009 anges aryoos | _auret apyoo ‘sarqooo aq ya paretoosse s] 41
sopoureed| av| Juay]9 aqL 18 pazors SaPIO09 saxo SuoMe|
atuteu ar4009 apjo09] _apyo09 anges aryoos | ature aryoos | __wto¥y apjoo zejnansed v Aptapt o1 posn st auJava Beans | 201
Batch
2018
UNIT-IV
Enterprise Java Beans: Deployment Descriptors — Session Java Bean -Entity Java Bean
Message Driven Bean.
TEXT BOOKS
1. Jim Keogh. (2010). The Complete Reference J2EE, Tata McGraw Hill: New Delhi.
Ist Edition,
REFERENCES
1. David R. Heffelfinger (2011), Java EE 6 Development with NetBeans 7,Packt
Publishers, 1 Edition.
2. Joel Murach, Michael Urban, (2014), Murach's Java Servlets and JSP, (Murach:
Training & Reference). 3rd Edition
3. Joseph, J. Bambara et al. (2007). J2EE Unleashed , New Delhi:Tech Media, 1*
Edition,
4, Paul, J. Perrone., Venkata, S. R. Chaganti., Venkata 8. R. Krishna., & Tom Schwenk,
(2003), /2EE Developer's Handbook Sams Publications, New Delhi, 1* Edition
5. Rod Johnson. (2004), J2EE Development without EJB , New Delhi: Wiley Dream
Tech, 1* Edition
6. Rod Johnson., & Rod Johnson, P.H. (2004). Expert One-On-One J2ee Design and
Development. New Delhi: John Wiley & Sons, 2" Edition,
7. John Brock, Arun Gupta, Geertjan Wielenga (2014), Java EE and HTMLS Enterprise
Application Development Oracle Press.
WEB SITES
1. www.java.sun.com/javaee/
‘www. java.sun.com/j2ee/|.4/does/tutorial/doci
www, eebrain.com/
www javaworld.com/
we
www corej2eepatterns.com!
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 1/22Java Beans | 2016-2018
Batch
ENTERPRISE JAVABEAN
OVERVIEW OF EJB
Enterprise beans are Java EE. components that implement Enterprise JavaBeans (EJB)
technology. Enterprise beans run in the EJB container, a runtime environment within the
Application Server. Although transparent to the application developer, the EJB container
provides system-level services such as transactions and security to its enterprise beans.
These services enable you to quickly build and deploy enterprise beans, which form the
core of transactional Java EE applications. Written in the Java programming language, an
enterprise bean is a server-side component that encapsulates the business logic of an
application. The business logic is the code that fulfills the purpose of the application. In
an inventory control application, for example, the enterprise beans might implement the
business logic in methods called checktnventoryLevel and ozderProduct. By
invoking these methods, clients can access the inventory services provided by the
application.
BENEFITS OF ENTERPRISE BEANS
For several reasons, enterprise beans simplify the development of large, distributed
applications. First, because the EJB container provides system-level services to enterprise
beans, the bean developer can concentrate on solving business problems. The EJB
container, rather than the bean developer, is responsible for system-level services such as
transaction management and security authorization,
Second, because the beans rather than the clients contain the application’s business logic,
the client developer can focus on the presentation of the client. The client developer does
not have to code the routines that implement business rules or access databases, As a
result, the clients are thinner, a benefit that is particularly important for clients that run on
small devices
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 2/22Java Beans | 2016-2018
Batch
Third, because enterprise beans are portable components, the application assembler can
build new applications from existing beans. These applications can run on any compliant
Java EE server provided that they use the standard APIS.
4.1 EJB DEPLOYMENT DESCRIPTOR,
Deployment descriptor is the file which tells the EJB server that which classes make up
the bean implementation, the home interface and the remote interface. it also indicates
the behavior of one EJB with other. The deployment descriptor is generally called as
ejb-jar.xml and is in the directory META-INF of the client application. In the example
given below our application consists of single EJB node
Accessing Database Application
Secure-app-client
secure
org.glassfish.docs.secure.secureHome
org glassfish.docs secure.secure
org.glassfish.docs.secure.secureBean
Stateless
‘
secure:-This is the node that assigns the name to the EJB.
Accessing Database Application:-This node gives the
brief description about the Ejb module created,
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 3/22Java Beans | 2016-2018
Batch
Stateless:-This node assigns the Session bean as
stateless or stateful, Here stateless means to say accessing Remote interface.
DEPLOYING EJB TECHNOLOGY
The container handles persistence, transactions, concurrency, and access control
automatically for the enterprise beans. The EJB specification describes a declarative
mechanism for how these things will be handled, through the use of an XML
deployment descriptor. When a bean is deployed into a container, the container reads
the deployment descriptor to find out how transaction, persistence (entity beans), and
access control should be handled. The person deploying the bean will use this
information and specify additional information to hook the bean up to these facilities at
run time. A deployment descriptor has a predefined format that all EJB-compliant
beans must use and all EJB-compliant servers must know how to read. This format is
specified in an XML Document Type Definition, or DTD. The deployment descriptor
describes the type of bean (session or entity) and the classes used for the remote, home,
and bean class. It also specifies the transactional attributes of every method in the bean,
which security roles can access each method (access control), and whether persistence
in the entity beans is handled automatically or is performed by the bean. Below is an
example of a XML deployment descriptor used to describe the Customer bean:
This bean represents a customer
CustomerBean
Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 4/22