Sunteți pe pagina 1din 4

07.

Introduction to Java Server Pages (JSP)

AIM: Write a program manipulates bank information using JSP sever side programming OBJECTIVE : To expose the concepts of Java Server Pages

1. JavaServer Pages
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically generated content rom servlets! "ou sim#ly write the regular HTML in the normal manner, using amiliar $eb%#age%building tools! "ou then enclose the code or the dynamic #arts in s#ecial tags, most o which start with <% and end with %>!
Thanks for ordering <I><%= request.getParameter("title") %></I>

Se#arating the static HTML rom the dynamic content #rovides a number o bene its over servlets alone, and the a##roach used in JavaServer Pages o ers several advantages over com#eting technologies such as &SP, PHP, or 'old(usion! Section )!* (The &dvantages o JSP) gives some details on these advantages, but they basically boil down to two acts+ that JSP is widely su##orted and thus doesn,t loc- you into a #articular o#erating system or $eb server and that JSP gives you ull access to servlet and Java technology or the dynamic #art, rather than re.uiring you to use an un amiliar and wea-er s#ecial%#ur#ose language! The #rocess o ma-ing JavaServer Pages accessible on the $eb is much sim#ler than that or servlets! &ssuming you have a $eb server that su##orts JSP, you give your ile a .jsp extension and sim#ly install it in any #lace you could #ut a normal $eb #age+ no com#iling, no #ac-ages, and no user CLASSPATH settings! However, although your #ersonal environment doesn,t need any s#ecial settings, the server still has to be set u# with access to the servlet and JSP class iles and the Java com#iler! (or details, see your server,s documentation or Section )!/ (0nstallation and Setu#)! &lthough what you write o ten loo-s more li-e a regular HTML ile than a servlet, behind the scenes, the JSP #age is automatically converted to a normal servlet, with the static HTML sim#ly being #rinted to the out#ut stream associated with the servlet,s service method! This translation is normally done the irst time the #age is re.uested! To ensure that the irst real user doesn,t get a momentary delay when the JSP #age is translated into a servlet and com#iled, develo#ers can sim#ly re.uest the #age themselves a ter irst installing it! Many $eb servers also let you de ine aliases so that a 12L that a##ears to re erence an HTML ile really #oints to a servlet or JSP #age! &side rom the regular HTML, there are three main ty#es o JSP constructs that you embed in a #age+ scripting elements, directives, and actions! Scri#ting elements let you s#eci y Java code that will become #art o the resultant servlet, directives let you control the overall structure o the servlet, and actions let you s#eci y existing com#onents that should be used and otherwise control the behavior o the JSP engine! To sim#li y the scri#ting elements, you have access to a number o #rede ined variables, such as request in the code sni##et 3ust shown! Scri#ting elements are covered in this cha#ter, and directives and actions are ex#lained in the ollowing cha#ters!

Scripting Elements
JSP scri#ting elements let you insert code into the servlet that will be generated rom the JSP #age! There are three orms+ )! Expressions o the orm <%= expression %>, which are evaluated and inserted into the servlet,s out#ut 4! Scriptlets o the orm <% code %>, which are inserted into the servlet,s _jspService method (called by service) 5! Declarations o the orm <%! code %>, which are inserted into the body o the servlet class, outside o any existing methods 6ach o these scri#ting elements is described in more detail in the ollowing sections!

Template Text
0n many cases, a large #ercentage o your JSP #age 3ust consists o static HTML, -nown as template text! 0n almost all res#ects, this HTML loo-s 3ust li-e normal HTML, ollows all the same syntax rules, and is sim#ly 7#assed through8 to the client by the servlet created to handle the #age! 9ot only does the HTML loo- normal, it can be created by whatever tools you already are using or building $eb #ages! There are two minor exce#tions to the 7tem#late text is #assed straight through8 rule! (irst, i you want to have <% in the out#ut, you need to #ut <\% in the tem#late text! Second, i you want a comment to a##ear in the JSP #age but not in the resultant document, use <%-- JSP Comment --%> HTML comments o the orm <!-- HTML Comment --> are #assed through to the resultant HTML normally!

JSP Expressions
& JSP ex#ression is used to insert values directly into the out#ut! 0t has the ollowing orm+
<%= Java Expression %>

The ex#ression is evaluated, converted to a string, and inserted in the #age! This evaluation is #er ormed at run time (when the #age is re.uested) and thus has ull access to in ormation about the re.uest! (or exam#le, the ollowing shows the date:time that the #age was re.uested+
Current time <%= ne! "a#a.util.$ate() %>

JSP Scriptlets
0 you want to do something more com#lex than insert a sim#le ex#ression, JSP scri#tlets let you insert arbitrary code into the servlet,s _jspService method (which is called by service)! Scri#tlets have the ollowing orm+
<% Java Code %>

Scri#tlets have access to the same automatically de ined variables as ex#ressions ( request, response, session, out, etc)! So, or exam#le, i you want out#ut to a##ear in the resultant #age, you would use the out variable, as in the ollowing exam#le!
<% %tring quer&$ata = request.get'uer&%tring()( out.)rintln("*tta+hed ,-T data " . quer&$ata)( %>

0n this #articular instance, you could have accom#lished the same e ect more easily by using the ollowing JSP ex#ression+
*tta+hed ,-T data <%= request.get'uer&%tring() %>

0n general, however, scri#tlets can #er orm a number o tas-s that cannot be accom#lished with ex#ressions alone! These tas-s include setting res#onse headers and status codes, invo-ing side e ects such as writing to the server log or u#dating a database, or executing code that contains loo#s, conditionals, or other com#lex constructs! (or instance, the ollowing sni##et s#eci ies that the current #age is sent to the client as #lain text, not as HTML (which is the de ault)!
<% res)onse.setContentT&)e("te/t/)lain")( %>

0t is im#ortant to note that you can set res#onse headers or status codes at various #laces within a JSP #age, even though this ca#ability a##ears to violate the rule that this ty#e o res#onse data needs to be s#eci ied be ore any document content is sent to the client! Setting headers and status codes is #ermitted because servlets that result rom JSP #ages use a s#ecial ty#e o PrintWriter (o the more s#eci ic class JspWriter) that bu ers the document be ore sending it! This bu ering behavior can be changed, however; see Section ))!< or a discussion o the autoflush attribute o the page directive! &s an exam#le o executing code that is too com#lex or a JSP ex#ression the listing #resents a JSP #age that uses the bgColor re.uest #arameter to set the bac-ground color o the #age! Some results are shown in (igures

BGColor.jsp
<0$1CT2P- 3T45 P675IC "8//9:C//$T$ 3T45 ;.< Transitional//-="> <3T45> <3-*$> <TIT5->Color Testing</TIT5-> </3-*$> <% String bgColor = request.getParameter("bgColor"); boolean hasExplicitColor; i (bgColor != null) " hasExplicitColor = true; # else " hasExplicitColor = alse; bgColor = "$%&'E";

# %( <71$2 7,C151>="<%= bgColor %("> <3? *5I,=="C-=T->">Color Testing</3?> <% i (hasExplicitColor) " out.println(")ou supplie* an explicit bac+groun* color o " , bgColor , "."); # else " out.println("-sing *e ault bac+groun* color o $%&'E. " , "Suppl. the bgColor request attribute to tr. " , "a stan*ar* color/ an 001122 3alue/ or to see " , "i .our bro4ser supports 566 color names."); # %( </71$2> </3T45>

Default result of BGColor.jsp.

Result of BGColor.jsp when accessed with a bgColor parameter having the RGB value C0C0C0.

Using Scriptlets to Make Parts of the JSP File Conditional


&nother use o scri#tlets is to conditionally include standard HTML and JSP constructs! The -ey to this a##roach is the act that code inside a scri#tlet gets inserted into the resultant servlet,s _jspService method (called by service) exactly as written, and any static HTML (tem#late text) be ore or a ter a scri#tlet gets converted to print statements! This means that scri#tlets need not contain com#lete Java statements, and bloc-s le t o#en can a ect the static HTML or JSP outside o the scri#tlets! (or exam#le, consider the ollowing JSP ragment containing mixed tem#late text and scri#tlets!
<% if (4ath.random() < <.@) A %> 3a#e a <7>ni+e</7> da&0 <% B else A %> 3a#e a <7>lous&</7> da&0 <% B %>

$hen converted to a servlet by the JSP engine, this ragment will result in something similar to the ollowing!
if (4ath.random() < <.@) A out.)rintln("3a#e a <7>ni+e</7> da&0")( B else A out.)rintln("3a#e a <7>lous&</7> da&0")( B

The page directive lets you control the structure o the servlet by im#orting classes, customi=ing the servlet su#erclass, setting the content ty#e, and the li-e! & page directive can be #laced anywhere within the document; its use is the to#ic o this cha#ter! The second directive, include, lets you insert a ile into the servlet class at the time the JSP ile is translated into a servlet! &n include directive should be #laced in the document at the #oint at which you want the ile to be inserted; The page directive lets you de ine one or more o the ollowing case%sensitive attributes+ import, contentType, isThreadSafe, session, buffer, autoflush, extends, info, errorPage, isErrorPage, and language! These attributes are ex#lained in the ollowing sections!

The import Attribute


The import attribute o the page directive lets you s#eci y the #ac-ages that should be im#orted by the servlet into which the JSP #age gets translated! 0 you don,t ex#licitly s#eci y any classes to im#ort, the servlet im#orts java.lang.*, javax.servlet.*, javax.servlet.jsp.*, javax.servlet. http.*, and #ossibly some number o server%s#eci ic entries! 9ever write JSP code that relies on any server%s#eci ic classes being im#orted automatically! 1se o the import attribute ta-es one o the ollowing two orms+
<%C )age im)ort=")a+kage.+lass" %> <%C )age im)ort=")a+kage.+lassDE...E)a+kage.+lass=" %>

(or exam#le, the ollowing directive signi ies that all classes in the java.util #ac-age should be available to use without ex#licit #ac-age identi iers!
<%C )age im)ort=""a#a.util.F" %>

The import attribute is the only page attribute that is allowed to a##ear multi#le times within the same document! &lthough page directives can a##ear anywhere within the document, it is traditional to #lace import statements either near the to# o the document or 3ust be ore the irst #lace that the re erenced #ac-age is used!

The contentT pe Attribute


The contentType attribute sets the Content-Type res#onse header, indicating the M0M6 ty#e o the document being sent to the client! (or more in ormation on M0M6 ty#es! 1se o the contentType attribute ta-es one o the ollowing two orms+
<%C )age +ontentT&)e="4I4-8T&)e" %> <%C )age +ontentT&)e="4I4-8T&)e( +harset=Chara+ter8%et" %>

(or exam#le, the directive


<%C )age +ontentT&)e="te/t/)lain" %>

has the same e ect as the scri#tlet


<% res)onse.setContentT&)e("te/t/)lain")( %>

1nli-e regular servlets, where the de ault M0M6 ty#e is text/plain, the de ault or JSP #ages is text/html (with a de ault character set o ISO-8859-1)!

S-ar putea să vă placă și