Home

Herong`s Notes on JSP

image

Contents

1. gt cookies gt cookies As you can see from the diagram cookies are actually saved to the hard disk of Web browser user s machines Many users are concerned about this But I think it is pretty safe to allow your browser to save cookies If you are really concerned you can change your browser s settings to reject cookies But this may cause many Web based applications fail to run on your browser Sending and Receiving Cookies Sending cookies to the browser can be done by the addCookie method on the response object while receiving cookies from the browser can be done by the getCookies method on the request object Here is program to demonstrate how to use those methods lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt CookieTest jsp Copyright c 2002 by Dr Herong Yang All rights reserved gt lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt lt jsp directive page import javax servlet http Cookie gt 1 of 6 http www geocities com herong_yang jsp cookie html lt jsp scriptlet gt lt CDATA out printIn lt b gt Cookies received by the server lt b gt lt br gt Cookie cookies request getCookies intn 0 if cookies null n cookies length for int i 0 i lt cookies length i out println cookies i getName cookies i getValue lt br gt out printIn lt b gt
2. lt jsp directive page contentType text html gt lt html gt lt body gt lt hy echo message Fish I love you and respect you very much gt lt body gt lt html gt lt jsp root gt You can guess what you will be getting when you access this page Tag Attribute Value Type Conversion In my previous example the attribute value is passed to the tag object property as a string data type Can we pass attribute values to tag object as other data types or objects The answer is yes JSP tag extension facility will try to convert attribute values to the data types of the tag object properties I couldn t find any official specifications on the match rules The following is my guesses e Match the attribute name to the setter method of a property with the same name in the tag object If the data type of the input parameter of the setter method is a primitive data type like long give the attribute value as literal data to the input parameter If the data type of the input parameter of the setter method is the wrapper class of a primitive data type like Long instantiate an object of that class with the attribute value as a String input to the constructor and give the new object to the input parameter If the data type of the input parameter of the setter method is the String class give the attribute value as string literal to the input parameter If the data type of the input parameter of the setter method is any other class u
3. message m public int doStartTagQ try if message null char a message toCharArray int n a length for int i 0 i lt n 2 i char t a i afi a n 1 i a n i 1 t pageContext getOut print a pageContext getOut printIn lt br gt catch IOException e System err printIn e toString return SKIP_BODY Here is the TLD file lt xml version 1 0 gt lt DOCTYPE taglib PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by Dr Herong Yang gt lt taglib gt lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt echo lt name gt lt tag class gt herong EchoTag lt tag class gt 2 of 12 http www geocities com herong_yang jsp tag_attribute html lt body content gt empty lt body content gt lt attribute gt lt name gt message lt name gt lt required gt false lt required gt lt attribute gt lt tag gt lt taglib gt Here is a test page EchoTagTest jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt lt EchoTagTest jsp Copyright c 2003 by Dr Herong Yang gt
4. Content Type content text html charset gb2312 gt writeGB lt body gt writeGB lt b gt uCBB5 uC3F7 lt b gt writeGB lt p gt uD5E2 uCAC7 uD2BB uB7DD uB7C7 uB3 A3 uBCE4 uB5A5 UBSC4 uCBB5 uC3F7 uCAE9 A 1 AD lt p gt writeGB lt body gt writeGB lt html gt gt lt jsp scriptlet gt lt jsp root gt When I opened HelpGB2312Java jsp with IE I saw Chinese characters correctly displayed on the screen So option 1 works But note that e Figuring out the byte sequences of non ASCII characters in a particular encoding is not that hard Simplified Chinese text files are usually written in byte sequences of GB2312 encoding Byte sequences can only be entered in Java statements in Hex number format response getOutputStream need to be called before any other output statements Once response getOutputStream is called you can not call response getWriter any more So the entire HTML document must be outputed in binary mode You can not add any static HTML text because that requires response getWriter A JSP directive page element is needed to set the Content Type header of the HTML reponse with the sample charset value as the HTML document Java Strings Unicode Codes Local Language Independent Let s try option 2 now Here is my sample JSP page lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version
5. Each gt lt p gt header lt p gt lt c forEach items header var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt headerValues lt p gt lt c forEach items headerValues var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt cookie lt p gt lt c forEach items cookie var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt initParam lt p gt lt c forEach items initParam var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt Class path list lt p gt lt c forTokens items applicationScope org apache catalina jsp_classpath delims var entry gt lt c out value entry gt lt br gt 4 of 7 http www geocities com herong_yang jsp jstl_core html lt c forTokens gt lt body gt lt html gt lt jsp root gt Output of JstlObjects jsp slightly reformatted Browsing all the JSTL implicit objects pageContext org apache jasper runtime PageContextImp 4ed821 pageScope javax servlet jsp jspApplication org apache catalina core ApplicationCon javax servlet jsp jspSession org apache catalina session StandardSession org apache taglibs standard ImplicitObjects org apache taglibs standard javax servlet jsp jspOut org apache jasper runtime JspWriterImp 7c3828 javax servlet jsp jspResponse org apache coyote tomc
6. The base interface required by a tag class to interact with the JSP tag extension facility IterationTag interface Extended from Tag interface to support looping logic within custom tags e BodyTag interface Extended from IterationTag interface to allow custom tags to evaluate their own body e TagSupport class Dummy implementation of IterationTag interface BodyTagSupport class Dummy implementation of BodyTag interface BodyTag Interface Since BodyTag interface requires deeper knowledge of JSP in order to evaluate the tag body properly we will discuss it later For now let s concentrate on InterationTag interface only Here is the list of methods required by InterationTag interface and their calling conditions e setPageContext PageContext pc A help method called before calling doStartTag to pass the PageContext object to the tag object setParent Tag t A help method called before calling doStartTag to pass the parent tag object to the current tag object in case the current tag is nested within another tag getParent A help method called by child tag classes to access grand parent tags doStartTag An interfacing point called at the beginning of the process of the tag e doAfterBody An interfacing point called after processing the body e doEndTag An interfacing point called when ready to leave the process of the tag e release An interfacing point called before ending the process of the ta
7. application getInitParameterNames while e hasMoreElements String n String e nextElement out printIn Init Parameter Name n lt br gt P gt lt p gt lt body gt lt html gt Output JSP Page Context Information Pre defined objects out org apache jasper runtime JspWriterImp1 this org apache jsp ContextInfo_jsp request org apache coyote tomcat4 CoyoteRequestFacade response org apache coyote tomcat4 CoyoteResponseFacade session org apache catalina session StandardSessionFacade application org apache catalina core ApplicationContextFacade config org apache catalina core StandardWrapperFacade pageContext org apache jasper runtime PageContextImpl Information about session pageContext getSession Class Name org apache catalina session StandardSessionFacade Session ID 35466D59BF54A55 1BFBABA22B61A66EB Create Time Sun Dec 22 13 40 55 EST 2002 Last Access Time Sun Dec 22 13 40 55 EST 2002 Is Session New true Information about sessionContext session getSessionContext Class name org apache catalina session StandardSessionContext Information about application pageContext getServletContext Class Name org apache catalina core ApplicationContextFacade Major Version 2 Minor Version 3 Server Info Apache Tomcat 4 1 18 Serlet Context Name Welcome to Tomcat 3 of 6 http www geocities com herong_yang jsp context html A new session will be established if this JS
8. gt lt jsp directive page contentType text html gt lt html gt lt body gt lt jsp directive page import java util gt lt jsp directive page import java text gt 4 of 9 http www geocities com herong_yang jsp element html lt jsp declaration gt private Date now private JspWriter out private void printTime String tz throws Throwable DateFormat df DateFormat getInstance df setTimeZone TimeZone getTimeZone tz out println tz df format now amp lt br gt lt jsp declaration gt lt p gt lt b gt Current time in different time zones lt b gt lt br gt lt jsp scriptlet gt this out out now new Date printTime America New_ York printTime America Los_Angeles printTime Asia Shanghai printTime Europe Paris printTime Europe Moscow lt jsp scriptlet gt lt p gt lt p gt lt jsp directive include file JvmStamp jsp gt lt p gt lt p gt lt jsp include page TimeStamp jsp gt lt p gt lt body gt lt html gt lt jsp root gt Here is the JSP file used by the include directive element JvmStamp jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt JvmStamp jsp Copyright c 2002 by Dr Herong Yang gt lt b gt Current JVM lt b gt lt br gt lt jsp scriptlet gt String s s java vm name out printIn s System getProperty s amp lt br gt s java vm versio
9. null javax servlet jsp PageContext pageContext null HttpSession session null ServletContext application null 2 of 5 http www geocities com herong_yang jsp jsp html ServletConfig config null JspWriter out null Object page this JspWriter _jspx_out null try _jspxFactory JspFactory getDefaultFactory response setContentT ype text html charset ISO 8859 1 pageContext _jspxFactory getPageContext this request response null true 8192 true application pageContext getServletContext config pageContext getServletConfig session pageContext getSession out pageContext getOut _jspxX_out out out write lt html gt out write lt body gt r n out printIn Hello world out write r n out write lt body gt out write lt html gt catch Throwable t out _jspx_out if out null amp amp out getBufferSize 0 out clearBuffer if pageContext null pageContext handlePageException t finally if _jspxFactory null _jspxFactory releasePageContext pageContext You will also see a Java class file hello_jsp class What happened here was that Tomcat the JSP Web server has translated hello jsp into hello_jsp java and compiled it to hello_jsp class The Java file hello_jsp java shows that e hello_jsp is a sub class of org apache jasper runtime HttpJspBase which is a sub class of javax servlet http HttpServle
10. out write nUnicode uHEX u8bf4 u660e out write lt br gt out write nUnicode UTF8 OxE8AFB4E6988E out write lt br gt out write lt p gt 11 of 13 http www geocities com herong_yang jsp non_ascii html I have tried to change charset to UTF 8 but it did not work JSP pages in XML syntax are always decoded as ISO 8859 1 May be there is a setting somewher to control this but I don t know Supporting Characters from Multiple Languages If you planning to write a page that has characters from multiple language encodings you have to use Unicode codes and UTF 8 HTML document encoding Here is an example with characters from two encodings GB2312 and Big5 lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt HelpUnicodeUTF8 jsp Copyright c 2004 by Dr Herong Yang gt lt jsp scriptlet gt lt CDATA response setContentType text html charset utf 8 out println lt meta http equiv Content Type content text html charset utf 8 gt out println lt body gt out printIn lt b gt u8bf4 u660e lt b gt lt br gt out printIn lt p gt u8fd9 u662fiu4e00 u4efd u97 5e uSe3 8 u95 4 u5355 u7684 u8bf4 u660e u4e66 u2026 lt p gt out printIn lt b gt u8aaa u660e lt b gt lt br gt out println lt p gt u90 1 9 u662fiu4e00 u4efd u97 Se u5e3 8 u9593 u55ae u7
11. Adobe Reader to display the hello message as a PDF document 4 Use IE to request http localhost 8080 GetFile jsp hello doc you should see IE calling MS Word to display the hello message as Word document Of course you have prepare such a Word document and put it on Tomcat server in order to do this test 5 Use IE to request http localhost 8080 GetFile jsp any txt you should see IE displaying an error message The reason is of course that the requested file doesn t exist Another way of sending non HTML data to the client is via attachment The following JSP will show you how to do this lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt Download jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page session false import java io gt lt jsp scriptlet gt String p request getQueryString boolean ok true ok p null if ok if p indexOf html gt 1 12 of 14 http www geocities com herong_yang jsp response_header html response setContentT ype text html else if p indexOf gif gt 1 response setContentT ype image gif else if p indexOf pdf gt 1 response setContentT ype application pdf else if p indexOf doc gt 1 response setContentT ype application msword else ok false if ok response setHeader Content disposition attachment filename p try int 1
12. Content Encoding Content Language Content Length Content Location Content MD5 Content Range Content Type Expires Last Modified Controlling Response Header Lines When a JSP page is requested the response header lines will be created by the JSP server But you can indirectly control some header lines in three 3 different ways 1 Using a directive element to set the entity header line Content_Type as shown in the 2 of 14 http www geocities com herong_yang jsp response_header html following example lt jsp directive page contentType text html gt 2 Using special methods on the response object as defined by the javax servlet ServletResponse interface to set the entity header lines Content_Type and Content_Length as shown in the following example response setContentT ype text html responee setContentLength 909 3 Using generic methods on the response object as defined by the javax servlet http HttpServletResponse interface to add or set any response header lines as shown in the following example response setHeader Content_Type text html response setIntHeader Content_Length 909 response setDateHeader Last Modified System currentTimeMillis response addHeader Content_Type charset ISO 8859 1 Viewing Response Header Lines When the client program receives the HTTP response it will look at the header lines first Based on the information contained in the header lines the client
13. If there is any additional body content in the loop tag after the break tag it will not be skipped Sharing Data with Other Tags In the previous example we looked at how tags can be nested inside each other and how child tags can access parent tags to modify their behavior In the next example we will look at how non nested tags brother tags can communicate to each other If a tag wants to share data with a brother tag it must store the data to a common place where both of them have access Obviously that common place is the pageContext object The JSP tag extension facility offers to every tag object the access to pageContext object by the setPageContext call in Tag interface If you use the TagSupport implementation class pageContext is already made available as an instance variable If you read the PageContext class API you will see that it allows you to store and retrieve objects as named attributes at any time So if one tag wants to share an object to another tag it can store that object to pageContext and the other tag can retrieve it from pageContext Another advantage of using pageContext to share objects is that JSTL tags are also using pageContext to store and share objects So if we use it correctly we can share objects in custom tags with JSTL tags 3 of 6 http www geocities com herong_yang jsp tag_parent html Let s look at a very simple example SetTimeTag java It does nothing but storing the current tim
14. JSP Standard Tag Libraries is a collection of JSP custom tags developed by Java Community Process www jcp org The reference implementation is developed by the Jakarta project jakarta apache org The latest version of JSTL is JSTL 1 1 which requires a JSP container that supports the Java Servlet 2 4 and JavaServer Pages 2 0 specifications Jakarta Tomcat 5 supports these specifications The previous version is JSTL 1 0 which requires a JSP container that supports the Java Servlet 2 3 and JavaServer Pages 1 2 specifications Jakarta Tomcat 4 supports these specifications Since I have Tomcat 4 1 18 installed on my machine I will talk about JSTL 1 0 only in this section The goal of JSTL as described in the specification is to help simplify JavaServer Pages page authors lives To achieve this goal JSTL has provided custom tags for many common JSP page authoring tasks that require scripting statements to manipulate server side dynamic data JSTL offers tags through 4 libraries core Basic scripting functions e xml XML processing e fmt Internationalization of formatting e sql Data base accessing Installing JSTL 1 0 Implementation Standard Taglib 1 0 4 Standard Taglib 1 0 4 is Jakara Taglibs s open source implementation of the JSP Standard Tag Library JSTL 1 0 I did the following to download the last release of Standard Taglib 1 0 4 e Go to http apache towardex com jakarta taglibs standard 1 0 and download j
15. identifier_a identifier_b then evaluate it as identifier_a get Identifier_b 8 If step 7 failed try to finish the operation as an object member variable So evaluate identifier_a identifier_b as identifier_a identifier_b I am note so sure about this Needs further research As you can see this process is very complex But it does make page author s life easier by putting a lot of intelligence behind this operation But it also brings a lot of confusion when you debug the code The JSTL specification about the and operators is quoted below as reference But I believe my description is much easier to understand 4 of 9 http www geocities com herong_yang jsp jstl_el html The expression language follows ECMAScript in unifying the treatment of the and operators expr a identifier b is equivalent to a identifier b that is the identifier identifier b is used to construct a literal whose value is the identifier and then the operartor is used with that value To evaluate expr a expr b Evaluate expr a into value a if value a is null return null Evaluate expr b into value b if value b is null return null if value a is a Map List or array if value a is a Map if value a contains Key value b then return null otherwise return value a get value b if value a is a List or array coerce value b to int using coercing rules if coercion couldn t be performed error
16. int new File p lengthQ response setContentLength 1 byte b new byte I FileInputStream f new FileInputStream p f read b ServletOutputStream o response getOutputStream o write b 0 1 o flushQ o close f closeQ catch Exception e ok false if ok response sendError HttpServletResponse SC_BAD_REQUEST lt jsp scriptlet gt lt jsp root gt In this page anther header line Content disposition is added to the response in which I am telling the client program that the entity data is an attachment with file name specified Now try to use IE to request http localhost 8080 Download jsp hello pdf you will see IE prompting you to save the attachment instead of calling Adobe Reader to display the data IE 6 0 Bug on Display PDF Data While I was trying to display PDF data I found that IE 6 0 is not responding correctly to 13 of 14 http www geocities com herong_yang jsp response_header html Content Type application pdf Here is a sample JSP GetPdf jsp to show the problem lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt GetPdf jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page session false import java io gt lt jsp scriptlet gt String p hello pdf response setContentT ype application pdf try int int new File p lengthQ response setContentLength 1 byte b new by
17. lt br gt out printIn Session ID session getIdQ lt br gt java util Date d new java util DateQ d setTime session getCreationTime out printIn Create Time d toString lt br gt d setTime session getLastAccessedTime out printIn Last Access Time d toString lt br gt out printIn Is Session New session isNew lt br gt P gt lt p gt lt p gt lt b gt Information about sessionContext lt b gt lt br gt lt i gt session getSessionContext lt i gt lt br gt lt javax servlet http HttpSessionContext c session getSessionContext out printIn Class name c getClass getName lt br gt P gt lt p gt lt p gt lt b gt Information about application lt b gt lt br gt lt i gt pageContext getServletContext lt i gt lt br gt lt out println Class Name application getClass getName lt br gt out printIn Major Version application getMajorVersion lt br gt out printIn Minor Version application getMinorVersion lt br gt out println Server Info application getServerInfo lt br gt out println Serlet Context Name application getServletContextName lt br gt java util Enumeration e application getServletNames while e hasMoreElements String n String e nextElement 2 of 6 http www geocities com herong_yang jsp context html out printIn Servlet Name n lt br gt e
18. out print JspRuntimeLibrary toString CacheBean pageContext findAttribute b getText out write lt br gt out write nInfo from my Bean out print b getInfo out write lt body gt out write lt html gt catch Throwable t out _jspx_out if out null amp amp out getBufferSize 0 out clearBuffer if pageContext null pageContext handlePageException t finally if _jspxFactory null _jspxFactory releasePageContext pageContext Note that e The page directive element with import attribute was translated into a true import Java statement e The useBean action element was translated into a block of code to load bean class instantiate an object of that bean class and put that object into the attribute collection in the page context object The name of the attribut is set to the same as the object name 4 of 12 http www geocities com herong_yang jsp usebean html e The setProperty action element was translated into a call to introspecthelper method e The getProperty action element was translated into a call to a get method e The expression element was translated into a call to out printQ Compilation Errors with Tomcat 4 1 18 and JDK 1 4 1 If you are using JDK 1 4 1 and trying to run the above example you will get the following compilation error org apache jasper JasperException Unable to compile class for JSP An error occurred at
19. queryString indexOf key if gt 1 i i key lengthQ int j queryString indexOf amp i if G gt 1 value queryString substring i j else value queryString substring i if value startsWith value value replaceFirst return value gt lt jsp declaration gt lt jsp scriptlet gt lt CDATA out print lt html gt lt body gt String lastUser String application getAttribute name String queryString request getQueryString 4 of 10 http www geocities com herong_yang jsp session html out print lt b gt Thank you for registering with us lt b gt lt br gt out print Login Name String session getAttribute name lt br gt out print Password String session getAttribute pass lt br gt out print Favor Color getItem queryString color lt br gt out print Your session ID is session getIdQ lt br gt out print Last user on the server lastUser lt br gt out print lt body gt lt html gt gt lt jsp scriptlet gt lt jsp root gt Request RegForm jsp with a browser you will get a page similar to this Registration Form Login Name Password Favor Color Your session ID is 2B20E475CA7BOFFC4C2E752ABF24C772 Last user on the server Nobody Then fill in the page with Login Name Herong Password Secret Favor Color Red Click the Submit button you will get the output of RegDone jsp pag
20. 1 2 gt lt HelpGB2312Unicode jsp 6 of 13 http www geocities com herong_yang jsp non_ascii html Copyright c 2002 by Dr Herong Yang gt lt jsp scriptlet gt lt CDATA response setContentType text html charset gb23 12 out printIn lt html gt out println lt meta http equiv Content Type content text html charset gb2312 gt out println lt body gt out printIn lt b gt u8bf4 u660e lt b gt lt br gt out println lt p gt u8fd9 u662fiu4e00 u4efd u97 5e uSe3 8 u95 4 u5355 u7684 u8bf4 u660e u4e66 u2026 lt p gt out println lt body gt out println lt html gt gt lt jsp scriptlet gt lt jsp root gt nn When I opened HelpGB2312Unicode jsp with IE I saw Chinese characters correctly displayed on the screen Remember I have Unicode Chinese fonts installed on my system So option 2 works But note that e Option 2 looks much simpler than option 1 No need to output HTML documents in binary mode e response setContentType must be called before any output statements e out is ready to use with the specified encoding schema embedded e The Chinese characters must be enterred as Unicode codes not GB2312 codes If you Chinese text is in GB2312 encoding format you need to convert the text to Unicode codes in u format One good tool for this is native2ascii from JDK Here is a sample command to convert HelpGB2312 html jdk bin native2ascii encoding gb23
21. 10 and 12 show you two correct ways of accessing object properties Examples 11 is understandable because an expression is expected in side and method without quotes is an identifier and it matches no existing objects variable names Examples 13 and 14 have syntax errors because the operator only takes identifiers names as operands Exampels 15 and 16 are different ways of writting nested operations Exampels 24 and 25 have syntax errors because 0 is not allowed an identifier Exampels 30 and 31 tell us that variables declared by scriptlet are not available to JSTL eoeee 7 of 9 http www geocities com herong_yang jsp jstl_el html e Exampel 32 is working because Java offers Object getClass getName e Exampel 33 is not working because name evaluates to null e Exampels 34 and 35 show you that the out is not directly accessible but it is an accessible property of pageContext e Exampels 36 and 37 show you that new elements can be added to implicit map object sessionScope Exercise Write an example JSP page to show how to create a JavaBean object and how to access the properties of this object with JSTL expressions pageContext Attributes and JSTL Top Level Identifiers Based the rules and the examples in the previous sections we can easily conclude that e JSTL top level identifiers variables are pageContext attributes e pageContext attributes are JSTL top level identifiers variables H
22. AttValueTag _jspx_th_hy_attValue_0 herong AttValueTag _jspx_tagPool_hy_attValue_stringObject_long Value_longObject _jspx_th_hy_attValue_0 setPageContext pageContext _jspx_th_hy_attValue_0 setParent null _jspx_th_hy_attValue_0 setLongObject new Long 11 _jspx_th_hy_attValue_0 setLongValue 21 _jspx_th_hy_attValue_0 setDoubleObject new Double 1 1 _jspx_th_hy_attValue_0 setDoubleValue 2 2 _jspx_th_hy_attValue_0 setBooleanObject new Boolean true _jspx_th_hy_attValue_0 setBooleanValue false _jspx_th_hy_attValue_0 setStringObject Hello world int _jspx_eval_hy_attValue_0 _jspx_th_hy_attValue_0 doStartTagQ if _jspx_th_hy_attValue_0 doEndTag javax servlet jsp tagext Tag SKIP_PAGE return true _jspx_tagPool_hy_attValue_stringObject_long Value_longObject return false I only copied the method that interacts with the tag class out of the Servlet class here Note that e The setter methods for the primitive data types are called with attribute values directly except that 1 is added to the end of the value like 11 e The setter methods for the wrapper classes of the primitive data types are called with new objects instantiated with the attribute values e How can Tomcat server figure out the class type of the setter method parameter Could someone help me here 7 of 12 http www geocities com herong_yang jsp tag_attribute html Tag Attribute Value Expression In the previous sections I only t
23. Cookies added by the server lt b gt lt br gt Cookie c new Cookie Cookie_ n value out printIn c getName c getValue lt br gt response addCookie c gt lt jsp scriptlet gt lt p gt lt body gt lt html gt lt jsp root gt So I opened this page with IE I got Cookies received by the server Cookies added by the server Cookie_0 value Then I clicked the refresh button on the IE window I got Cookies received by the server Cookie_0 value JSESSIONID 7E33A5 1C5F05A11647467E1735C5084E Cookies added by the server Cookie_2 value What happened here was that when I opened the page the first time the server received no cookie from the browser s request But my program added one cookie named as Cookie_0 to the response and the JSP server also added a cookie named as JSESSIONID When I clicked the refresh button the browser sent the two cookies back to the server in the request Then my program added another cookie named as Cookie_2 in the response If I keep clicking the refresh button more and more cookies would be added to the request and response But there is a limit The browser will only take up to 20 cookies from one Web server 2 of 6 http www geocities com herong_yang jsp cookie html Persistent Cookies There are two kinds of cookies persistent cookies and temporary cookies A persistent cookie is one stored as a file on your computer and it remains there
24. different time zones out write lt b gt out write lt br gt this out out now new Date printTime America New_ York printTime America Los_Angeles printTime Asia Shanghai printTime Europe Paris printTime Europe Moscow out write lt p gt out write lt p gt out write lt b gt out write Current JVM out write lt b gt out write lt br gt String s s java vm name wou out printIn s System getProperty s lt br gt s java vm version out println s System getProperty s lt br gt s os name out println s System getProperty s lt br gt s os version out println s System getProperty s lt br gt out write lt p gt out write lt p gt http www geocities com herong_yang jsp element html JspRuntimeLibrary include request response TimeStamp jsp out false out write lt p gt out write lt body gt out write lt html gt catch Throwable t 8 of 9 http www geocities com herong_yang jsp element html out _jspx_out if out null amp amp out getBufferSize 0 out clearBuffer if pageContext null pageContext handlePageException t finally if _jspxFactory null _jspxFactory releasePageContext pageContext Couple of interesting things to know in this example e The pre defined objects like out is not avail
25. file response setContentType text html charset gb23 12 out write lt p gt r nGB2312 binary OxCBB5C3F7 out write lt br gt r nGB23 12 xHEX amp xCBB5 amp xC3F7 out write lt br gt r nGB2312 WHEX UCBB5 uC3F7 out write lt br gt r nUnicode binary Ox8bf4660e out write lt br gt r nUnicode binary Ox8bf4660e out write lt br gt r nUnicode x HEX amp x8bf4 amp x660e out write lt br gt r nUnicode uHEX u8bf4 u660e out write lt br gt r nUnicode UTF8 OxE8AFB4E6988E If you change the charset to utf 8 I am sure Unicode UTF 8 line will be displayed correctly You know why By the way charset can also be specified as pageEncoding in the page directive statement Static HTML Text JSP Page in XML Syntax In the third test the static text is inserted into a JSP page in XML syntax lt xml version 1 0 encoding gb2312 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt jsp directive page contentType text html charset gb2312 gt lt StaticGB2312 jsp Copyright c 2002 by Dr Herong Yang gt lt html gt lt body gt lt p gt GB2312 binary OxCBB5C3F7 lt br gt GB2312 xHEX amp xCBB5 amp xC3F7 lt br gt GB2312 uHEX uUCBB5 uC3F7 lt br gt Unicode binary 0x8bf4660e lt br gt Unicode xHEX amp x8bf4 amp
26. gt You may have trouble read this file on this page or copy it to your local system because it contains non ASCII characters Bellow is the same file in hex number format You can use it to fix or regenerate HelpGB2312 html 3C68746D6C3E0D0A3C212D2D2048656C 704742323331322E68746D6C0D0A2020 202020436F7079726967687420286329 20323030342062792044722E20486572 6F6E672059616E670D0A2D2D3E0D0A3C 6D65746120687474702D65717569763D 22436F6E74656E742D54797065222063 6F6E74656E743D22746578742F68746D 6C3B20636861727365743D6762323331 32223E0D0A3C626F64793E0D0A3C623E CBB5C3F73C2F623E3C62722F3E0D0A3C 703ED5E2CAC7D2BBB7DDB7C7B3A3BCE4 B5A5B5C4CBB5C3F7CAE9A1AD3C2F703E 0D0A3C2F626F64793E0D0A3C2F68746D 6C3E0D0A When I opened HelpGB2312 html with IE Internet Explorer I saw Chinese characters correctly displayed on the screen I verified my IE encoding settings View menu and Encoding command it has Auto select checked and Chinese Simplified GB2312 selected I also verified my IE font settings Tools menu Internet Options command and Fonts button it has fonts installed for Chinese Simplified language When I changed my IE encoding setting to another encoding like UTF 8 I got strange characters showing up on the screen because I forced IE to decode my GB2312 encoded document with UTF 8 encoding schema Entering Non ASCII Characters in Java Strings Now let s look at the first part of the process to see how non ASCII chararters can be entered in
27. gt HelloTag lt tag class gt lt body content gt empty lt body content gt lt tag gt lt taglib gt 4 Installing the tld file Tag library descriptor files need to be accessible by the tomcat server So I copied HyTaglib tld to local jakarta tomcat 4 1 18 webapps root web inf tlds directory 5 Writing the JSP page To use my first custom tag I wrote the following JSP page hello_tag jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt 2 of 3 http www geocities com herong_yang jsp tag html lt hello_tag jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page import HelloTag gt lt jsp directive page contentType text html gt lt html gt lt body gt lt hy hello gt lt body gt lt html gt lt jsp root gt 6 Viewing the JSP page To see the output of my JSP page I copied hello_tag jsp to local jakarta tomcat 4 1 18 webapps root started tomcat 4 1 18 server and use Internet Explorer IE to view http localhost 8080 hello_tag jsp 7 I did get the Hello world message in the IE window So my hello tag worked perfectly 8 If you are changing your tag class after it has been loaded by tomcat you may need to restart tomcat or click restart on the root application on the tomcat admin page root application is where I put my JSP pages How Custom Tag Works Here is my
28. http java sun com JSP Page version 1 2 gt lt UseBean jsp Copyright c 2002 by Dr Herong Yang gt lt html gt lt body gt lt jsp directive page import CacheBean gt lt jsp useBean id b class CacheBean gt lt jsp setProperty name b property text value Hello world gt Property from my Bean lt jsp getProperty name b property text gt lt br gt Info from my Bean lt jsp expression gt b getInfo lt jsp expression gt lt body gt lt html gt lt jsp root gt Then I compiled CacheBean java with JDK 1 3 1 and copied CacheBean class to local jakarta tomcat 4 1 18 webapps root web inf classes Here is what I got by requesting UseBean jsp from IE Property from my Bean Hello world Info from my Bean My JavaBean Version 1 00 Note that CacheBean class needs to be imported into the JSP page The class file needs to be copied to the web inf classes directory It s very interesting to see the Servlet class translated from UseBean jsp 2 of 12 http www geocities com herong_yang jsp usebean html package org apache jsp import javax servlet import javax servlet http import javax servlet jsp import org apache jasper runtime import CacheBean public class UseBean_jsp extends HttpJspBase private static java util Vector _jspx_includes public java util List getIncludes return _jspx_includes public void _jspService HttpServletRequest request HttpServletRe
29. jsp Copyright c 2003 by Dr Herong Yang All rights reserved gt lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt lt jsp directive page import javax servlet http Cookie gt lt jsp scriptlet gt lt CDATA Setting a cookie with default properties out printIn lt b gt Cookie with default properties lt b gt lt br gt Cookie c new Cookie Date 30 Mar 2003 response addCookie c 3 of 6 http www geocities com herong_yang jsp cookie html out printIn Name c getName lt br gt out printIn Value c getValue lt br gt out printIn Domain c getDomain lt br gt out printIn Path c getPathO lt br gt out printIn MaxAge c getMaxAge lt br gt out printIn Version c getVersion lt br gt Setting a cookie with specified properties out printIn lt b gt Cookie with specified properties lt b gt lt br gt c new Cookie User Herong Yang c setMax Age 3 24 60 60 response addCookie c out printIn Name c getName lt br gt out printIn Value c getValue lt br gt out printIn Domain c getDomain lt br gt out printIn Path c getPathO lt br gt out printIn MaxAge c getMaxAge lt br gt out printIn Version c getVersion lt br gt Checking properties of the received cookies out printIn lt b gt Properties of the received cookies lt b
30. page with XML syntax to see how Tomcat server will convert them into Java class files and in what incodings Static HTML Text HTML Page In the first test the static text is inserted into a regular HTML file lt html gt lt StaticGB2312 html Copyright c 2002 by Dr Herong Yang gt lt body gt lt p gt GB2312 binary OxCBB5C3F7 lt br gt GB2312 xHEX amp xCBB5 amp xC3F7 lt br gt GB2312 uHEX uUCBB5 uC3F7 lt br gt Unicode binary 0x8bf4660e lt br gt Unicode xHEX amp x8bf4 amp x660e lt br gt Unicode uHEX u8bf4 u660e lt br gt Unicode UTF8 OxE8AFB4E6988E lt br gt lt p gt lt body gt lt html gt Now view StaticGB2312 html with IE and try to change the encoding schema in the View 8 of 13 http www geocities com herong_yang jsp non_ascii html menu Results match my expectations except one area e Westen European Windows Unicode xHEX line shows up correctly I wasn t expecting this and had no idea why e Chinese Simplified GB2312 GB2312 binary line shows up correctly e Unicode UTF 8 Unicode UTF8 line shows up correctly Since this is not a JSP Tomcat will not convert it into a Java class file I am using this test to validate that the codes are entered correctly Static HTML Text JSP Page in Standard Syntax In the second test the static text is inserted into a JSP page in standard syntax lt page contentT ype text html charset gb231
31. printIn Servlet Path request getServletPathO lt br gt out printIn Cookies lt br gt javax servlet http Cookie cookies request getCookies for int i 0 i lt cookies length i out printIn amp nbsp amp nbsp cookies i getName cookies i getValue lt br gt out printIn Headers lt br gt java util Enumeration e request getHeaderNames while e hasMoreElements String n String e nextElement out printIn amp nbsp amp nbsp n request getHeader n lt br gt 4 of 6 http www geocities com herong_yang jsp context html P gt lt p gt lt body gt lt html gt Output Information about request Class Name org apache coyote tomcat4 CoyoteRequestFacade Auth Type null Context Path Method GET Path Info null Path Translated null Query String null Remote User null Requested Session ID 13190484CD4CE195C9434A318D46950E Request URI RequestInfo jsp Request URL http localhost 8080 RequestInfo jsp Servlet Path RequestInfo jsp Cookies JSESSIONID 13190484CD4CE195C9434A318D46950E Headers accept image gif image x xbitmap image jpeg image pjpeg accept language en us accept encoding gzip deflate user agent Mozilla 4 0 compatible MSIE 6 0 MSNIA Windows NT host localhost 8080 connection Keep Alive cookie JSESSIONID 13190484CD4CE195C9434A3 18D46950E The session Object session A object provided by the JSP serve
32. program will decide what to do with the actual response data in the entity body If you use a Web browser as a HTTP client program it will process the data in the entity body differently depending on mainly the Content_Type entity header line displaying the data as it is rendering the data as a HTML document and displaying the resulting information or passing the data to other registered programs to handle it Once the Web browser finishes processing the entity body you can get some limited information from the header lines For example you can click the right mouse button and select the properties command on Internet Explorer it will display some general properties about this response in a pop up window The properties displayed are not always identical to the response header lines The Modified property is probably identical to the Last_Modified entity header line The Type property is sometime related to the Content_Type entity header line and sometimes related to server side resource that generated the response For example if you use Internet Explorer to request hello jsp from a JSP Web server and view the page properties you will see JavaServer Page in the Type property But the Content_Type header line received from this JSP page is text html How to view all the header lines received in the HTTP response I couldn t find any existing tools to do this So wrote the following program to dump the entire response includ
33. that will be translated and executed by the JSP server There are three types of JSP elements Directive Element A JSP element that provides global information for the translation phase There are two ways to write a directive element lt directive_name attribute value gt Action Element A JSP element that provides information for the execution phase lt action_name attribute value gt action_body lt action_name gt lt action_name attribute value gt Scripting Element A JSP element that provides embedded Java statements There are three types of scripting elements Declaration Element A JSP element that provides the embedded Java declaration statements to be inserted into the Servlet class lt 9 Java decalaration statements gt Scriptlet Element A JSP element that provides the embedded Java statements to be executed as part of the service method of the Servlet class There are two ways to write a scriptlet element lt Java statements gt Expression Element A JSP element that provides the embedded Java expressions to be 1 of 9 http www geocities com herong_yang jsp element html evaluated as part of the service method of the Servlet class There are two ways to write an express element lt Java expressoins gt Writing JSP Pages in XML Format JSP pages can also be written in XML format To do this you have to use the XML version of the syntaxes for directive elements declara
34. x660e lt br gt Unicode uHEX u8bf4 u660e lt br gt 10 of 13 http www geocities com herong_yang jsp non_ascii html Unicode UTF8 OxE8 AFB4E6988E lt br gt lt p gt lt body gt lt html gt lt jsp root gt If you view this page with IE you should will see that only Unicode xHEX line is displayed correctly This is a big supprise to me e The XML parser in Tomcat is not deconding my JSP page with gb2312 e My JSP page seems to be decoded with ISO 8859 1 Windows default encoding scheme e The 0x0e code in Unicode binary line is causing trouble to Tomcat server so I have to remove those binary codes e The Java class file is generated in UTF 8 encoding e The out object and the Content Type header are set correctly to GB2312 The XML entity codes xHEX lines are decoded into binary values This is different than the standard syntax e Here are the related lines of the generated Java class file response setContentType text html charset gb2312 out write lt p gt out write nGB2312 binary 0xCBB5C3F7 out write lt br gt out write nGB23 12 xHEX out write out write out write lt br gt out write nGB2312 WHEX UCBB5 uC3F7 out write lt br gt out write nUnicode binary 0x8bf4660e out write lt br gt out write nUnicode xHEX out write out write out write lt br gt
35. 003 Home Help TOC Herong s Notes on JSP JSP Standard Tag Libraries JSTL 5 of 5 http www geocities com herong_yang jsp jstl_el html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC JSTL Syntax and Expression Language This chapter explains e Basics on JSTL syntax e Basics on Expression Language e Literal data and named variables e Basic operators and operations e Accessing collection elements and object properties e ExpExample jsp Expression examples JSP page e pageContext attributes and JSTL top level identifiers JSTL Syntax JSTL syntax is very simple JSTL allows you to write tags in JSP pages Each tag is actually called an action Every action must be written as an XML element The syntax of an JSTL action XML element is something like these lt p tag attribute text_only gt lt p tag gt xml_body lt p tag gt lt p tag attribute text_only gt xml_body lt p tag gt lt p tag attribute expression gt xml_body lt p tag gt lt p tag attribute text expression text express gt xml_body lt p tag gt As you can see there are a number variations in the syntax e An action can be an empty or non empty XML element e An action can have zero one or many attributes e Attribute values can be text only or mixed with expressions e Anexpress is always written in the format of expression 1 of 9 http www ge
36. 10 milliseconds As you can see from the testing page I used setTime to store the current time at the beginning of my prime number checking process as t1 and the current time at the end as t2 Then I used out to retrieve them and calculate their difference in a single expression Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP Tags Working Together 6 of 6 http www geocities com herong_yang jsp tomcat_jdk141 html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC Tomcat 4 1 18 with JDK 1 4 1 This chapter explains e How to change Tomcat 4 1 18 installation from using JDK 1 3 1 to using JDK 1 4 1 e Compilation issues of using JavaBean classes in unnamed packages e How to create JavaBean classes in named packages Upgrading Tomcat 4 1 18 to JDK 1 4 1 One of the readers reported a JSP compilation issue while following my tutorials with Tomcat 4 1 29 and JDK 1 4 x In order to understand the issue better I upgraded my Tomcat 4 1 18 installation from JDK 1 3 1 to JDK 1 4 1 1 Checked my JDK 1 4 1 installation The following command shows that I have JDK 1 4 1_01 working correctly gt local j2sdk1 4 I bin java version java version 1 4 1_01 Java TM 2 Runtime Environment Standard Edition build 1 4 1_01 b01 Java HotSpot TM Client VM build 1 4 1_01 b01 mixed mode 2 Started Tomcat server with JDK 1 4 1 without any problem cd local jakar
37. 12 HelpGB2312 html test html You could also enter non ASCII characters as Unicode codes in UTF 8 format This is very easy to do if you have a special text editor that supports Unicode UTF 8 encoding and input interface for your local language characters Entering Non ASCII Characters as Static HTML Text Entering non ASCII characters as static HTML text is much harder than what I initially thought There are many factors that should be considered e JSP page syntax Using standard syntax or XML syntax e Encoding schema of the JSP page source code e Encoding schema of the converted Java source code 7 of 13 http www geocities com herong_yang jsp non_ascii html e Encoding schema of the HTTP response In order to test out how to control those factors I picked two simplified Chinese characters and entered them in 7 different formats as a simple HTML paragraph lt p gt GB2312 binary OxCBB5C3F7 lt br gt GB2312 xHEX amp xCBB5 amp xC3F7 lt br gt GB2312 uHEX uCBB5 uC3F7 lt br gt Unicode binary 0x8bf4660e lt br gt Unicode xHEX amp x8bf4 amp x660e lt br gt Unicode uHEX u8bf4 u660e lt br gt Unicode UTF8 OxE8AFB4E6988E lt br gt lt p gt Hex numbers are provided next to the binary codes just in case if you have trouble to copy this file to your local system In the next 3 sections I will put this paragraph into a regular HTML file a JSP page with standard syntax and a JSP
38. 2 gt lt StaticGB2312 jsp Copyright c 2002 by Dr Herong Yang gt lt html gt lt body gt lt p gt GB2312 binary OxCBB5C3F7 lt br gt GB2312 xHEX amp xCBB5 amp xC3F7 lt br gt GB2312 uHEX uUCBB5 uC3F7 lt br gt Unicode binary 0x8bf4660e lt br gt Unicode xHEX amp x8bf4 amp x660e lt br gt Unicode uHEX u8bf4 u660e lt br gt Unicode UTF8 OxE8AFB4E6988E lt br gt lt p gt lt body gt lt html gt If you view this page in IE you will that see both GB2312 binary line and Unicode xHEX line are displayed correctly Here is the explanation e The charset value gb2312 in the page directive statement tells Tomcat to read this JSP files as GB2312 encoding So GB2312 binary line is decoded correctly into Unicode codes e All other binary lines are decoded incorrectly because they are not GB2312 codes e Uicode xHEX line is not decoded because they are normal ASCII characters e When generating the Java class file all strings are encoded as UTF 8 This is the default setting of Tomcat You can change this in the conf web xml file e The charset value gb2312 also tells Tomcat to change the encoding to GB2312 on the out object and the Conten Type HTTP header so the generated HTML document will 9 of 13 http www geocities com herong_yang jsp non_ascii html in GB2312 encoding To appove the above explanation here is the related lines of the generated Java class
39. 23 Mar 2003 13 46 53 GMT Author Herong Yang Author Joe Wang Content Type text xml charset UTF 8 9 of 14 http www geocities com herong_yang jsp response_header html Content Length 38 Date Sat 23 Mar 2003 13 46 53 GMT Server Apache Coyote 1 0 Connection close lt html gt lt body gt Hello world lt body gt lt html gt Note that e There are two Content_Type header lines one from my setHeader call and one added by Tomcat My guess is that Tomcat does not recognize the Content_Type header line generated by the addHeader method So we have to use setContentType method to control the Content_Type header line e The same issue also exists on the Content_Length header line We have to use setContentLength method to control the Content_Length header line e The setIntHeader method is called twice with the same header line name Content_Length The second call overrides the first call e I added two new header lines called Author Here is the revised version of the second example SetHeaderRevised jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt SetHeaderRevised jsp Copyright c 2002 by Dr Herong Yang gt lt jsp scriptlet gt lt CDATA response setContentType text html charset UTF 8 String text lt html gt lt body gt Hello world lt body gt lt html gt response setContentLength text length response setDate
40. 3 x Then I clicked the IE refresh button I got the following in the IE window Cookie with default properties Name Date Value 30 Mar 2003 Domain null Path null MaxAge 1 Version 0 Cookie with specified properties Name User Value Herong Yang Domain null Path null MaxAge 259200 5 of 6 Version 0 Properties of the received cookies Name Date Value 30 Mar 2003 Domain null Path null MaxAge 1 Version 0 Name User Value Herong Yang Domain null Path null MaxAge 1 Version 0 Name JSESSIONID Value 37CB87D855A94F84355FE86626D2BAF7 Domain null Path null MaxAge 1 Version 0 It is interesting to know that http www geocities com herong_yang jsp cookie html e The setMaxAge did force the Web browser to save the cookie to the local hard disk e The persisted cookie User has the default domain localhost and default path jsp e When this persisted cookie User was posted to the server again the MaxAge value got reset to 1 again e Cookie SESSIONID was added by the Web server not by my program Dr Herong Yang updated in 2003 Herong s Notes on JSP Using Cookies 6 of 6 Home Help TOC http www geocities com herong_yang jsp response_header html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC Controlling HTTP Response Header Lines HTTP Response Syntax Based on HTTP 1 1 protocol afte
41. 3 03 29 21 GMT Server Apache Coyote 1 0 Connection close PDF 1 3 Again Content_Type was set correctly to application pdf for file name extension pdf as defined in the MIME settings I truncated the entity body to save some space Response Header Lines Affected by jsp directive page Elements As I mentioned earlier the first way to control the response header lines is to use jsp directive page elements Let me use the following 3 example JSP pages to show you how to do this Copy the first example JSP page hello jsp to Tomcat server lt html gt lt body gt lt out printIn Hello world gt lt body gt lt html gt Then obtain the response with java HttpRequestGet hello jsp 8080 HTTP 1 1 200 OK Set Cookie JSESSIONID 4BEF55D47FC7A80A75A97082756B772E Path Content Type text html charset ISO 8859 1 Content Length 44 Date Sat 23 Mar 2003 21 48 54 GMT Server Apache Coyote 1 0 Connection close lt html gt lt body gt Hello world lt body gt lt html gt hello jsp was written in an HTML format with embedded JSP statements so Tomcat decided to 6 of 14 http www geocities com herong_yang jsp response_header html set Content_Type to text html charset ISO 8859 1 which is perfectly ok Copy the second example JSP page hello_xml jsp Tomcat server lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt hello_xml jsp Copy
42. 684 u8aaa u660e u66f8 u2026 lt p gt out println lt body gt out printIn lt html gt gt lt jsp scriptlet gt lt jsp root gt View this page with IE you should see the same message appear twice one as simplified Chinese and the other as tranditional Chinese Conclusion As you can see from my notes in the previous sections localizing or internationalizing JSP pages is not an easy task My recommendations are e Avoid using static text Put the entire page under a scriptlet so all text messages are generated from Java statements e Using Unicode codes in UTF 8 format or UHEX format for string literals It allows to 12 of 13 http www geocities com herong_yang jsp non_ascii html support characters in all local languages in a single encoding e Use UTF 8 as the HTML document encoding instead of encodings of a particular local language like GB2312 This may cause problems for users on locale systems where Unicode fonts are not supported But more and more locale systems are supporting Unicode and UTF 8 encoding e I still don t know how to control the source code encoding of JSP pages in XML syntax Dr Herong Yang updated in 2002 Home Help TOC Herong s Notes on JSP Localization Internationalization Non ASCII Characters in JSP Pages 13 of 13 http www geocities com herong_yang jsp performance html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC J
43. Core Library e JJSTL Core Library e c out Action e c set Action e c if Action e c choose Action e c forEach Action e c forTokens Action e JSTL Core Example JstlObjects jsp e JSTL Core Example JstIPrimeNumbers jsp JSP Custom Tag e What is a Custom Tag e Hello world Custom Tag e How Custom Tag Works 3 of 4 9 7 2004 3 17 PM JSP Tag Java Interface e javax servlet jsp tagext Package e BodyTag Interface e Implenting BodyTag Interface TraceTag java e The Servlet Class TraceTagTest_jsp java e Dummy Implementation of IterationTag Interface TagSupport Class JSP Tag Attribute Handling e Tag Attribute Setter Method e Tag Attribute Setter Method Example EchoTag java e Tag Attribute Value Type Conversion e Tag Attribute Value Type Conversion Example AttValueTag java e Tag Attribute Value Expression e Tag Attribute Value Expression Example AttObjectTag java Tags Working Together e Nested Tags e Sharing Data with Other Tags Tomcat 4 1 18 with JDK 1 4 1 e Upgrading Tomcat 4 1 18 to JDK 1 4 1 e Compilation Errors with Tomcat 4 1 18 and JDK 1 4 1 e JavaBean in a Named Package TempratureConvertorBean java References Key Words attachment Big5 book Chinese content disposition content_type cookie custom tag debugging example expression language GB2312 GBK header lines HTTP 1 1 HTTP Response internationalization i18n IterationTag JavaBeen JSP JSTL JSTL EL
44. Enter non ASCII characters in the encoded form required by the HTML document as sequence of types and use Java binary output stream to generate the HTML document e 2 Enter non ASCII characters in Unicode codes and use Java writer output stream to generate the HTML with the stream set to the encoding required by the HTML document e 3 Enter non ASCII characters as static HTML text and let the JSP server to convert them into out write statements to generate the HTML document Java Strings Byte Sequences Encoded for Local Languages Let s try option 1 mentioned in the previous section first Here is my sample JSP page lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt HelpGB2312Java jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page contentType text html charset gb2312 gt lt jsp declaration gt lt CDATA private java io OutputStream outStream private void writeGB String s throws Throwable for int i 0 i lt s lengthQ i char c s charAt i byte b byte c gt gt 8 amp OxOOFF 5 of 13 http www geocities com herong_yang jsp non_ascii html fif b gt 0 outStream write b b byte c amp OxOOFF outStream write b gt lt jsp declaration gt lt jsp scriptlet gt lt CDATA outStream response getOutputStream writeGB lt html gt writeGB lt meta http equiv
45. Header Last Modified System currentTimeMillis response setHeader Author Herong Yang out print text gt lt jsp scriptlet gt lt jsp root gt Generating Non HTML Entity Body Sometimes you may want to send back information in the entity body that are not in the HTML format for example a PDF document or MS Word Document In this case we have to set Content_Type Content_Length and other header lines carefully to provide correct information about the entity body for the client program Here is a sample JSP page to show you how to set header lines for different types of data in the entity body 10 of 14 http www geocities com herong_yang jsp response_header html lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt GetFile jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page session false import java io gt lt jsp scriptlet gt String p request getQueryString boolean ok true ok p null if ok if p indexOf html gt 1 response setContentT ype text html else if p indexOf gif gt 1 response setContentT ype image gif else if p indexOf pdf gt 1 response setContentT ype application pdf else if p indexOf doc gt 1 response setContentT ype application msword else ok false if ok try int int new File p lengthQ response setContentLeng
46. Hello world gt lt body gt lt html gt you will get something similar to this local j2sdk1 4 1_01 bin java cp HttpResponseTest 1 hello jsp 8080 Performace Information Number of tests 1 Time seconds Rerulst of Last Test lt html gt lt body gt Hello world lt body gt lt html gt I repeated the tests by changes the controlling parameters The following table shows the results comparing with similar tests I did with other technologies Number Debug Time Cases of Tests Mode Sec Note 1000 No 2 Static text with IIS 5 0 2000 No 4 Static text with IIS 5 0 1000 No 6 ASP page with IIS 5 0 2000 No 11 ASP page with IS 5 0 1000 7 Static text with Tomcat 4 1 18 2000 15 Static text with Tomcat 4 1 18 1000 8 JSP page with Tomcat 4 1 18 aS Ce to 4 of 5 http www geocities com herong_yang jsp performance html 8 2000 16 JSP page with Tomcat 4 1 18 Conclusion e So the performance cost of writing text through ASP statements is 2 times slower than the static pages e Tomcat is 3 times slower than IIS when serving static pages e Tomcat is also slower than IIS when serving dynamic text Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP JSP Performance 5 of 5 http www geocities com herong_yang jsp jstl html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC JSP Standard Tag Libraries JSTL What is JSTL JSTL
47. Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC Herong s Notes on JSP Version 3 03 Dr Herong Yang Copyright 2001 2003 by Dr Herong Yang All rights reserved Table of Contents About This Book Tomcat e Installing Tomcat 4 1 18 e Using Tomcat as a Web Server e Hello world Example JavaServer Pages JSP e What is JSP e Hello world Java Servlet Class e Writing JSP Servlet Class Directly Execution Context e Predefined Objects e The request Object e The session Object JSP Elements e Syntactic Elements of a JSP Page e Writing JSP Pages in XML Format e Directive Elements e Action Elements 1 of 4 9 7 2004 3 17 PM e JSP Example CurrentTime jsp JSP Sessions and Debugging e What Is a Session e The session Object e Passing Values between Pages e HTTP Communication Level Debugging Using JavaBean Classes e The jsp useBean Action Elements e Compilation Errors with Tomcat 4 1 18 and JDK 1 4 1 e Setting and Getting JavaBeans Properties e Using JavaBeans as Objects in Scripting Elements e Using Java Objects as JavaBeans e Refreshing the Loaded Bean Classes Using Cookies e What is a Cookie e Sending and Receiving Cookies e Persistent Cookies Controlling HTTP Response Header Lines e HTTP Response Syntax e HTTP Response Header Lines Controlling Response Header Lines Viewing Response Header Lines Response H
48. JSP pages converted into Java programs and outputed into HTML documents Rules related to these steps are e Non ASCII characters can be entered JSP pages in two ways as static HTML text and as dynamic Java statements e Java strings are sequences of 2 byte characters e Non ASCII characters can be entered into Java string literals as Unicode codes in u hex 4 of 13 http www geocities com herong_yang jsp non_ascii html digits sequences e Non ASCII characters can also be entered into Java string literals as Unicode codes in UTF 8 encoding byt sequences You may need a UTF 8 sensitive editor to enter your Java source code because regular text editor may not be able to recongnize UTF 8 byte sequences e Java can convert Unicode codes to various local language codes as encoding processes at the character based output stream level e JSP server object response offers two output streams response getWriter and response getOutputStream You can only use one of the two streams in a single JSP page e response getWrite allows you to output characters with Unicode encoding specified by the response setContentType method e response getOutputStream allows you to output binary bytes e Static HTML text will be converted into out write statemenss e JSP page can be written as an XML file which requires XML encoding rules Based these rules we have three options to output a HTML document with non ASCII characters e 1
49. P Custom Tag What is a Custom Tag Custom Tag is an action tag defined by the user through the JSP tag extension facility It can be used to move JSP page authoring logics and information into a tag Java class and invoke it by an action tag that is linked to that class There are two main advantages of using custom tags e Repeatable JSP page logics and information can be simplified and centralized into a single tag For example we can define a custom tag called lt my copyright gt for producing the copyright information that need to be used on every page of server e Moving complex business logics from the JSP to a tag class so the JSP page author can concentrate on the presentation logics only For example we can define a custom tag called lt my userList gt for producing a HTML table filled with a list of users The tag class will manage how the put each user into a row and each user property into a column I am sure that the functionalities provided by custom tags can also be archived by using JavaBean and scripting elements together But tags seem to be simpler to use for many unsophisticated JSP page authors Hello world Custom Tag Before we go into any technical details let me use a very simple example to show you the steps to define and use a custom tag I want to define a tag called lt hy hello gt to produce the Hello world in the calling JSP page 1 Writing the tag class Here is my first tag class HelloTag jav
50. P page lof5 http www geocities com herong_yang jsp jsp html e Compilation A JSP page must be compiled into a Java Servlet class before it can be executed The server can compile a JSP page in real time when the page is requested for the first time if the page is not pre compiled e Execution When a JSP page is requested its compiled class will be executed on the server The server will send back the output of the execution not the content of the JSP page Hello world Java Servlet Class To understand more about the JSP compilation process let s use my hello jsp again lt html gt lt body gt lt out printIn Hello world gt lt body gt lt html gt Then save hello jsp to local jakarta tomcat 4 1 18 webapps ROOT and run IE with url http localhost 8080 hello jsp You should see Hello world in the IE window Now if you look at the directory local jakarta tomcat 4 1 18 work standalone localhost _ you will see a Java file hello_jsp java package org apache jsp import javax servlet import javax servlet http import javax servlet jsp import org apache jasper runtime public class hello_jsp extends HttpJspBase private static java util Vector _jspx_includes public java util List getIncludes return _jspx_includes public void _jspService HttpServletRequest request HttpServletResponse response throws java io IOException ServletException JspFactory _jspxFactory
51. P page is requested for the first time Subsequent requests will share the same session Click the refresh button on the Web browser you will see that the session ID will be the same the create time will be the same but the last access time will be the new time and is session new will be false The request Object The request object is an important object to the JSP page because it contains a lot of useful information The following JSP page will you some details of the request object lt RequestInfo jsp Copyright c 2002 by Dr Herong Yang All rights reserved gt lt html gt lt body gt lt p gt lt b gt Information about request lt b gt lt br gt lt out printIn Class Name request getClass getName lt br gt out printIn Auth Type request getAuthType lt br gt out printIn Context Path request getContextPath lt br gt out printIn Method request getMethod lt br gt out println Path Info request getPathInfo lt br gt out printIn Path Translated request getPathTranslated lt br gt out println Query String request getQueryString lt br gt out printIn Remote User request getRemoteUser lt br gt out printIn Requested Session ID request getRequestedSessionId lt br gt out printIn Request URI request getRequestURIQ lt br gt out printIn Request URL request getRequestURLQ lt br gt out
52. SP Performance Calculating Prime Numbers The first area I want to test for performance is integer arithmetic calculations The following JSP page calculates prime number starting from number 3 and repeats the test many times lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt PrimeNumbers jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt jsp directive page import java util gt lt jsp scriptlet gt lt CDATA int primes new int 1000 int numberOfTests 100 int numberOfPrimes 1000 long tl System currentTimeMillisQ for int nTest 1 nTest lt numberOfTests nTest Getting prime numbers int nPrime 0 int i 2 while nPrime lt numberOfPrimes i it l int j 2 boolean isPrime true while j lt i amp amp isPrime isPrime i j gt 0 j j 1 if isPrime nPrime nPrime 1 primes nPrime 1 i long t2 System currentTimeMillis lof5 long t t2 tl Displaying the results out printIn lt html gt lt body gt out printIn lt b gt Performace Information lt b gt lt br gt http www geocities com herong_yang jsp performance html out printIn Number of tests numberOfTests lt br gt out printIn Time t 1000 seconds lt br gt out printIn lt b gt numberOfPrimes prime numbers lt b gt l
53. T WEB INF lib standard jar C local jakarta tomcat 4 1 18 shared classes C local jakarta tomcat 4 1 18 common classes C local jakarta tomcat 4 1 18 common endorsed xercesImpl jar C local jakarta tomcat 4 1 18 common endorsed xmlParserAPIs jar C local jakarta tomcat 4 1 18 common lib activation jar C local jakarta tomcat 4 1 18 common lib ant jar C local jakarta tomcat 4 1 18 common lib commons collections jar C local jakarta tomcat 4 1 18 common lib commons dbcp jar C local jakarta tomcat 4 1 18 common lib commons logging api jar C local jakarta tomcat 4 1 18 common lib commons pool jar C local jakarta tomcat 4 1 18 common lib jasper compiler jar C local jakarta tomcat 4 1 18 common lib jasper runtime jar C local jakarta tomcat 4 1 18 common lib jdbc2_0 stdext jar C local jakarta tomcat 4 1 18 common lib jndi jar C local jakarta tomcat 4 1 18 common lib jta jar C local jakarta tomcat 4 1 18 common lib mail jar C local jakarta tomcat 4 1 18 common lib naming common jar C local jakarta tomcat 4 1 18 common lib naming factory jar C local jakarta tomcat 4 1 18 common lib naming resources jar 6of7 http www geocities com herong_yang jsp jstl_core html C Mocal jakarta tomcat 4 1 18 common lib servlet jar JSTL Core Example JstIPrimeNumbers jsp As my second JSTL core example JstIPrimeNumbers jsp is to calculate if a given number is prime number or not lt xml version 1 0 gt lt jsp root xmlns jsp http java su
54. Yang All rights reserved package herong import java util import java io import javax servlet jsp import javax servlet jsp tagext import org apache taglibs standard lang support public class AttObjectTag extends TagSupport private String booleanAtt null private Boolean booleanObject null 8 of 12 http www geocities com herong_yang jsp tag_attribute html private String stringAtt null private String stringObject null private String mapAtt null private Map mapObject null public void setBooleanAtt String att booleanAtt att try booleanObject Boolean ExpressionEvaluatorManager evaluate pooleanAtt booleanAtt java lang Boolean class this pageContext catch JspException e System err printIn e toString public void setStringAtt String att stringAtt att try stringObject String ExpressionEvaluatorManager evaluate stringAtt stringAtt java lang String class this pageContext catch JspException e System err printIn e toString public void setMapAtt String att mapAtt att try mapObject Map ExpressionEvaluatorManager evaluate mapAtt mapAtt java util Map class this pageContext catch JspException e System err printIn e toString public int doStartTagQ JspWriter out pageContext getOut try out printin booleanAtt booleanAtt lt br gt out println booleanObjec
55. _jspxFactory null _jspxFactory releasePageContext pageContext 6 of 8 http www geocities com herong_yang jsp tag_interface html private boolean _jspx_meth_hy_trace_0 javax servlet jsp PageContext pageContext throws Throwable JspWriter out pageContext getOut hy trace herong TraceTag _jspx_th_hy_trace_0 herong TraceTag _jspx_tagPool_hy_trace_myAtt get herong TraceTag class _jspx_th_hy_trace_0 setPageContext pageContext _jspx_th_hy_trace_0 setParent null _jspx_th_hy_trace_0 setMyAtt my value int _jspx_eval_hy_trace_0 _jspx_th_hy_trace_0 doStartTagQ if _jspx_eval_hy_trace_0 javax servlet jsp tagext Tag SKIP_BODY do out write JSP body out write lt br gt int evalDoAfterBody _jspx_th_hy_trace_0 doAfterBody if evalDoAfterBody javax servlet jsp tagext BodyTag EVAL_BODY_AGAIN break while true if _jspx_th_hy_trace_0 doEndTag javax servlet jsp tagext Tag SKIP_PAGE return true _jspx_tagPool_hy_trace_myAtt reuse _jspx_th_hy_trace_0 return false As you can see the entire hy trace element was translated into a method call _jspx_meth_hy_trace_O pageContext In that method an object was instantiated from my trace tag class Then interface methods were called one by one in the same order as we discussed in the previous section The do loop was there to re evaluate the body based on the returning flag of doAfterBody call After fin
56. _tagPool_hy_trace_myAtt public TraceTagTest_jspQ _jspx_tagPool_hy_trace_myAtt new org apache jasper runtime TagHandlerPool public java util List getIncludes return _jspx_includes public void _jspDestroy 5 of 8 http www geocities com herong_yang jsp tag_interface html _jspx_tagPool_hy_trace_myAtt release public void _jspService HttpServletRequest request HttpServletResponse response throws java io IOException ServletException JspFactory _jspxFactory null javax servlet jsp PageContext pageContext null HttpSession session null ServletContext application null ServletConfig config null JspWriter out null Object page this JspWriter _jspx_out null try _jspxFactory JspFactory getDefaultFactory response setContentType text html charset UTF 8 pageContext _jspxFactory getPageContext this request response null true 8192 true application pageContext getServletContext config pageContext getServletConfig session pageContext getSession out pageContext getOut _jspxX_out out out write lt html gt out write lt body gt if _jspx_meth_hy_trace_O pageContext return out write lt body gt out write lt html gt catch Throwable t out _jspx_out if out null amp amp out getBufferSize 0 out clearBuffer if pageContext null pageContext handlePageException t finally if
57. a which extends the TagSupport class provided in the JSP package HelloTag java Copyright c 2003 by Dr Herong Yang All rights reserved import java io import javax servlet jsp tagext public class HelloTag extends TagSupport public int doStartTagQ 1 of 3 http www geocities com herong_yang jsp tag html try pageContext getOut write Hello world catch IOException e System err printIn e toString return SKIP_BODY 2 Installing the tag class I compiled HelloTag java with JDK 1 3 1 and servlet jar provided by the Tomcat 4 1 18 server Like the JavaBean class files tag class files also need to be installed in the class path of the tomcat server So I copied the HelloTag class to local jakarta tomcat 4 1 18 webapps root web inf classes directory 3 Writing the tag library descriptor tld file Now I need to define a tag in a tag library descriptor file to use the tag class Here is my first tld file HyTaglib tld lt xml version 1 0 gt lt DOCTYPE taglib PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by Dr Herong Yang gt lt taglib gt lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt hello lt name gt lt tag class
58. able in the directive elements So I used an instance variable out to pass the pre defined out to my printTime method in the declaration element e Since Iam using XML format lt needs to be replaced by the entity name amp lt in any Java statements During the translation process the entity names will be replaced back to ng e No Servlet class was created for JvmStamp jsp because its content was included into CurrentTime jsp during the translation process e TimeStamp jsp was treated differently than JvmStamp jsp TimeStamp jsp was translated independently into a Servlet class Its service method was called by CurrentTime_jsp java during execution Dr Herong Yang updated in 2002 Home Help TOC Herong s Notes on JSP JSP Elements 9 of 9 http www geocities com herong_yang jsp session html Herong s Notes on JSP Dr Herong Yang Version 3 03 2002 Home Help TOC JSP Sessions and Debugging This chapter describes e What is a session and how a JSP server uses cookies to pass an IDs to the browser to link multiple HTTP requests together as a session e What is the session object and what functions are available on the session object e A sample application to show you how to pass data between JSP pages e How Perl tools can be used to help debug JSP applications at the HTTP communication level What Is a Session session A concept to represent a series of HTTP requests and response
59. acters can safely travel through those steps without any issues However for non ASCII characters we have to watch out each steps carefully to make sure that characters are not damaged and or decoded correctly if encoded ASCII Characters in JSP Pages As I mentioned earlier ASCII characters can travel from JSP files to browsers easily without any trouble Here is a simple JSP file with ASCII characters only lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt HelpASCILjsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt b gt Help lt b gt lt br gt lt p gt This is a very simple help page lt p gt 2 of 13 http www geocities com herong_yang jsp non_ascii html lt body gt lt html gt lt jsp root gt If you view this page with a browser you will get two lines of characters Help This is a very simple help page They are exactly what I entered into the JSP file Presenting Non ASCII Characters in HTML Documents In order to ensure non ASCII characters entered in JSP files to show up on browser screens correctly we need to understand how non ASCII characters are processed from one step to the other The processing steps can be grouped into two parts e Outputing HTML documents with non ASCII characters steps 0 1 2 and 3 e Presentin
60. ader line indicating the new URL Obviously this response was generated by the sendRedirect function in my JSP page RegForm jsp The LWP UserAgent object is smart It recognized the 302 Moved Temporarily code and automatically send another request with new URL location With no surprises the third response came ok The JSP did recognize my session ID in my second and third request But response content was missing in the debugging log for some reason But the response was captured in the my regular output file client out It is interesting to see that there was no cookie in the second response and third response My guess is that JSP server saw the session ID in the second request and third request so there was no need to put the session ID as a cookie in the responses Dr Herong Yang updated in 2002 Home Help TOC Herong s Notes on JSP JSP Sessions and Debugging 10 of 10 http www geocities com herong_yang jsp usebean html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC Using JavaBean Classes This chapter explains e How to load a JavaBean into JSP pages and manipulate its properties e Compilation issues of using JavaBean classes in unnamed packages e Setting and getting JavaBeans properties e Using JavaBeans as Java objects in scripting elements e Using Java objects as JavaBeans e How to refresh the JavaBean objects loaded in memory The jsp useBean Action El
61. age Hi there Hi there Hello world Sat Jul 12 14 06 16 EDT 2003 Sun Jul 13 14 06 16 EDT 2003 Sat Sep 08 21 46 40 EDT 2001 1000000000000 NDAN WNK Note that e useBean element also adds an attribute to pageContext For more information see chapter Using JavaBean Classes Exercise Since there many methods to add an attribute to pageContext useBean c set and pageContext setAttribute write a simple program to show what happens if the same attribute name is used by different methods Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP JSTL Syntax and Expression Language 9 of 9 http www geocities com herong_yang jsp jstl_core html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC JSTL Core Library JSTL Core Library JSTL core libary can be introduced to a JSP page with lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt It provides the following basic scripting functions lt c out value gt lt c set var value gt lt c if test gt body lt c if gt lt c choose gt body lt c choose gt lt c forEach items gt body lt c forEach gt lt c forTokens items delims gt body lt c forTokens gt c out Action lt c out value text_mixed_with_expressions gt The value attribute will be evaluated and the resulting value wil
62. age xmlns c http java sun com jstl core xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt lt SetTimeTagTest jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt hy setTime var t1 gt lt p gt Checking prime numbers lt p gt lt c set var upperLimit value 50 gt lt c forEach var i begin 3 end upperLimit gt lt c set var isPrime value true gt lt c forEach var j begin 2 end i 1 gt lt c if test 1 j 0 gt lt c set var isPrime value false gt lt We should break the loop here gt lt c if gt lt c forEach gt lt c choose gt lt c when test isPrime gt lt c out value i is a prime number gt lt br gt lt c when gt lt c otherwise gt lt c out value i is a not prime number gt lt br gt lt c otherwise gt lt c choose gt lt c forEach gt lt hy setTime var t2 gt lt p gt lt c out value Total time t2 t1 milliseconds gt lt p gt lt body gt lt html gt lt jsp root gt The output Checking prime numbers 5 of 6 http www geocities com herong_yang jsp tag_parent html 3 is a prime number 4 is a not prime number 5 is a prime number 6 is a not prime number 7 is a prime number 8 is a not prime number 9 is a not prime number 10 is a not prime number 50 is a not prime number Total time 1
63. akarta taglibs standard current zip e Unzip it to local directory and read local jakarta taglibs standard 1 0 4 README e Then create a new directory in Tomcat server mkdir local jakarta tomcat 4 1 18 webapps ROOT WEB INF lib and copy jar files to there lof5 http www geocities com herong_yang jsp jstl html copy local jakarta taglibs standard 1 0 4 lib jar local jakarta tomcat 4 1 18 webapps ROOT WEB INF lib e Restart Tomcat and you are ready to try Taglib 1 0 4 Hello world with JSTL To understand how JSTL works let s try a very simple example using JSTL to display Hello world Here is my JSP source code hello_jstl jsp lt taglib uri http java sun com jstl core prefix c gt lt html gt lt body gt lt c out value Hello world gt lt body gt lt html gt Save it to local jakarta tomcat 4 1 18 webapps ROOT and run IE with url http Nocalhost 8080 hello_jstl jsp Guess what You will receive crashing page with an error message like javax servlet ServletException Cannot inherit from final class So what happened I really don t know My guess is that some of the jar files from Taglib 1 0 4 are not compatible with Tomcat 4 1 18 To approve this I removed all Taglib jar files except standard jar and jstl jar from local jakarta tomcat 4 1 18 webapps ROOT WEB INF ib I restarted Tomcat and ran IE again with url http localhost 8080 hello_jstl jsp I got the prefect message Hello w
64. alked about how to define an attribute in a custom tag how attribute values are passed to the tag class and how attribute values are converted to correct data type required by the tag class Now let s look at the possibility of entering expressions as attribute values in a custom tag similar to JSTL tags Based on my readings on the Internet expression language is not supported directly in custom tags in JSP 1 2 However there are two approaches to use expressions indirectly in custom tags 1 Using Java expression elements as attribute values You need to define the attribute in the TLD file with lt rtexprvalue gt true lt rtexprvalue gt then enter the attribute value with the following format lt hy tag att lt java_expression gt gt 2 Using JSTL expressions and evaluate them inside tag class You can enter a JSTL expression in an attribute value received it by the setter method as a string then evaluate it to the desire data type using the expression evaluation tool offer by the JSTL The first approach requires the JSP page to be written in a non XML format And I don t like that format So I am not going to try that The second approach seems to be interesting and powerful You can use it to pass an object of any class as an attribute value to the tag class See the example bellow Tag Attribute Value Expression Example AttObjectTag java The tag class AttObjectTag java Copyright c 2003 by Dr Herong
65. alues into the session object e Putting values into the application object e Putting values at the end of the redirect URL In the following example I have two JSP pages working together as a registration process Here is the fist JSP page RegForm jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt RegForm jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt jsp declaration gt lt CDATA 2 of 10 http www geocities com herong_yang jsp session html private String getItem String queryString String key String value null if queryString null int i queryString indexOf key if gt 1 i i key lengthQ int j queryString indexOf amp i if G gt 1 value queryString substring i j else value queryString substring i if value startsWith value value replaceFirst return value gt lt jsp declaration gt lt jsp scriptlet gt lt CDATA String lastUser String application getAttribute name if lastUser null lastUser Nobody application setAttribute name lastUser String queryString request getQueryString String submit getItem queryString submit if submit null amp amp submit equals Submit Collecting the input data session setAttribute name getItem queryString name session setAttr
66. ame gt lt br gt lt c out value 34 out class name gt lt br gt lt c out value 35 pageContext out class name gt lt br gt lt c out value 36 sessionScope now gt lt br gt lt jsp scriptlet gt session setAttribute now new java util Date lt jsp scriptlet gt lt c out value 37 sessionScope now time gt lt br gt lt body gt lt html gt lt jsp root gt 6 of 9 http www geocities com herong_yang jsp jstl_el html Here is the output this page But you read the output I want you take guess on the resulting values my expression examples would give and compare them with the output JSTL Expression Examples 1 true 2 2 3 0 3333333333333333 4 0 3333333333333333 5 false 6 Hi there 7 message 10 GET 11 12 GET 15 GET 16 GET 21 JSESSIONID 22 FAC70AB7F4107ES5EC81A14B 1C080FC79 23 javax servlet http Cookie 352d87 26 javax servlet http Cookie 352d87 30 31 32 org apache coyote tomcat4 CoyoteRequestFacade 33 34 35 org apache jasper runtime JspWriterImp1 37 1065795381165 Do you have any supprises when you compare your guess with output I have some explanations on the output to help you Example 3 shows you that the result of integer operations is not converted by to integer Example 5 confirms that null is converted to false Example 7 shows ycu that value will be converted back to an identifier variable name Examples
67. ang jsp tag_attribute html lt taglib gt The JSP page lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt lt AttObjectTagTest jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt Regular Strings lt p gt lt hy attObject booleanAtt true stringAtt Hello world gt lt p gt Literals lt p gt lt hy attObject booleanAtt false stringAtt Herong Yang gt lt p gt Expressions lt p gt lt hy attObject booleanAtt 1 1 stringAtt pageContext request method mapAtt cookie gt lt body gt lt html gt lt jsp root gt The output Regular Strings booleanAtt true booleanObject true stringAtt Hello world stringObject Hello world mapAtt null mapObject null Literals booleanAtt false booleanObject false stringAtt Herong Yang stringObject Herong Yang mapAtt null mapObject null 11 of 12 http www geocities com herong_yang jsp tag_attribute html Expressions booleanAtt 1 1 booleanObject true stringAtt pageContext request method stringObject GET mapAtt cookie mapObject size 0 Note that e The JSTL expression evaluation tool is a static method evaluate in ExpressionEvaluationManager clas
68. anguage supports 5 types of literal data e Boolean true and false Same as Java boolean 2 of 9 http www geocities com herong_yang jsp jstl_el html e Integer like 9999 3 and 0 Same as Java long e Floating point number like 1 0 3 14159 and 1 0e 3 Same as Java double e String like USA USA or Herong s notes Close to Java String e Null null Same as Java null The literal data rules are easy to understand with a couple of exceptions e No literal data for character data type e String can be quoted by single quote Named variables are coming from two sources e Variables defined by the JSTL set action e Variables provided as attributes in the pageContext object prepared by other server side codes like useBean and scriptlet JSP elements Variables provided as pageContext attributes will have their original Java types like int float char or Object But all JSTL operations will be carried out in one of the 5 types of literal data Operators of other types will be converted before the operation Type conversion rules nn e To string Using the Java rules except that null will be converted to e To boolean Using the Java rules except that null or will be converted to false e To integer Using the Java rules except that null or will be converted to 0 e To floating porint number Using the Java rules except that null or will be converted to 0 0 e To object Usin
69. assed as part of the redirect URL It will show up in the browser s URL area So you should not use this approach to pass sensitive information from one JSP page to another The application object is also used to pass name from RegForm jsp to RegDone jsp This copy of name is used as the last user on the server which is not session specific In general passing session specific data through the application object is not safe Different sessions could override each other When the browser is closed and started again a new session object is created but the application is still the same This is why you see Herong again as the last user on the server HTTP Communication Level Debugging If you have a problem with your JSP application at the HTTP communication level one good debugging tool is the Perl LWP package It can be used as a Web browser to talk to your JSP application and to log everything at the HTTP communication level Here is my sample Perl program reg_client pl designed to work with my previous JSP registration application reg_client pl Copyright c 2002 by Dr Herong Yang use LWP Debug qw 6 of 10 http www geocities com herong_yang jsp session html use LWP UserA gent use HTTP Cookies url ARGV url http localhost unless url ua new LWP UserAgent cookie_jar HTTP Cookies gt new amp getForm amp submitForm exit sub getForm u url RegForm jsp my
70. at4 CoyoteResponseFa javax servlet jsp jspRequest org apache coyote tomcat4 CoyoteRequestFaca javax servlet jsp jspConfig org apache catalina core StandardWrapperFaca javax servlet jsp jspPage org apache jsp JstlObjects_jsp 27538 javax servlet jsp jspPageContext org apache jasper runtime PageContextIm requestScope sessionScope applicationScope javax servlet context tempdir D local jakarta tomcat 4 1 18 work Standa org apache catalina WELCOME_FILES Ljava lang String 628b8d org apache catalina resources org apache naming resources ProxyDirContex org apache catalina jsp_classpath D local jakarta tomcat 4 1 18 webapp param paramValues header accept language en us connection Keep Alive 5 of 7 http www geocities com herong_yang jsp jstl_core html cookie JSESSIONID 8 1C98734DD4FOE3F75608D6E3B 1D83D0 accept host localhost 8080 user agent Mozilla 4 0 compatible MSIE 6 0 MSNIA Windows NT 5 0 Q31 headerValues accept language Ljava lang String 5dc721 connection Ljava lang String 3c59aa cookie Ljava lang String 22da07 accept Ljava lang String 180c26 host Ljava lang String 45bb9d user agent Ljava lang String 204425 cookie JSESSIONID javax servlet http Cookie 5al142f initParam Class path list C local jakarta tomcat 4 1 18 webapps ROOT WEB INF classes C local jakarta tomcat 4 1 18 webapps ROOT WEB INF lib jstl jar C local jakarta tomcat 4 1 18 webapps ROO
71. b PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by Dr Herong Yang gt lt taglib gt 3 of 8 http www geocities com herong_yang jsp tag_interface html lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt trace lt name gt lt tag class gt herong TraceTag lt tag class gt lt body content gt jsp lt body content gt lt attribute gt lt name gt myAtt lt name gt lt required gt false lt required gt lt attribute gt lt tag gt lt other tags gt lt taglib gt Since my trace tag will have body I set body content to jsp instead of empty The updated tld file was copied to local jakarta tomcat 4 1 18 webapps root web inf tlds directory To test my trace tag I wrote the following JSP page TraceTagTest jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt lt TraceTagTest jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt hy trace myAtt my value gt lt jsp text gt JSP body lt jsp text gt lt br gt lt hy trace gt lt body gt lt htm
72. cal language independent e How to enter non ASCII characters as static HTML text How static HTML text works in HTML pages How static HTML text works in JSP pages with standard syntax e How static HTML text works in JSP pages with XML syntax e How to supporting characters from multiple languages For more notes on non ASCII codes and Java program localization see my other books Herong s Notes on Unicode and Herong s Notes on JDK Characters Traveling from JSP Files to Browser Screens Handling non ASCII characters in JSP files correctly is not an easy task I have seen many messages on the Wep in this area reporting various frustrating situations One main reason is that text entered in a JSP file must travel through many steps before being displayed by a browser on a screen The following diagram illustrates steps that characters must travel from a JSP file to a browser screen and computing technologies that are used at different steps 0 Key Sequences from Keyboard l l Text Editor v 1 JSP File l XML Parser v 1 of 13 http www geocities com herong_yang jsp non_ascii html 2 Java Source File Java Compiler v 3 Java Class File l Java Virtual Machine v 4 HTML Document l Web Server v 5 HTTP Response l Internet TCP IP Connection v 6 HTTP Response l Web Browser v 7 Characters on the Screen Since all computing technologies are using ASCII encoding by default text of ASCII char
73. cat as a Web Server To find out where it document root directory of this Web server let s create hello html lt html gt lt body gt Hello world lt body gt lt html gt Then save hello html to local jakarta tomcat 4 1 18 webapps ROOT Now run IE with url http Aocalhost 8080 hello html You should see Hello world in the IE window Now we know that the Web server Listening on port 8080 Serving document from local jakarta tomcat 4 1 18 webapps ROOT To change the port number you need to edit local jakarta tomcat 4 1 18 conf server xml Hello world Example To verify if Tomcat supports JSP or not let s create hello jsp lt html gt lt body gt lt out println Hello world gt lt body gt lt html gt Then save hello jsp to local jakarta tomcat 4 1 18 webapps ROOT Now ran IE with url http Nocalhost 8080 hello jsp You should see Hello world in the IE window Congratulations I have successfully served an JSP page through Tomcat Dr Herong Yang updated in 2002 Home Help TOC Herong s Notes on JSP Tomcat 2 of 2 http www geocities com herong_yang jsp jsp html Herong s Notes on JSP Dr Herong Yang Version 3 03 2002 Home Help TOC JavaServer Pages JSP What is JSP JSP is a technology not a language It allows Web page authors to put dynamic data into a Web document with Java statements embedded in special HTML tags The embedded Java statements will be execu
74. concept of linking multiple trips of requests and response into a single process unit application A ServletContext object representing the concept of grouping Servlets into a single application e config A ServletConfig object e pageContext A PageContext object The following JSP page will show you more details about those pre defined objects lt ContextInfo jsp Copyright c 2002 by Dr Herong Yang All rights reserved gt lt html gt lt body gt lt p gt lt b gt JSP Page Context Information lt b gt lt br gt lt p gt lt p gt lt b gt Pre defined objects lt b gt lt br gt lt out println out out getClass getName lt br gt out println this this getClass getName lt br gt out println request request getClass getName lt br gt out println response response getClass getName lt br gt 1 of 6 http www geocities com herong_yang jsp context html out printIn session session getClass getName lt br gt out println application application getClass getName lt br gt out println config config getClass getName lt br gt out println pageContext pageContext getClass getName lt br gt P gt lt p gt lt p gt lt b gt Information about session lt b gt lt br gt lt i gt pageContext getSession lt i gt lt br gt lt out printIn Class Name session getClass getName
75. e Thank you registrating with us Login Name Herong Password Secret Favor Color Red Your session ID is 2B20E475CA7BOFFC4C2E752ABF24C772 Last user on the server Herong Then close your browser and start it again with RegForm jsp you will get Registration Form Login Name 5 of 10 http www geocities com herong_yang jsp session html Password Favor Color Your session ID is A497631211582DE3799223EEF3 1 BCF4F Last user on the server Herong A number of interesting notes RegForm jsp page is designed to serve two functions presenting the form and collecting data from the submitted form When RegForm jsp is requested for the first time there will be no submit in the query string So the JSP code will continue with the presenting form section When the user finishes filling in the form and clicks the Submit button the browser will request RegForm jsp again and attach all the data in the form as the query string This behavior is specified by the lt form gt tag When RegForm jsp is requested by the Submit button submit will have Submit as its value So the JSP code will continue with the collecting data section In the collecting data section I want to pass the collected data to another JSP page RegDone jsp Here I use two approaches to pass data to RegDone jsp name and pass are passed through the session object This is probably the best approach to pass data from one JSP page to another color is p
76. e in milliseconds into pageContext as an attribute with a given name Once the data is stored in pageContext any other tags can come and retrieve it SetTimeTag java Copyright c 2003 by Dr Herong Yang All rights reserved package herong import javax servlet jsp tagext public class SetTimeTag extends TagSupport private String var null public void setVar String v this var v public int doStartTagQ Long now new Long System currentTimeMillis pageContext setAttribute var now return SKIP_BODY The TLD file lt xml version 1 0 gt lt DOCTYPE taglib PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by Dr Herong Yang gt lt taglib gt lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt setTime lt name gt lt tag class gt herong SetTimeTag lt tag class gt lt body content gt empty lt body content gt lt attribute gt lt name gt var lt name gt lt required gt true lt required gt lt attribute gt 4 of 6 http www geocities com herong_yang jsp tag_parent html lt tag gt lt other tags gt lt taglib gt Here is the testing page lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP P
77. e name extensions 1 Command java HttpRequestGet hello html 8080 gives us HTTP 1 1 200 OK ETag W 38 1047477954000 Last Modified Sat 22 Mar 2003 14 05 54 GMT Content Type text html Content Length 38 Date Sun 23 Mar 2003 02 59 32 GMT Server Apache Coyote 1 0 Connection close Hello world Couple of interesting notes here e Content Type was set to text html because the file name extension was html e The request was marked as HTTP 1 0 in HttpRequestGet but Tomcat responded with a higher version HTTP 1 1 e also tried to use HTTP 1 1 in my request but Tomcat returned with an error Why Tomcat could not support HTTP 1 1 request 2 Command java HttpRequestGet dot gif 8080 gives us HTTP 1 1 200 OK ETag W 43 1029361700000 Last Modified Sun 11 Aug 2002 21 48 20 GMT Content Type image gif Content Length 43 Date Sun 23 Mar 2003 03 14 22 GMT Server Apache Coyote 1 0 Connection close As you can see Content_Type was set correctly to image gif for file name extension gif as defined in the MIME settings I could not included the entity body here because it contains binary data 3 Command java HttpRequestGet hello pdf 8080 gives us HTTP 1 1 200 OK 5 of 14 http www geocities com herong_yang jsp response_header html ETag W 909 1059340932000 Last Modified Sun 17 Mar 2003 21 22 12 GMT Content Type application pdf Content Length 909 Date Sat 23 Mar 200
78. e one to be used by the setProperty action element o If there is only one set method the input parameter type should be a primitive type 5 of 12 http www geocities com herong_yang jsp usebean html e The get method name must be the property name with the first lower case letter being translated to upper case and prefixed with get For example getAuthor is a good method name to support the getProperty action element for property name author e The get method should take no input parameter e The return type of the get method can be String or any primitive type e JavaBean proproty names must be started with a lower case letter To validate the above rules I wrote the following sample JavaBean class DemoBean java Copyright c 2003 by Dr Herong Yang All rights reserved package herong public class DemoBean private String author Herong private int count 0 private boolean status true private String total 1 private String size 2 public void setAuthor String a author a public String getAuthor return author public void setCount int c count C public int getCount return count public void setStatus boolean s status s public boolean getStatus return status public void setTotal int t total int t public void setTotal double t total double t 6 of 12 http www geocities com herong_yang js
79. eader Lines of Static Files Response Header Lines Affected by jsp directive page Elements Setting Header Lines Directly in JSP Pages e Generating Non HTML Entity Body e JE 6 0 Bug on Display PDF Data Localization Internationalization Non ASCII Characters in JSP Pages e Characters Traveling from JSP Files to Browser Screens e ASCII Characters in JSP Pages e Presenting Non ASCII Characters in HTML Documents e Entering Non ASCII Characters in Java Strings e Java Strings Byte Sequences Encoded for Local Languages e Java Strings Unicode Codes Local Language Independent e Entering Non ASCII Characters as Static HTML Text e Static HTML Text HTML Page 2 of 4 9 7 2004 3 17 PM e Static HTML Text JSP Page in Standard Syntax e Static HTML Text JSP Page in XML Syntax e Supporting Characters from Multiple Languages JSP Performance e Calculating Prime Numbers e Response Time of Hello Page JSP Standard Tag Libraries JSTL e What is JSTL e Installing JSTL 1 0 Implementation Standard Taglib 1 0 4 e Hello world with JSTL e JSTL in XML Style JSP Pages e JSTL Requirements JSTL Syntax and Expression Language e JSTL Syntax e Expression Language e Literal Data and Named Variables e Basic Operators and Operations e Implicit Objects e Accessing Collection Elements and Object Properties e ExpExample jsp Expression Example Page e pageContext Attributes and JSTL Top Level Identifiers JSTL
80. ebean html Here is a sample page to show you how to use a JavaBean as a Java object It is using the same JavaBean class herong DemoBean as the previous section lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt BeanAsObject jsp Copyright c 2003 by Dr Herong Yang gt lt html gt lt body gt lt jsp useBean id b class herong DemoBean gt lt jsp setProperty name b property author value Someone gt Line 11 author lt jsp expression gt b getAuthor lt jsp expression gt lt br gt lt jsp scriptlet gt lt CDATA b setTotal 10 gt lt jsp scriptlet gt Line 12 total lt jsp getProperty name b property total gt lt br gt lt jsp scriptlet gt lt CDATA b setSize 15 gt lt jsp scriptlet gt Line 13 size lt jsp getProperty name b property size gt lt br gt Line 14 size lt jsp scriptlet gt lt CDATA out printIn b getSize gt lt jsp scriptlet gt lt br gt lt jsp scriptlet gt lt CDATA Object o pageContext findAttribute b String s herong DemoBean o getSizeQ out printIn Line 15 size s gt lt jsp scriptlet gt lt br gt lt body gt lt html gt lt jsp root gt Open this JSP page with IE you will get Line 11 author Someone Line 12 total int 10 Line 13 size int 15 Line 14 size int 15 Line 15 size int 15 Note that e Line 11 tells us that we ca
81. ements jsp useBean A JSP action element that loads a JavaBean object into the JSP page lt jsp useBean id object_name class class_name gt where object_name is the name of the object to be created and class_name is the class name of the JavaBean class from which the object will be instantiated Once a bean object is loaded into the page you can use two other action elements to manipulate it lt jsp setProperty name obj property prop_name value prop_value gt lt jsp getProperty name obj property prop_name gt The setProperty action will set a new value to the specified property of the specified bean object The getProperty action will get the current value of the specified property of the specified bean object This value will be converted into a string Once a bean object is loaded into the page it can be used in other scripting elements in the same JSP page Here is my first JavaBean CacheBean java CacheBean java Copyright c 2002 by Dr Herong Yang All rights reserved 1 of 12 http www geocities com herong_yang jsp usebean html public class CacheBean private String text null public String getText return text public void setText String text this text text public String getInfo return My JavaBean Version 1 00 Here is a simple JSP page to show you how to use JavaBean UseBean jsp lt xml version 1 0 gt lt jsp root xmlns jsp
82. er req is used to add the cookies received from the previous response to the current request One of the cookies is the session id which is important for the JSP server to recognize the current request is a continuation of the previous request If you run it with reg_client p http localhost 8080 gt client out in a command window you will get the following in the window LWP UserA gent new LWP UserA gent request LWP UserAgent simple_request GET http localhost 8080 RegForm jsp LWP UserAgent _need_proxy Not proxied LWP Protocol http request LWP Protocol http request GET RegForm jsp HTTP 1 0 Host localhost 8080 User Agent libwww perl 5 51 LWP Protocol http request reading response LWP Protocol http request HTTP 1 1 200 OK Set Cookie JSESSIONID 887896C93 DFFF372EB388 1 8BF9F68DB2 Path Content Type text html charset UTF 8 Content Length 393 Date Sat 28 Dec 2002 20 37 04 GMT Server Apache Coyote 1 0 Connection close lt html gt lt body gt lt b gt Registration Form lt b gt lt br gt lt form action RegForm jsp met hod get gt Login Name lt input type text size 16 name name gt lt br gt Password lt i nput type text size 16 name pass gt lt br gt Favor Color lt input type text siz e 16 name color gt lt br gt lt input type submit name submit value Submit gt lt br gt lt form gt Your session ID is 887896C93DFFF372EB388 1 8BF9F68DB2 lt br gt Last us er on the s
83. ere is a sample code to show you that you can mix variables and pageContext attributes any way you want lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt ExpVariable jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt c set var message value Hi there gt lt c out value 1 message gt lt br gt 2 lt jsp expression gt pageContext findAttribute message lt jsp expression gt lt br gt lt jsp scriptlet gt lt CDATA String s Hello world pageContext setAttribute hello s PageContext PAGE_SCOPE gt lt jsp scriptlet gt lt c out value 3 hello gt lt br gt lt jsp useBean id today class java util Date gt lt c out value 4 today gt lt br gt lt jsp scriptlet gt lt CDATA java util Date d new java util Date 8 of 9 http www geocities com herong_yang jsp jstl_el html d setTime d getTime 24 60 60 1000 pageContext setAttribute tomorrow d PageContext PAGE_SCOPE gt lt jsp scriptlet gt lt c out value 5 tomorrow gt lt br gt lt jsp setProperty name today property time value 1000000000000 gt lt c out value 6 today gt lt br gt lt c out value 7 today time gt lt br gt lt body gt lt html gt lt jsp root gt Here is the output this p
84. erver But a better way to force the server to use the new versions is to use the Tomcat Manger tool Here is how to do this 1 Set up a manager user name and password by adding the following line to local jakarta tomcat 4 1 18 conf tomcat users xml lt user username herong password yang roles manager gt 2 Shut down and re start Tomcat server 3 Request UseBean jsp with IE 4 Modify CacheBean java compile it and copy the class file the web inf classes 5 Run the reload command with IE at http localhost 8080 manager reload path You need enter user name and password created in step 1 6 Request UseBean jsp again You should see the changes made to CacheBean java in step 4 Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP Using JavaBean Classes 11 of 12 http www geocities com herong_yang jsp usebean html 12 of 12 http www geocities com herong_yang jsp cookie html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC Using Cookies What is a Cookie Cookie A small amount of information sent by a Web server to a Web browser saved by the browser and sent back to the server later Cookies are transmitted inside the HTTP header Cookies move from server to browser and back to server as follows Web Web Local Web Web Server Browser System Browser Server Send Receive Save Send back Receive cookies gt cookies gt cookies
85. erver Nobody lt br gt lt body gt lt html gt LWP Protocol http request HTTP 1 1 200 OK LWP Protocol collect read 393 bytes LWP UserAgent request Simple response OK HTTP Cookies extract_cookies Set cookie JSESSIONID gt 887896C93DFFF 372EB388 18BF9F68DB2 HTTP Cookies add_cookie_header Checking localhost local for cookies 8 of 10 http www geocities com herong_yang jsp session html HTTP Cookies add_cookie_header checking cookie path HTTP Cookies add_cookie_header checking cookie JSESSIONID 887896 C93 DFFF372EB388 1 8BF9F68DB2 HTTP Cookies add_cookie_header it s a match HTTP Cookies add_cookie_header Checking local for cookies LWP UserA gent request LWP UserAgent simple_request GET http localhost 8080 RegForm jsp name Mike amp pass None amp color Blue amp submit Submit LWP UserAgent _need_proxy Not proxied LWP Protocol http request LWP Protocol http request GET RegForm jsp name Mike amp pass None amp col or Blue amp submit Submit HTTP 1 0 Host localhost 8080 User Agent libwww perl 5 51 Cookie JSESSIONID 887896C93 DFFF372EB388 8BF9F68DB2 Cookie2 Version 1 LWP Protocol http request reading response LWP Protocol http request HTTP 1 1 302 Moved Temporarily Location http localhost 8080 RegDone jsp color Blue Content Type text html charset UTF 8 Content Length 0 Date Sat 28 Dec 2002 20 37 04 GMT Server Apache Coyote 1 0 Connection c
86. ff http java sun com webservices docs 1 0 tutorial doc JSTL html 74644 Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP References 1 of 1
87. formation and methods common to all JSP pages running under one session The session object must be an instance of a class that implements the javax servlet http HttpSession interface defined by the J2EE specification Here is the highlights of the HttpSession interface defined in J2EE 1 3 e getAttribute Returns the object that is associated to the specified key string defined in the session getAttributeNames Returns an Enumeration object that contains all the key strings defined in the session getCreationTime Returns the time when this session was created measured in milliseconds since midnight January 1 1970 GMT getId Returns the session ID as a string getLastAccessedTime Returns the last time the client sent a request associated with this session as the number of milliseconds since midnight January 1 1970 GMT e getMaxInactivelInterval Returns the maximum time interval in seconds that the servlet container will keep this session open between client accesses removeAttribute Removes the object associated with the specified key string from this session setAttribute Associate an object with the specified key string and store them to this session e setMaxInactiveInterval Specifies the time in seconds between client requests before the servlet container will invalidate this session Passing Values between Pages There are many ways to pass values from one pages to the next pages e Putting v
88. g The steps used by the JSP tag extension facility to process a custom tag can be summarized as follows e Instanciating the tag object e Calling setPageContext and setParent of the tag object e Processing attributes of the tag See my other notes on how attribute values are passed to the tag object 1 of 8 http www geocities com herong_yang jsp tag_interface html e Calling doStartTag of the tag object which may return a flag to request for skipping the body to perform a conditional body logic e Processing the body of the tag e Calling doAfterBody of the tag object which may return a flag to request for processing the body again to perform a loop logic on the body e Calling doEndTag of the tag object e Calling release of the tag object Implenting BodyTag Interface TraceTag java In order to confirm my understanding of the IterationTag interface I wrote the following tag class to print a short message from each implemented method to show when it is called I also used a very simple logic in doAfterTag to force the tag body being evaluated twice TraceTag java Copyright c 2003 by Dr Herong Yang All rights reserved package herong import java io import javax servlet jsp import javax servlet jsp tagext public class TraceTag implements IterationTag private boolean stop false private PageContext pc null private Tag t null public void setPageContext PageCo
89. g non ASCII characters in HTML documents steps 4 5 6 and 7 Let s look at the second part first to see how non ASCII characters are stored in HTML documents transferred from Web servers to browsers displayed on the screen Here are some basic rules related to these steps e Non ASCII characters must be encoded in a particular encoding schema like GB2312 Shift JIS or UTF 8 e You only use a single encoding schema in one HTML document The encoding schema name should be given in a meta tag as the charset value For examples see my sample HTML document in this section Non ASCII characters can be transferred safely from Web servers to browsers e The browser must decode HTML documents based on the schema name given in the documents auto mode or set by the browser user manual mode e Once non ASCII characters are decoded correctly the browser must be provided with font files that match the character set in which those non ASCII characters are defined In order to test these rules I translated my HelpASCILhtml to Chinese with GB2312 encoding schema and saved in a file called HelpGB2312 html lt html gt lt HelpGB2312 html Copyright c 2002 by Dr Herong Yang gt lt meta http equiv Content Type content text html charset gb2312 gt lt body gt lt b gt lt b gt lt br gt 3 of 13 http www geocities com herong_yang jsp non_ascii html lt p gt lt p gt lt body gt lt html
90. g the Java rules except that nn will be converted to null Basic Operators and Operations JSTL supports all logical relational and arithmetic operators supported in Java with exceptions e eq ne It gt le and ge could be used as relational operators e and or and not could be used as logical operators Implicit Objects JSTL has a set of predefined objects accessible by the following variable names e pageContext the PageContext object e pageScope a Map that maps page scoped attribute names to their values e requestScope a Map that maps request scoped attribute names to their values e sessionScope a Map that maps session scoped attribute names to their values 3 of 9 http www geocities com herong_yang jsp jstl_el html e applicationScope a Map that maps application scoped attribute names to their values e param a Map that maps parameter names to a single String parameter value obtained by calling ServletRequest getParameter String e paramValues a Map that maps parameter names to a String of all values for that parameter obtained by calling ServletRequest getParameterValues String e header a Map that maps header names to a single String header value obtained by calling ServletRequest getheader String e headerValues a Map that maps header names to a String of all values for that parameter obtained by calling ServletRequest getHeaders String e cookie a Map
91. gt 0 numberOfTests Integer valueOf args 0 intValueQ long t1 System currentTimeMillisQ String result for int nTest 1 nTest lt numberOfTests nTest result test args long t2 System currentTimeMillisQ long t t2 tl PrintStream out System out out printIn Performace Information out printIn Number of tests numberOfTests out printIn Time t 1000 seconds out printIn Rerulst of Last Test out println result public static String test String args String path index html int port 80 String host localhost if args length gt 1 path args 1 if args length gt 2 port Integer valueOf args 2 intValueQ if args length gt 3 host args 3 min String result try Socket c new Socket host port BufferedWriter w new BufferedWriter new OutputStream Writer c getOutputStream BufferedReader r new BufferedReader new InputStreamReader c getInputS tream String m GET path w write m 0 m length w newLine w flushQ 3 of 5 http www geocities com herong_yang jsp performance html while m r readLine null result result m n w close r close c close catch IOException e System err printIn e toString return result Now compile this program and try it with the following Hello JSP page hello jsp lt html gt lt body gt lt out printIn
92. gt lt br gt Cookie cookies request getCookies intn 0 if cookies null n cookies length for int i 0 i lt cookies length i out printIn Name cookies i getName lt br gt out printin Value cookies i getValueQ lt br gt out printIn Domain cookies i getDomain lt br gt out println Path cookies i getPath lt br gt out println MaxAge cookies i getMaxAge lt br gt out printIn Version cookies i get Version lt br gt gt lt jsp scriptlet gt lt p gt lt body gt lt html gt lt jsp root gt So I opened this page with IE and got Cookie with default properties Name Date Value 30 Mar 2003 4 of 6 http www geocities com herong_yang jsp cookie html Domain null Path null MaxAge 1 Version 0 Cookie with specified properties Name User Value Herong Yang Domain null Path null MaxAge 259200 Version 0 Properties of the received cookies Then I clicked at IE Tools menu selected Internet Options and clicked the Settings button in the Temporary Internet files section of the General tab I saw where is my Temporary Internet files folder So I went to that folder and saw a cookie file named something like Cookie user localhost jsp I double clicked on that file and was able to open it in notepad User Herong Yang localhost jsp 1024 2353942784 29567146 224352272 2956654
93. he class path into multiple items lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt JstLObjects jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt Browsing all the JSTL implicit objects lt p gt lt p gt pageContext lt p gt lt c out value pageContext gt lt br gt lt p gt pageScope lt p gt lt c forEach items pageScope var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt requestScope lt p gt lt c forEach items requestScope var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt sessionScope lt p gt 3 of 7 http www geocities com herong_yang jsp jstl_core html lt c forEach items sessionScope var entry gt lt c out value entry gt lt br gt lt c forEach gt lt p gt applicationScope lt p gt lt c forEach items applicationScope var entry gt lt c out value entry gt lt br gt lt c for Each gt lt p gt param lt p gt lt c forEach items param var entry gt lt c out value entry gt lt br gt lt c for Each gt lt p gt paramValues lt p gt lt c forEach items paramValues var entry gt lt c out value entry gt lt br gt lt c for
94. ibute Here is the steps you need to follow to add an attribute to a custom tag 1 Define a property in the tag class with the same name as the attribute name by adding a setter method and a getter method This is the same way as defining a property in a JavaBean class 2 Add an attribute element inside the tag element in your TLD file with the following syntax lt tag gt lt name gt tag_name lt name gt lt tag class gt class_full_name lt tag class gt lt body content gt empty jsp lt body content gt lt attribute gt lt name gt attribute_name lt name gt lt required gt true false lt required gt lt attribute gt lt tag gt 3 Add the attribute to the custom tag in your JSP page Then the tag is processed the setter method of the tag object will be called to pass the attribute value into the tag object Tag Attribute Setter Method Example EchoTag java To show you how to use attributes in a custom tag I wrote the following example tag EchoTag java It does nothing but takes the value of the message attribute and echoes back to the page output with characters reversed EchoTag java Copyright c 2003 by Dr Herong Yang All rights reserved 1 of 12 http www geocities com herong_yang jsp tag_attribute html package herong import java io import javax servlet jsp tagext public class EchoTag extends TagSupport private String message null public void setMessage String m
95. ibute pass getItem queryString pass application setAttribute name getItem queryString name response sendRedirect RegDone jsp color getItem queryString color else Presenting the registration form out print lt html gt lt body gt out print lt b gt Registration Form lt b gt lt br gt out print lt form action RegForm jsp method get gt out print Login Name out print lt input type text size 16 name name gt lt br gt out print Password out print lt input type text size 16 name pass gt lt br gt 3 of 10 http www geocities com herong_yang jsp session html out print Favor Color out print lt input type text size 16 name color gt lt br gt out print lt input type submit name submit value Submit gt lt br gt out print lt form gt out print Your session ID is session getIdQ lt br gt out print Last user on the server lastUser lt br gt out print lt body gt lt html gt gt lt jsp scriptlet gt lt jsp root gt Here is the second JSP page RegDone jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt RegDone jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt jsp declaration gt lt CDATA private String getItem String queryString String key String value null if queryString null int i
96. ing all 3 of 14 http www geocities com herong_yang jsp response_header html header lines received from a Web server HttpRequestGet java Copyright c 2002 by Dr Herong Yang All rights reserved import java io import java net public class HttpRequestGet public static void main String args String path index html int port 80 String host localhost if args length gt 0 path args 0 if args length gt 1 port Integer valueOf args 1 intValueQ if args length gt 2 host args 2 win String result try Socket c new Socket host port BufferedWriter w new BufferedWriter new OutputStream Writer c getOutputStream BufferedReader r new BufferedReader new InputStreamReader c getInputS tream String m GET path HTTP 1 0 w write m 0 m length w newLine w newLine w flushQ while m r readLine null System out println m w close r close c close catch IOException e System err printIn e toString Response Header Lines of Static Files Static files can be served directly by Tomcat server if you copy the files to 4 of 14 http www geocities com herong_yang jsp response_header html local jakarta tomcat 4 1 18 webapps ROOT Tomcat server will set Content_Type header line based on the file name extension and the MIME settings of the server configuration Let s look at 3 commonly used fil
97. ishing this trace tag example I had a very good understanding of how the tag interface offered by the extension facility works now How about you Dummy Implementation of IterationTag Interface TagSupport Class J2EE supplied a dummy implementation called TagSupport to the IterationTag interface If you are design a new tag class you may extend your class from TagSupport instead of 7 of 8 http www geocities com herong_yang jsp tag_interface html implement InterationTag Extending your tag class from TagSupport gives you two advantages 1 Need to code any required method if you are happy with the implementation of that method inside TagSupport 2 TagSupport provides you the pageContext object ready to use No need for you to code setPageContext and save it in your tag object Examples of using TagSupport will be include in my other notes on custom tags Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP JSP Tag Java Interface 8 of 8 http www geocities com herong_yang jsp tag_attribute html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC JSP Tag Attribute Handling Tag Attribute Setter Method The JSP tag extension facility maps each attribute encountered in a custom tag to an property of the same name of the tag object So if you want to use an attribute in a custom tag you must define a property in the tag class with the same name as the attr
98. jsp scriptlet gt lt body gt lt html gt lt jsp root gt There is another problem with the XML format of JSP pages The problem is caused by the XML requirement that the entire file must be well formed This is a tough requirement for the embedded Java statements because of the lt operator and other special operators So we need to use the lt CDATAJ gt to protect the Java statements Here is an example LoopTest jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt LoopTest jsp Copyright c 2002 by Dr Herong Yang All rights reserved gt lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt lt jsp scriptlet gt lt CDATA out printIn lt b gt Sum of 1 2 10 lt b gt lt br gt int sum 0 for int i 0 1 lt 10 i sum i out printIn sum gt lt jsp scriptlet gt lt p gt lt body gt lt html gt lt jsp root gt If you open this page with IE you should have no problem to get the result Directive Elements The most commonly used directive is probably the page directive which specifies page level properties for the JSP server Here is some examples lt jsp directive page import java util gt lt jsp directive page import java net session false gt lt jsp directive page contentType text html gt 3 of 9 http www geocities com herong_yang jsp e
99. l be converted into a string which will be inserted into the HTTP response The c out action serves similar purposes as the JSP expression element c set Action lt c set var name value expression gt The var attribute apecifies a variable name which will be declared and assigned with the value resulted from the value attribute The c set action serves similar purposes as the Java assignement statement c if Action 1 of 7 http www geocities com herong_yang jsp jstl_core html lt c if test expression gt body lt c if gt If the test attribute is evaluated to true body will be processed The c if action serves similar purposes as the Java if statement c choose Action lt c choose gt lt c when test expression gt body lt c when gt lt c when test expression gt body lt c when gt lt c otherwise gt body lt c otherwise gt lt c choose gt The body of the first c when action that has the test attribute evaluated to true will be processed If all test attributes are evaluated to false the body of the c otherwise action will be processed The c choose action serves similar purposes as the Java if else statment c forEach Action lt c forEach var name items expression begin expression end expression step expression gt body lt c forEach gt If the items attribute is specified it will be used to identify an array or collection object the elements in the ar
100. l gt lt jsp root gt Note that I did not use jsp directive page to import my trace tag class because the class in now under herong package I put the JSP page on my tomcat server and restarted the server When requesting this JSP page with IE I got the following output setPageContext called setParent called setMyAtt called 4 of 8 http www geocities com herong_yang jsp tag_interface html doStartTag called JSP body doAfterBody called JSP body doAfterBody called doEndTag called The output was exactly what I expected The JSP was indeed evaluated twice as controlled by the returning flag of doAfterBody One surpprise is that there was no call to release I don t know why The Servlet Class TraceTagTest_jsp java As we all know that JSP pages are translated into Servlet classes before execution So we actually review the translate Servlet class to see how the tag extension facility connects the Servlet class to the tag class To review the Servlet class translated from TraceTagTest jsp open TraceTagTest_jsp java in local jakarta tomcat 4 1 18 work standalone localhost _ you will see package org apache jsp import javax servlet import javax servlet http import javax servlet jsp import org apache jasper runtime public class TraceTagTest_jsp extends HttpJspBase private static java util Vector _jspx_includes private org apache jasper runtime TagHandlerPool _jspx
101. lement html Note that e All directive attributes are optional e import tells the JSP server to insert import statements into the Servlet class e session tells the JSP server to execute the Servlet with a session or without a session The default value is true contentType tells the JSP server to set content type of HTTP response with the specified value Another commonly used directive is the include directive which tells the ASP server to include the specified JSP page into the current JSP page before translation lt jsp directive include file header jsp gt lt jsp directive include file footer jsp gt Action Elements The most commonly used action is probably the include action which tells the ASP server to execute the specified JSP page and include the output into the current JSP page lt jsp include page CurrentMonthCalendar jsp gt Another commonly used action is the useBean action which loads a JavaBean object into the JSP page lt jsp useBean id object_name class class_name gt JSP Example CurrentTime jsp The following example has three JSP files working together to show you how to use decalaration elements include directive elements and include action elements Here is the main JSP file CurrentTime jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt CurrentTime jsp Copyright c 2002 by Dr Herong Yang
102. let and JavaServer Pages technologies developed under the Jakarta project at the Apache Software Foundation Tomcat 4 1 18 is a web server and supports Servlet 2 3 and JSP 1 2 It requires JDK 1 2 or later I did the following to get Tomcat 4 1 18 installed 1 Checked JDK requirement I had JDK 1 3 1 installed on local jdk1 3 1 2 Downloaded tomcat 4 1 18 zip from http www apache inetcosmos org dist jakarta tomcat 4 binaries 3 Unziped tomcat 4 1 18 zip in local 4 Started Tomcat server cd local jakarta tomcat 4 1 18 bin set JAVA_HOME local jdk1 3 1 startup 5 Tomcat created a separate command window on which I got INFO Registry Loading registry information INFO Registry Creating new Registry instance INFO Registry Creating MBeanServer INFO Http11Protocol Initializing Coyote HTTP 1 1 on port 8080 Starting service Tomcat Standalone Apache Tomcat 4 1 18 INFO Http11Protocol Starting Coyote HTTP 1 1 on port 8080 INFO ChannelSocket JK2 ajp13 listening on 0 0 0 0 0 0 0 0 8009 INFO JkMain Jk running ID 0 time 30 130 config C ocal jakarta tomcat 4 1 18 bin conf jk2 properties 6 Ran Internet Explorer IE with url http localhost 8080 I got the Tomcat home page with the following message on it 1 of 2 http www geocities com herong_yang jsp tomcat html If you re seeing this page via a web browser it means you ve setup Tomcat successfully Congratulations Using Tom
103. line 8 in the jsp file UseBean jsp Generated servlet error javac Compiling 1 source file Cxocal jakarta tomcat 4 1 18 work Standalone localhost _ UseBean_jsp java 7 expected import CacheBean This is because JDK 1 4 1 does not allow import statement to be used on classes in unnamed packages any more For more detail information please see section Tomcat 4 1 18 with JDK 1 4 1 in this book Setting and Getting JavaBeans Properties As you can see from previous sections a JavaBean is just a regular Java obect Once a JavaBean is created in a JSP you can use JSP setProperty and getProperty action elements to set and retrieve values of its properties To support these action elements a JavaBean class must implement set and get methods based on some rules In this section let s look at some of the basic rules about setting and getting JavaBean properties e The setProperty element must be supported by at least one set method in the JavaBean class The set method name must be the property name with the first lower case letter being translated to upper case and prefixed with set For example setAuthor is a good method name to support the setProperty action element for property name author The return type of the set method should be void e The set method should take only one input parameter e If there are multiple set methods there must be one that takes String as the input parameter type and this will be th
104. lo_xml_html jsp 8080 HTTP 1 1 200 OK Set Cookie JSESSIONID 4B6E955411EBC4536206978E3B498B50 Path Content Type text html charset UTF 8 Content Length 40 Date Sat 23 Mar 2003 22 11 40 GMT Server Apache Coyote 1 0 Connection close lt html gt lt body gt Hello world lt body gt lt html gt As you can see from the response the attribute contentType in the jsp directive page changed the Content_Type header line Note that the charset portion was not changed because no value was given in the contentType attribute Setting Header Lines Directly in JSP Pages The second way and third way to control the response header lines are related to the build in response object One is to use the specialized methods the other is to use the generic methods Let me use the following 2 examples to show you how those methods work The first example SetContentType jsp uses the special methods to set Content_Type and Content_Length header lines lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt SetContentType jsp Copyright c 2002 by Dr Herong Yang gt lt jsp scriptlet gt lt CDATA response setContentT ype text html String text lt html gt lt body gt Hello world lt body gt lt html gt response setContentLength text length out print text gt lt jsp scriptlet gt lt jsp root gt The response 8 of 14 http www geocities co
105. localization MIME named package online pageContext performance Perl Servlet session Taglib TagSupport tag interface TLD Tomcat tutorial unnamed package Unicode useBean UTF 8 XML Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP Table of Contents 4 of 4 9 7 2004 3 17 PM http www geocities com herong_yang jsp about html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC About This Book This book is a collection of notes and tutorial codes I wrote while I was leaning JSP JavaServer Pages Revision history Version 3 03 2003 Minor updates Version 3 00 2003 Added notes on JSTL tags and custom tags Version 2 00 2002 Reformatted in XHTML and PDF formats Version 1 00 2001 Started in text format Copyright e The notes and example codes are Copyright 2001 2003 by Dr Herong Yang All rights reserved e Using and distributing the notes and example codes are permitted as long as the above copyright notice is retained e The example codes is provided as is with no warranty of any kind Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP About This Book 1 of 1 http www geocities com herong_yang jsp tomcat html Herong s Notes on JSP Dr Herong Yang Version 3 03 2002 Home Help TOC Tomcat Installing Tomcat 4 1 18 Tomcat is a free open source implementation of Java Serv
106. longObject longObject lt br gt out printIn doubleValue doubleValue lt br gt out println doubleObject doubleObject lt br gt out printin boolean Value booleanValue lt br gt out println booleanObject booleanObject lt br gt out println stringObject stringObject lt br gt catch IOException e System err printIn e toString return SKIP_BODY The TLD file lt xml version 1 0 gt lt DOCTYPE taglib PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by Dr Herong Yang gt lt taglib gt lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt att Value lt name gt lt tag class gt herong AttValueTag lt tag class gt lt body content gt empty lt body content gt lt attribute gt lt name gt long Value lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt longObject lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt 5 of 12 http www geocities com herong_yang jsp tag_attribute html lt name gt doubleValue lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt doubleObject lt name g
107. lose LWP Protocol http request HTTP 1 1 302 Moved Temporarily LWP UserAgent request Simple response Found LWP UserA gent request LWP UserAgent simple_request GET http localhost 8080 RegDone jsp color Blue LWP UserAgent _need_proxy Not proxied LWP Protocol http request LWP Protocol http request GET RegDone jsp color Blue HTTP 1 0 Host localhost 8080 User Agent libwww perl 5 51 Cookie JSESSIONID 887896C93 DFFF372EB388 8BF9F68DB2 Cookie2 Version 1 LWP Protocol http request reading response LWP Protocol http request HTTP 1 1 200 OK Content Type text html Content Length 221 Date Sat 28 Dec 2002 20 37 04 GMT 9 of 10 http www geocities com herong_yang jsp session html Server Apache Coyote 1 0 Connection close LWP Protocol http request HTTP 1 1 200 OK LWP Protocol collect read 221 bytes LWP UserAgent request Simple response OK We have a lot of information here Let s analyze it quickly My first request was sent as GET RegForm jsp HTTP 1 0 The first response came back with a cookie as JSESSIONID 887896C93 DFFF372EB388 18BF9F68DB2 Apparently this is the session ID but encrypted My second request was sent as GET RegForm jsp name Mike HTTP 1 0 with two cookies The first cookie was the JSP server session ID The second cookie came from nowhere The second response was interesting It had code of 302 Moved Temporarily and a Location he
108. lue 7 message gt lt br gt lt c out value 10 pageContext request method gt lt br gt lt c out value 11 pageContext request method gt lt br gt lt c out value 12 pageContext request method gt lt br gt lt cout value 13 pageContext request method gt lt br gt lt cout value 14 pageContext request method gt lt br gt lt c out value 15 pageContext request method gt lt br gt lt c out value 16 pageContext request method gt lt br gt lt cout value 20 pageContext request cookies length gt lt br gt lt c out value 21 pageContext request cookies 0 name gt lt br gt lt c out value 22 pageContext request cookies 0 value gt lt br gt lt c out value 23 pageContext request cookies 0 gt lt br gt lt cout value 24 pageContext request cookies 0 gt lt br gt lt cout value 25 pageContext request cookies 0 name gt lt br gt lt c out value 26 pageContext request cookies 0 gt lt br gt lt jsp scriptlet gt double pi 3 14159 lt jsp scriptlet gt lt c out value 30 pi gt lt br gt lt jsp scriptlet gt double list new double 3 list 0 9 99 lt jsp scriptlet gt lt c out value 31 list 0 gt lt br gt lt c out value 32 pageContext request class name gt lt br gt lt c out value 33 pageContext request class n
109. ly once the tag is encountered At the end of the evaluation it checks its stop condition if stop is false it evaluates its body again This loop will be stopped only if stop is set to true during the body evaluation Here is the break tag BreakTag java BreakTag java Copyright c 2003 by Dr Herong Yang All rights reserved x package herong import herong import javax servlet jsp tagext public class BreakTag extends TagSupport private Tag parent null 1 of 6 http www geocities com herong_yang jsp tag_parent html public void setParent Tag t parent t public int doStartTag if parent null LoopTag grandParent LoopTag parent getParent if grandParent null grandParent stop true return SKIP_BODY The logic of the break tag is a little bit more complex To break the loop tag conditionally we are expecting an if tag will be nested inside the loop tag to control the condition and the break tag will be nested inside the if tag to break the loop So the break tag is actually nested 2 levels down inside the loop tag This is why I have to use parent getParent to get the grand parent to access the loop tag Here is the TLD file lt xml version 1 0 gt lt DOCTYPE taglib PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by D
110. m herong_yang jsp response_header html HTTP 1 1 200 OK Set Cookie JSESSIONID 1771F49508924D74AA8B29BB9AB770C8 Path Content Type text html Content Length 38 Date Tue 12 Aug 2003 23 05 34 GMT Server Apache Coyote 1 0 Connection close lt html gt lt body gt Hello world lt body gt lt html gt Note that the setContentType method overrides the Content_Type header line completely including the charset portion Here is another calling example response setContentT ype text html charset UTF 8 In the second example SetHeader jsp I was trying to use the generic methods to set various header lines lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt SetHeader jsp Copyright c 2002 by Dr Herong Yang gt lt jsp scriptlet gt lt CDATA response setHeader Content_Type text html response setIntHeader Content_Length 0 String text lt html gt lt body gt Hello world lt body gt lt html gt response setIntHeader Content_Length text lengthQ response setDateHeader Last Modified System currentTimeMillis response setHeader Author Herong Yang response addHeader Author Joe Wang out print text gt lt jsp scriptlet gt lt jsp root gt Here is the response HTTP 1 1 200 OK Set Cookie JSESSIONID 6C08 1 157BFD264C3222FB71728CO0B4C Path Content_Type text html Content_Length 38 Last Modified Sat
111. n out printIn s System getProperty s amp lt br gt 5 of 9 http www geocities com herong_yang jsp element html s os name out printIn s System getProperty s amp lt br gt s os version out printIn s System getProperty s amp lt br gt lt jsp scriptlet gt lt jsp root gt Here is the JSP file used by the include action element TimeStamp jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt TimeStamp jsp Copyright c 2002 by Dr Herong Yang gt lt b gt Current Time lt b gt lt jsp scriptlet gt java util Date d new java util Date out printIn d toString lt jsp scriptlet gt lt jsp root gt Here is what I got by requesting CurrentTime jsp from IE Current time in different time zones America New_ York 12 23 02 9 38 PM America Los_Angeles 12 23 02 6 38 PM Asia Shanghai 12 24 02 10 38 AM Europe Paris 12 24 02 3 38 AM Europe Moscow 12 24 02 5 38 AM Current JVM java vm name Java HotSpot TM Client VM java vm version 1 3 1_01 os name Windows 2000 os version 5 0 Current Time Mon Dec 23 21 38 10 EST 2002 It s very interesting to see the Servlet class translated from CurrentTime jsp package org apache jsp import javax servlet import javax servlet http import javax servlet jsp 6 of 9 http www geocities com herong_yang jsp element html import org apache jasper
112. n com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt JstIPrimeNumbers jsp It doesn t work can not change the index Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt Checking prime numbers lt p gt lt c set var upperLimit value 20 gt lt c forEach var i begin 3 end upperLimit gt lt c set var isPrime value true gt lt c forEach var j begin 2 end i 1 gt lt c if test 1 j 0 gt lt c set var isPrime value false gt lt We should break the loop here gt lt c if gt lt c forEach gt lt c choose gt lt c when test isPrime gt lt c out value i is a prime number gt lt br gt lt c when gt lt c otherwise gt lt c out value i is a not prime number gt lt br gt lt c otherwise gt lt c choose gt lt c for Each gt lt body gt lt html gt lt jsp root gt I am not showing you the output here But it is correct Trust me As you can see in the source code I am not breaking the loop on j when i has already been approved as a non prime number because I don t know how Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP JSTL Core Library 7 of 7 http www geocities com herong_yang jsp tag html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC JS
113. n null public void _jspService HttpServletRequest request HttpServletResponse response throws java io IOException ServletException JspFactory _jspxFactory null javax servlet jsp PageContext pageContext null JspWriter out null try 4 of 5 http www geocities com herong_yang jsp jsp html _jspxFactory JspFactory getDefaultFactory response setContentT ype text html charset ISO 8859 1 pageContext _jspxFactory getPageContext this request response null true 8192 true out pageContext getOut out write lt html gt out write lt body gt r n out printIn Hello world From Servlet out write r n out write lt body gt out write lt html gt catch Throwable t if out null amp amp out getBufferSize 0 out clearBuffer if pageContext null pageContext handlePageException t finally if _jspxFactory null _jspxFactory releasePageContext pageContext Compile this class with JDK 1 3 1 cd local jakarta tomcat 4 1 18 work standalone localhost _ set classpath common lib servlet jar set classpath classpath common lib servlet jar local jdk1 3 1 bin javac fake_jsp java Now run IE with url http localhost 8080 fake jsp Guess what you will get on the IE window The text from the fake jsp page or the output of fake_jsp java You should see the output of fake_jsp java Tomcat has been fooled by the file
114. n unnamed packages with Tomcat 4 1 18 and JDK 1 3 1 requires import directive elements in the JSP pages e There is no way to use JavaBean classes in unnamed packages with Tomcat 4 1 18 and JDK 1 4 1 e There is no problem using JavaBean classes in named packages with Tomcat 4 1 18 and JDK 1 4 1 Dr Herong Yang updated in 2003 Herong s Notes on JSP Tomcat 4 1 18 with JDK 1 4 1 5 of 5 Home Help TOC http www geocities com herong_yang jsp reference html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC References e JavaServer Pages Sun Mirosystems http java sun com products jsp JSR 000152 JavaServer PagesTM 2 0 Specification Sun Mirosystems http jcp org aboutJava communityprocess first jsr152 index2 html e JSR 000053 JavaTM Servlet 2 3 and JavaServer PagesTM 1 2 Specifications Java Community Process http www jcp org aboutJava communityprocess first jsr053 e Apache Jakarta Project Apache Software Foundation http jakarta apache org tomcat index html e Taglibs Apache Software Foundation http jakarta apache org taglibs index html o Servlets and JavaServer Pages JSP 1 0 A Tutorial Marty Hall 1999 http www apl jhu edu hall java Servlet Tutorial e JSR 000052 JavaServer PagesTM Standard Tag Library Specification Java Community Process http jcp org aboutJava communityprocess final jsr052 e JavaServer Pages Standard Tag Library Stephanie Bodo
115. n use an expression element to get the property value 9 of 12 http www geocities com herong_yang jsp usebean html e Line 12 tells us that if we use scriptlet element we can call a specific version of setTotal method Remember setProperty failed on total in the previous example e Line 15 tells us that we also retrieve the object back from pageContext because useBean element store the JavaBean object in pageContext Using Java Objects as JavaBeans Now we know that a JavaBean is just a normal Java object with some specially named methods and stored in pageContext s attribute collection We can use the useBean to create a JavaBean and use it any way we wanted The next question is can we create any object and put it into pageContext s attribute collection and use setProperty and getProperty elements The answer is yes Here is my sample JSP page to show you this lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt ObjectAsBean jsp Copyright c 2003 by Dr Herong Yang gt lt html gt lt body gt lt jsp scriptlet gt lt CDATA herong DemoBean b new herong DemoBean pageContext setAttribute b b PageContext PAGE_SCOPE b setAuthor Unknown b setTotal 9 99 gt lt jsp scriptlet gt Line 21 author lt jsp getProperty name b property author gt lt br gt Line 22 total lt jsp getProperty name b property total gt lt br gt lt jsp sc
116. names and time stamps When Tomcat receives a HTTP request for fake jsp it will look for fake_jsp class at the JSP Servlet directory Since fake_jsp class is there and has newer time stamp than fake jsp it will assume fake_jsp class is the latest class translated from fake jsp and execute it immediately Be aware that if you modify fake jsp and save it back The next time when Tomcat receives a request for fake jsp it will translate the new fake jsp and replace both fake_jsp java and fake_jsp class The original fake_jsp java will be gone Dr Herong Yang updated in 2002 Home Help TOC Herong s Notes on JSP JavaServer Pages JSP 5 of 5 http www geocities com herong_yang jsp context html Herong s Notes on JSP Dr Herong Yang Version 3 03 2002 Home Help TOC Execution Context Predefined Objects Now we know that the Java statements embedded in JSP pages will translated into _jspService method of a special Servlet class In that method there are a couple of pre defined objects ready for the embedded Java statements e out The output stream to collect dynamic data to be mixed into the final Web document e this The instance of the special Servlet class request An HttpServletRequest object representing the request received from the Web browser response An HttpServletResponse object representing the response to be delivered back to the Web browser session An HttpSession object representing the
117. nknown behavior 3 of 12 http www geocities com herong_yang jsp tag_attribute html Tag Attribute Value Type Conversion Example AttValueTag java Here is an example of to show you how JSP tag extension facility is converting the attribute values to the tag s setter methods required data types The tag class AttValueTag java Copyright c 2003 by Dr Herong Yang All rights reserved package herong import java io import javax servlet jsp import javax servlet jsp tagext public class AttValueTag extends TagSupport private long long Value 0 private Long longObject null private double doubleValue 0 0 private Double doubleObject null private boolean booleanValue true private Boolean booleanObject null private String stringObject null public void setLongValue long val long Value val public void setLongObject Long obj longObject obj public void setDoubleValue double val doubleValue val public void setDoubleObject Double obj doubleObject obj public void setBooleanValue boolean val booleanValue val public void setBooleanObject Boolean obj booleanObject obj public void setStringObject String obj stringObject obj 4 of 12 http www geocities com herong_yang jsp tag_attribute html public int doStartTagQ JspWriter out pageContext getOut try out println long Value longValue lt br gt out println
118. ntext pc this pc pe printIn setPageContext called public void setParent Tag t this t t printIn setParent called public Tag getParent println setParent called return t public void setMyAtt String v printIn setMyAttQ called public int doStartTagQ printIn doStartTagQ called return EVAL_BODY_INCLUDE 2 of 8 http www geocities com herong_yang jsp tag_interface html public int doAfterBody printIn doAfterBody called if stop stop true return EVAL_BODY_AGAIN else return SKIP_BODY public int doEndTag printIn doEndTag called return EVAL_ PAGE public void release printIn release called private void printIn String s try pe getOut printIn s lt br gt catch IOException e System err printIn e toString In this tag class I was planning to have one attribute for my trace tag Attributes of a tag need to be implemented as properties in the tag class The setMyAtt String v method define a property called myAtt for my trace tag After compiling my trace tag class I copied TraceTag class to local jakarta tomcat 4 1 18 webapps root web inf classes herong directory I had to put it under subdirectory herong because the tag class was define in herong package Then I updated my tld file HyTaglib tld with a new tag element lt xml version 1 0 gt lt DOCTYPE tagli
119. ocities com herong_yang jsp jstl_el html The expressions must be written by folowing rules defined by the expression language Examples of JSTL actions lt c out value Hello world gt lt c if test 14 1 2 gt Always true lt c f gt lt c set var message value Hello world gt lt c out value message gt Expression Language Since expression will be used in most of the JSTL actions let s look at the express language before individual JSTL actions JSTL expression language is inspired by both ECMAScript and XPath expression language It is simple and supporting the following features e Literal data and named variables e Logical relational and arithmetic operations e A set of implicit objects e Nested properties and accessors to collections Examples of JSTL expressions lt c out value 1 1 2 gt lt c out value 1 1 gt lt c out value 1 3 gt lt c out value 1 0 3 0 gt lt c out value message gt lt c out value pageContext request class name gt lt c out value pageContext request method gt lt c out value pageContext request requestedSessionId gt lt c out value pageContext request cookies 0 name gt lt c out value quantity price lt 100 0 amp amp country USA gt Literal Data and Named Variables As in all computer language expression starts with literal data and variables JSTL expression l
120. orld in the IE window Now let s see the Servlet class generated by Tomcat server based on my JSP page with the c out tag The Servlet class is located at local jakarta tomcat 4 1 18 work standalone localhost _ hello_jstl_jsp java package org apache jsp import javax servlet import javax servlet http import javax servlet jsp import org apache jasper runtime public class hello_jstl_jsp extends HttpJspBase private static java util Vector _jspx_includes private org apache jasper runtime TagHandlerPool _jspx_tagPool_c_out_value public hello_jstl_jspQ 2 of 5 http www geocities com herong_yang jsp jstl html _jspx_tagPool_c_out_value new org apache jasper runtime TagHandlerPool public java util List getIncludes return _jspx_includes public void _jspDestroy _jspx_tagPool_c_out_value releaseQ public void _jspService HttpServletRequest request HttpServletResponse response throws java io IOException ServletException JspFactory _jspxFactory null javax servlet jsp PageContext pageContext null HttpSession session null ServletContext application null ServletConfig config null JspWriter out null Object page this JspWriter _jspx_out null try _jspxFactory JspFactory getDefaultFactory response setContentT ype text html charset ISO 8859 1 pageContext _jspxFactory getPageContext this request response null true 8192 t
121. p usebean html public String getTotal return total public void setSize int s size int s public void setSize String s size String s public String getSizeQ return size public void setX String x author x public String getY return author Compile this source code with JDK 1 4 1 and copy the class file to the Tomcat class path Remember to store the class file under a sub directory named as herong gt local j2sdk1 4 1 bin java DemoBean java gt copy DemoBean class local jakarta tomcat 4 1 18 webapps root web inf classes herong Now we are ready to test this JavaBean with an JSP page DemoBean jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt DemoBean jsp Copyright c 2003 by Dr Herong Yang gt lt html gt lt body gt lt jsp useBean id b class herong DemoBean gt lt jsp setProperty name b property author value Nobody gt Line 1 author lt jsp getProperty name b property author gt lt br gt lt lt jsp getProperty name b property Author gt lt br gt gt lt lt jsp getProperty name b property AUTHOR gt lt br gt gt lt jsp setProperty name b property status value false gt Line 2 status 7 of 12 http www geocities com herong_yang jsp usebean html lt jsp getProperty name b property status gt lt br gt lt jsp setPropert
122. r Herong Yang gt lt taglib gt lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt loop lt name gt lt tag class gt herong LoopTag lt tag class gt lt body content gt jsp lt body content gt lt tag gt lt tag gt lt name gt break lt name gt lt tag class gt herong BreakTag lt tag class gt lt body content gt empty lt body content gt lt tag gt lt other tags gt lt taglib gt Here is a test page LoopTagTest jsp lt xml version 1 0 gt 2 of 6 http www geocities com herong_yang jsp tag_parent html lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt lt LoopTagTest jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt c set var i value 1 gt lt c set var s value 0 gt lt hy loop gt lt c set var s value s i gt lt c set var i value i 1 gt lt c if test i gt 10 gt lt hy break gt lt c if gt lt hy loop gt lt c out value Sum s gt lt br gt lt body gt lt html gt lt jsp root gt am sure you can read this page and understand what I am doing with the loop Warning my break tag is not a truly break statement
123. r receiving and interpreting an HTTP request from a client a server must responds with an HTTP response following the syntax bellow status line header line header line entity body Note that e Response must have one status line e Response can have zero one or many header lines e Response can only have zero or one entity body e There is a blank line between header lines and the entity body e Status line head line and blank line must be ended with CRLF r n characters Entity body is the actual data requested by the client request Header lines can be in any order Bellow is a simple HTTP response with two header lines HTTP 1 1 200 OK Content Type text html Content Length 38 Hello world HTTP Response Header Lines HTTP 1 1 response header lines allows the server to passes additional information about the response which cannot be placed in the status line Header lines can be divided into three groups 1 of 14 http www geocities com herong_yang jsp response_header html 1 General header lines Information about the transmission of the entire response message Cache Control Connection Date Pragma Trailer Transfer Encoding Upgrade Via Warning 2 Response header lines Information about the response Accept Ranges Age ETag Location Proxy Authenticate Retry After Server Vary WWW Authenticate 3 Entity header lines Information about the data requested by the client Allow
124. r to hold information and methods common to all JSP pages running under one session The session object must be an instance of a class that implements the javax servlet http HttpSession interface defined by the J2EE specification Here is the highlights of the HttpSession interface defined in J2EE 1 3 e getAttribute Returns the object that is associated to the specified key string defined in the session e getAttributeNames Returns an Enumeration object that contains all the key strings defined in the session e getCreationTime Returns the time when this session was created measured in milliseconds since midnight January 1 1970 GMT e getId Returns the session ID as a string 5 of 6 http www geocities com herong_yang jsp context html e setAttribute Associate an object with the specified key string and store them to this session More information about the session object and sample JSP codes will be give in another chapter Dr Herong Yang updated in 2002 Home Help TOC Herong s Notes on JSP Execution Context 6 of 6 http www geocities com herong_yang jsp element html Herong s Notes on JSP Dr Herong Yang Version 3 03 2002 Home Help TOC JSP Elements Syntactic Elements of a JSP Page There are two types of data in a JSP page e Template Data The static part anything that will be copied directly to the response by the JSP server e JSP Elements The dynamic part anything
125. ray or collection will be iterated At each iteration the current element will assign to a named variable specified in the var attribute and body will be processed If the begin end or step attribute is specified it will be used to restrict the beginning element the ending element or the step size of the iteration If the items attribute is not specified an index integer will be used to iterate from the begin value to the end value stepping with the step value The c forEach action serves similar purposes as the Java for statement But there is no break 2 of 7 http www geocities com herong_yang jsp jstl_core html mechanism c forTokens Action lt c forTokens var name items expression delims expression begin expression end expression step expression gt body lt c forTokens gt The string specified by the items attribute will be tokenized with the delimiter specified by the delims attribute Then resulting tokens will be iterated At each iteration the current token will assign to a named variable specified in the var attribute and body will be processed If the begin end or step attribute is specified it will be used to restrict the beginning element the ending element or the step size of the iteration JSTL Core Example JstlObjects jsp As my first JSTL core example JstlObjects jsp is to use c forEach to browse through all the implicit objects and c forTekons to break t
126. req new HTTP Request GET gt u my res ua gt request req req res gt request cookie_jar gt extract_cookies res amp dump req res sub submitForm u url RegForm jsp name Mike amp pass None amp color Blue amp submit Submit my req new HTTP Request GET gt u cookie_jar gt add_cookie_header req my res ua gt request req req res gt request cookie_jar gt extract_cookies res amp dump req res sub dump local req res _ print nREQUEST HEADERS n print req gt headers_as_string print nNRREQUEST CONTENT n print req gt content if res gt is_success print nRRESPONSE HEADERS n print res gt headers_as_string print nARRESPONSE CONTENT n print res gt content else print nARESPONSE ERROR n print res gt error_as_HTML A couple of notes to help you to understand this program 7 of 10 http www geocities com herong_yang jsp session html e use LWP Debug qw turns on the debugging at the highest level e A LWP UserAgent object is used to send a HTTP request to the HTTP server HTTP Request objects are used to compose HTTP requests cookie_jar gt extract_cookies res is used to extract cookies from the response This is very important because JSP server is sending the session ID as a cookie to the client and expecting the client to send it back in the next request cookie_jar gt add_cookie_head
127. rg apache jsp UseBeanModified_jsp CacheBean b null AN The actual cause of this error is not the compiler It is the Tomcat compilation environment Because you can compile the converted class UseBeanModified_jsp java correctly in a command window with the same class paths used by the Tomcat environment The only option left to use a JavaBean with Tomcat 4 1 18 and JDK 1 4 1 is to create your JavaBean in a named package The next section will give you an example JavaBean in a Named Package TempratureConvertorBean java Creating JavaBean classes in named packages is very simple just add a package declaration statement at the beginning of the class The following example shows you a JavaBean classe defined in a package named as herong 3 of 5 http www geocities com herong_yang jsp tomcat_jdk141 html TempratureConvertorBean java Copyright c 2003 by Dr Herong Yang All rights reserved package herong public class TempratureConvertorBean private double celsius 0 0 private double fahrenheit 32 0 public double getCelsius return celsius public void setCelsius double c celsius c fahrenheit 1 8 c 32 0 public double getFahrenheit return fahrenheit public void setFahrenheit double f fahrenheit f celsius f 32 0 1 8 public String getInfoQ return new String My TempraturConvertorBean Version 1 00 Compile this source code and cop
128. right c 2002 by Dr Herong Yang gt lt html gt lt body gt lt jsp scriptlet gt out println Hello world lt jsp scriptlet gt lt body gt lt html gt lt jsp root gt Then obtain the response with java HttpRequestGet hello_xml jsp 8080 HTTP 1 1 200 OK Set Cookie JSESSIONID 94F75D820DA1B0BA6023704C5D2E665C Path Content Type text xml charset UTF 8 Content Length 40 Date Sat 23 Mar 2003 21 59 03 GMT Server Apache Coyote 1 0 Connection close lt html gt lt body gt Hello world lt body gt lt html gt This time hello_xml jsp was written in XML format so Tomcat decided to set Content_Type to text xml charset UTF 8 This is not right because it doesn t match the entity body If you use Internet Explorer to request this JSP page the entity body will not be rendered as XML data In the third example JSP page hello_xml_html jsp I used the jsp directive page element to correct the problem in the second example lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt hello_xml_html jsp Copyright c 2002 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt jsp scriptlet gt out println Hello world lt jsp scriptlet gt lt body gt lt html gt 7 of 14 http www geocities com herong_yang jsp response_header html lt jsp root gt Obtain the response with java HttpRequestGet hel
129. riptlet gt lt CDATA b setSize 15 gt lt jsp scriptlet gt Line 23 size lt jsp getProperty name b property size gt lt br gt Line 24 size lt jsp scriptlet gt lt CDATA out printIn b getSize gt lt jsp scriptlet gt lt br gt lt jsp scriptlet gt lt CDATA java util Date d new java util Date pageContext setAttribute d d PageContext PAGE_SCOPE gt lt jsp scriptlet gt lt jsp setProperty name d property time value 1000000000000 gt Line 25 time lt jsp getProperty name d property time gt lt br gt 10 of 12 http www geocities com herong_yang jsp usebean html lt body gt lt html gt lt jsp root gt Open this JSP page with IE you will get Line 21 author Unknown Line 22 total double 9 99 Line 23 size int 15 Line 24 size int 15 Line 25 time 1000000000000 Note that e Line 25 tells us that we can even create a Date object and make it available a JavaBean Its setTime and getTime methods are used provide the time property Refreshing the Loaded Bean Classes Once a bean class has been used once by a JSP page it will stay loaded in memory to avoid loading it again when another JSP page uses it This is good to improve response time but it is a problem if you changed your bean and wants to push the newer version into the server One way to force the server to use the new versions of bean classes is to shut down the server and re start the s
130. rue application pageContext getServletContext config pageContext getServletConfig session pageContext getSession out pageContext getOut _jspxX_out out out write r n out write lt taglib uri http java sun com jstl core prefix c gt r n out write lt html gt out write lt body gt r n if _jspx_meth_c_out_O pageContext return nn 3 of 5 http www geocities com herong_yang jsp jstl html out write r n out write lt body gt out write lt html gt catch Throwable t out _jspx_out if out null amp amp out getBufferSize 0 out clearBuffer if pageContext null pageContext handlePageException t finally if _jspxFactory null _jspxFactory releasePageContext pageContext private boolean _jspx_meth_c_out_O javax servlet jsp PageContext pageContext throws Throwable JspWriter out pageContext getOut cout org apache taglibs standard tag el core OutTag _jspx_th_c_out_0 org apache taglibs standard tag el core OutTag _jspx_tagPool_c_out_value get org apache taglibs standard tag el core OutTag class _jspx_th_c_out_0 setPageContext pageContext _jspx_th_c_out_0 setParent null _jspx_th_c_out_0 setValue Hello world int _jspx_eval_c_out_0 _jspx_th_c_out_0 doStartTagQ if _jspx_th_c_out_0 doEndTag javax servlet jsp tagext Tag SKIP_PAGE return true _jspx_tagPool_c_ou
131. runtime import java util import java text public class CurrentTime_jsp extends HttpJspBase private Date now private JspWriter out private void printTime String tz throws Throwable DateFormat df DateFormat getInstance df setTimeZone TimeZone getTimeZone tz out printIn tz df format now lt br gt private static java util Vector _jspx_includes static _jspx_includes new java util Vector 1 _jspx_includes add jsp JvmStamp jsp public java util List getIncludes return _jspx_includes public void _jspService HttpServletRequest request HttpServletResponse response throws java io IOException ServletException JspFactory _jspxFactory null javax servlet jsp PageContext pageContext null HttpSession session null ServletContext application null ServletConfig config null JspWriter out null Object page this JspWriter _jspx_out null try _jspxFactory JspFactory getDefaultFactory response setContentType text html charset UTF 8 pageContext _jspxFactory getPageContext this request response null true 8192 true application pageContext getServletContext 7 of 9 config pageContext getServletConfig session pageContext getSession out pageContext getOut _jspxX_out out out write lt html gt out write lt body gt out write lt p gt out write lt b gt out write Current time in
132. s in org apache taglibs standard lang support package e The expression rules are identical to those described in JSTL because we are using the same evaluation tool e If you click refresh button on the browser the mapObject size will be 1 because the session id is stored in the cookie map Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP JSP Tag Attribute Handling 12 of 12 http www geocities com herong_yang jsp tag_parent html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC Tags Working Together Nested Tags When tags are nested JSP tag extension facility offers the child tag an access to the parent tag by the setParent method call You can take advantage of this access to design nested tags to work together to perform more complex functions As an example I wrote two simple tags to perform a loop function with the ability to break out the loop conditionally Here is my loop tag LoopTag java LoopTag java Copyright c 2003 by Dr Herong Yang All rights reserved Ef package herong import java io import javax servlet jsp tagext public class LoopTag extends TagSupport public boolean stop false public int doStartTag return EVAL _BODY_INCLUDE public int doAfterBody if stop return EVAL_BODY_AGAIN else return SKIP_BODY The logic of the loop tag is very simple It evaluates its body immediate
133. s exchanged between a specific Web browser and a specific Web server see the following diagram Server Browser ID created lt Request 1 Response 1 gt ID kept as cookie lt Request 2 ID send back to server Response 2 gt lt Request 3 ID send back to server Response 3 gt The session concept is managed by the server When the first request comes from a browser on a new host the server makes the beginning of a new session and assigns a new session ID The session ID will be then send to the browser as cookie The browser will remember this ID and send the ID back to the server in the subsequent requests When the server receives a request with session ID in them it knows this is a continuation of an existing session When the server receives a request from a browser on a new host request without a session ID the server not only creates a new session ID it also creates a new session object associated with the session ID See the next section for details If there is no subsequent request coming back for a long time for a particular session ID that session will be timed out After the session has been timed out if the browser comes back again with the associated session ID the server will give an invalid session error 1 of 10 http www geocities com herong_yang jsp session html The session Object session A object provided by the JSP server to hold in
134. sponse response throws java io IOException ServletException JspFactory _jspxFactory null javax servlet jsp PageContext pageContext null HttpSession session null ServletContext application null ServletConfig config null JspWriter out null Object page this JspWriter _jspx_out null try _jspxFactory JspFactory getDefaultFactory response setContentT ype text xml charset UTF 8 pageContext _jspxFactory getPageContext this request response null true 8192 true application pageContext getServletContext config pageContext getServletConfig session pageContext getSession out pageContext getOut _jspxX_out out out write lt html gt out write lt body gt CacheBean b null synchronized pageContext 3 of 12 http www geocities com herong_yang jsp usebean html b CacheBean pageContext getAttribute b PageContext PAGE_SCOPE if b null try b CacheBean java beans Beans instantiate this getClass getClassLoader CacheBean catch ClassNotFoundException exc throw new InstantiationException exc getMessage catch Exception exc throw new ServletException Cannot create bean of class CacheBean exc pageContext setAttribute b b PageContext PAGE_SCOPE JspRuntimeLibrary introspecthelper pageContext findAttribute b text Hello world null null false out write nProperty from my Bean
135. t booleanObject lt br gt out println stringAtt stringAtt lt br gt out println stringObject stringObject lt br gt 9 of 12 http www geocities com herong_yang jsp tag_attribute html out println mapAtt mapAtt lt br gt if mapObject null out println mapObject size mapObject size lt br gt else out println mapObject null lt br gt catch IOException e System err printIn e toString return SKIP_BODY The TLD file lt xml version 1 0 gt lt DOCTYPE taglib PUBLIC Sun Microsystems Inc DTD JSP Tag Library 1 2 EN http java sun com j2ee dtds web jsptaglibrary_1_2 dtd gt lt HyTaglib tld Copyright c 2003 by Dr Herong Yang gt lt taglib gt lt tlib version gt 1 lt tlib version gt lt jsp version gt 1 2 lt jsp version gt lt short name gt Herong s Tag Library lt short name gt lt tag gt lt name gt attObject lt name gt lt tag class gt herong AttObjectTag lt tag class gt lt body content gt empty lt body content gt lt attribute gt lt name gt booleanAtt lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt stringAtt lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt mapAtt lt name gt lt required gt false lt required gt lt attribute gt lt tag gt 10 of 12 http www geocities com herong_y
136. t e The important method in hello_jsp is _jspService with two objects listed as parameters one represents the Servlet request and the other represents the Servlet response 3 of 5 http www geocities com herong_yang jsp jsp html e The static content of hello jsp is translated into out write statements e The embedded Java statement in hello jsp is copied directly Writing JSP Servlet Class Directly Now we know that a JSP page is served by the JSP Web server by executing the JSP Servlet Java class translated from the JSP page This means that we can write a JSP Servlet Java class directly and ask the JSP Web server to serve it To try this idea let s first write this JSP page fake jsp and save it to local jakarta tomcat 4 1 18 webapps ROOT lt fake jsp Copyright c 2002 by Dr Herong Yang All rights reserved gt lt html gt lt body gt This a faked JSP page The real content will come from the output of the JSP Servlet class lt body gt lt html gt Then write the following JSP Servlet class fake_jsp java and save it to local jakarta tomcat 4 1 18 work standalone localhost _ fake_jsp java Copyright c 2002 by Dr Herong Yang All rights reserved package org apache jsp import javax servlet import javax servlet http import javax servlet jsp import org apache jasper runtime public class fake_jsp extends HttpJspBase public java util List getIncludes retur
137. t lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt booleanValue lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt booleanObject lt name gt lt required gt false lt required gt lt attribute gt lt attribute gt lt name gt stringObject lt name gt lt required gt false lt required gt lt attribute gt lt tag gt lt taglib gt The JSP file lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core xmlns hy urn jsptld WEB INF tlds HyTaglib tld version 1 2 gt lt AttValueTagTest jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt hy attValue longObject 1 long Value 2 doubleObject 1 1 doubleValue 2 2 booleanObject true boolean Value false stringObject Hello world gt lt body gt lt html gt lt jsp root gt The output long Value 2 6 of 12 http www geocities com herong_yang jsp tag_attribute html longObject 1 doubleValue 2 2 doubleObject 1 1 booleanValue false booleanObject true stringObject Hello world The Servlet class produced by Tomcat server private boolean _jspx_meth_hy_attValue_0 javax servlet jsp PageContext pageContext throws Throwable JspWriter out pageContext getOut hy attValue herong
138. t br gt for int n 1 n lt numberOfPrimes n out printIn primes n 1 out println lt body gt lt html gt gt lt jsp scriptlet gt lt jsp root gt I run this page and got the following result It tells me the page is working correctly Performace Information Number of tests 1 Time 0 seconds First 1000 Prime numbers 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 By changing the controlling parameters I was able to get some results Number Number Debug Time Cases of Tests of Primes Mode sec Notes OV te 1 1000 Yes 25 ASP with IS 5 0 1 1000 No 25 ASP with IIS 5 0 1 1000 0 JSP with Tomcat 4 1 18 10 1000 2 JSP with Tomcat 4 1 18 100 1000 22 JSP with Tomcat 4 1 18 100 1000 21 JVM HotSpot 1 3 1 So this tells us that JSP pages are 100 times faster than ASP pages for integer calculations Response Time of Hello Page The next area I want test is total response time of ASP pages To do this I wrote the following Java program This program is doing a single HTTP request to a specifield Web page and repeating this for many times 2 of 5 http www geocities com herong_yang jsp performance html HttpResponseTest java Copyright c 2002 by Dr Herong Yang All rights reserved import java io import java net public class HttpResponseTest public static void main String args int numberOfTests 1 if args length
139. t_value reuse _jspx_th_c_out_0 return false As you can see the c out tag is replaced by method call The method then interacts with the class org apache taglibs standard tag el core OutTag where the out tag is implemented The implementation is probably very simple may be just an out write statement JSTL in XML Style JSP Pages Since I like to write JSP in XML style I have to find out how to use JSTL in XML style JSP pages It took me some time to figure this Here is an example code hello_jstl_xml jsp 4 of 5 http www geocities com herong_yang jsp jstl html lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt hello_jstl_xml jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt lt jsp scriptlet gt out println Hello world lt jsp scriptlet gt lt br gt lt c out value Hello world from c out gt lt body gt lt html gt lt jsp root gt The trick is to convert the tablib to a name space attribute in the jsp root element JSTL Requirements The requirements to use JSTL are e A JSP server Tomcat from apache org e A JSTL implementation Tablib from apache org jstl jar and standard jar e A JSTL document JSTL specification from jcp org e JSP pages with JSTL tags You write them Dr Herong Yang updated in 2
140. ta tomcat 4 1 18 bin set JAVA_HOME local j2sdk1 4 1 startup 3 Created the following JSP page hello jsp and copied to local jakarta tomcat 4 1 18 webapps ROOT lt html gt lt body gt lt out printIn Hello world gt lt body gt lt html gt 4 Ran Internet Explorer IE with url http localhost 8080 hello jsp You should see Hello world in the IE window lof5 http www geocities com herong_yang jsp tomcat_jdk141 html I am pretty sure now my Tomcat server is running ok with JDK 1 4 1 Compilation Errors with Tomcat 4 1 18 and JDK 1 4 1 To demonstrate the compilation error run IE on the following JSP page I created in the Using JavaBean Classes chapter UseBean jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt UseBean jsp Copyright c 2002 by Dr Herong Yang gt lt html gt lt body gt lt jsp directive page import CacheBean gt lt jsp useBean id b class CacheBean gt lt jsp setProperty name b property text value Hello world gt Property from my Bean lt jsp getProperty name b property text gt lt br gt Info from my Bean lt jsp expression gt b getInfo lt jsp expression gt lt body gt lt html gt lt jsp root gt You will see a compilation error in the IE window org apache jasper JasperException Unable to compile class for JSP An error occurred at line 8 in the jsp file UseBean jsp Genera
141. te I FileInputStream f new FileInputStream p f read b ServletOutputStream o response getOutputStream o write b 0 1 o flushQ o close f close catch Exception e response sendError HttpServletResponse SC_BAD_REQUEST lt jsp scriptlet gt lt jsp root gt If you use IE 6 0 to request http localhost 8080 GetPdf jsp you will get nothing on the IE window Now if you use IE 6 0 to request http localhost 8080 GetPdf jsp x pdf you will see Adobe Reader displaying the hello message Interestingly if you use IE 6 0 to request http localhost 8080 GetPdf jsp x doc you will also see Adobe Reader displaying the hello message I guess IE 6 0 has a stupid bug What do you think Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP Controlling HTTP Response Header Lines 14 of 14 http www geocities com herong_yang jsp non_ascii html Herong s Notes on JSP Dr Herong Yang Version 3 03 2002 Home Help TOC Localization Internationalization Non ASCII Characters in JSP Pages This chapter explains e How characters travel from JSP files to browser screens How ASCII characters work in JSP pages How to present non ASCII characters in HTML documents How to enter non ASCII charactetrs in Java strings and contole the output encodings e How Java string works with byte sequences encoded for a local language e How Java string works with Unicode codes lo
142. ted by the JSP enabled Web server not by the Web browser JSP Page is a Web page HTML document with enbedded Java statements in a structure defined by the JSP specification Here is a JSP page example hello jsp lt html gt lt body gt lt out printIn Hello world gt lt body gt lt html gt Line 1 and 3 are normal HTML tags But line 2 is a Java statement embedded in special HTML tag We know how a normal Web page is served by a normal Web server e Step 1 The Web browser sends a HTTP request to the Web server with the path name of the Web page e Step 2 The Web server picks up the Web page by following the specified path name e Step 3 The Web server puts the content of the Web page without any changes into a HTTP response e Step 4 The Web server sends the HTTP response to the Web browser Here is how a JSP page is served by a JSP Web server e Step 1 The Web browser sends a HTTP request to the Web server with the path name of the JSP page e Step 2 The Web server checks to see if there is a compiled version of the requested JSP page If no it compiles the requested JSP page immediately e Step 3 The Web server executes the compiled version of the requested JSP page and collects the output of the execution Step 4 The Web server puts the output of the execution into a HTTP response Step 5 The Web server sends the HTTP response to the Web browser There are two key processes involved in serving a JS
143. ted servlet error javac Compiling 1 source file Cxocal jakarta tomcat 4 1 18 work Standalone localhost _ UseBean_jsp java 7 expected import CacheBean This tells us that JDK 1 4 1 does not allow import statement to be used on classes in unnamed packages So what can we do about this Can we remove the import statement The answer is no You can try by running the following modified JSP page UseBeanModified jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt 2 of 5 http www geocities com herong_yang jsp tomcat_jdk141 html lt UseBeanModified jsp Copyright c 2002 by Dr Herong Yang gt lt html gt lt body gt lt jsp useBean id b class CacheBean gt lt jsp setProperty name b property text value Hello world gt Property from my Bean lt jsp getProperty name b property text gt lt br gt Info from my Bean lt jsp expression gt b getInfo lt jsp expression gt lt body gt lt html gt lt jsp root gt You will get the following compilation error saying CacheBean is not resolvable org apache jasper JasperException Unable to compile class for JSP An error occurred at line 7 in the jsp file jsp UseBeanModified jsp Generated servlet error javac Compiling 1 source file D Mocal jakarta tomcat 4 1 18 work Standalone localhost _ jsp UseBeanModified_jsp java 43 cannot resolve symbol symbol class CacheBean location class o
144. th 1 byte b new byte I FileInputStream f new FileInputStream p f read b ServletOutputStream o response getOutputStream o write b 0 1 o flushQ o close f closeQ catch Exception e ok false if ok response sendError HttpServletResponse SC_BAD_REQUEST lt jsp scriptlet gt lt jsp root gt 11 of 14 http www geocities com herong_yang jsp response_header html Ideas used in this page e The objective of this page is to send back the content of the requested file in entity body and set the Content_Type and Content_Length header lines correctly e The requested file name is given in the query string of the HTTP request e The extension of the requested file name is checked to determine the Content_Type header line Then the requested file size is checked to set the Content_Length header line Then the requested file is opened and the content is copied to output stream of the response object as a byte array e If any thing goes wrong an error status code is send to the response e Now let s see how this page works 1 Use IE Internet Explorer to request http localhost 8080 GetFile jsp hello html you should see the hello message properly displayed as HTML document 2 Use IE to request http localhost 8080 GetFile jsp dot gif you should see a tiny dot displayed as an image 3 Use IE to request http localhost 8080 GetFile jsp hello pdf you should see IE calling
145. that maps cookie names to a single Cookie obtained by calling HttpServletRequest getCookie String e initParam a Map that maps a parameter names to a single String parameter value obtained by calling ServletRequest getInitParameter String Accessing Collection Elements and Object Properties JSTL supports reference operations to collection elements and object properties by using and operators But they are used in the way as ECMAScript which is very different than Java Here is the main steps of the evaluation process e 0 Check syntax to only allow identifier_a identifier_b and identifier_a expression_b e 1 Replacing operator by operator So convert identifier_a identifier_b to identifier_a identifier_b e 2 Evaluate the second operand So convert identifier_a expresion_b to identifier_a value_b e 3 If the first operand matches no existing object name return null e 4 If the second operand evaluates to null return null e 5 If the first operand reprents an array try to finish the operation as So try to evaluate identifier_a value_b as is e 6 If the first operand reprents a map try to finish the operation with a call to get So try to evaluate identifier_a value_b as identifier_a get value_b e 7 If the first operand represents an object of orther types try to finish the operation as a Java bean property accessing operation So convert identifier_a value_b to
146. then if value a get value b or Array get value a value b throws ArrayIndexOutOfBoundsException or IndexOutOfBoundsException return null otherwise if value a get value b or Array get value a value b throws other exception error otherwise return value a get value b or Array get value a value b as appropriate Otherwise a JavaBeans object coerce value b to String If value b is a readable property of value a if getter throws an exception error otherwise return result of getter call otherwise error ExpExample jsp Expression Example Page To check my understanding of the expression language I wrote the following JSP to show some expression examples lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page xmlns c http java sun com jstl core version 1 2 gt lt ExpExample jsp Copyright c 2003 by Dr Herong Yang gt 5 of 9 http www geocities com herong_yang jsp jstl_el html lt jsp directive page contentType text html gt lt html gt lt body gt lt p gt JSTL Expression Examples lt p gt lt c out value 1 1 1 2 gt lt br gt lt c out value 2 1 1 gt lt br gt lt c out value 3 1 3 gt lt br gt lt c out value 4 1 0 3 0 gt lt br gt lt c out value 5 quantity price It 100 0 and country USA gt lt br gt lt c set var message value Hi there gt lt c out value 6 message gt lt br gt lt c out va
147. tion scriptlet and expression elements lt jsp directive directive_name attribute value gt lt jsp declaration gt Java decalaration statements lt jsp declaration gt lt jsp scriptlet gt Java statements lt jsp scriptlet gt lt jsp expression gt Java expressions lt jsp expression gt You also have to create a jsp root element Here is my Hello world example in XML format lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt hello_xml jsp Copyright c 2002 by Dr Herong Yang gt html gt lt body gt lt jsp scriptlet gt out println Hello world lt jsp scriptlet gt lt body gt lt html gt lt jsp root gt Then open this JSP page with IE what you will see is this lt html gt lt body gt Hello world lt body gt lt html gt What happens here is that the server is probably sending response with content type set to text xml To fix the problem we need to use a directive element to set the contect type back to text html Here is the modified JSP page hello_xml_html jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt hello_xml_html jsp Copyright c 2002 by Dr Herong Yang gt 2 of 9 http www geocities com herong_yang jsp element html lt jsp directive page contentType text html gt lt html gt lt body gt lt jsp scriptlet gt out println Hello world lt
148. understanding of how custom tag works using the Hello world tag as an example e When hello_tag jsp page is requested for the first time Tomcat server will translate the JSP page into a java class e When the lt hy hello gt custom tag is encountered during the translation Tomcat server will follow the tld file to locate the HelloTag class file Note that the tld file is provided in the jsp root element e Then Tomcat server will replace the custom tag with some Java code to instantiate an object of the tag class initialize the object and call the doStartTag method e To output data into page you can get an output stream from the pageContext object provided by the JSP tag extension facility pageContext getOut This is how the Hello world message gets produced in the IE window e Note that I have to use jsp directive page to import HelloTag class into the JSP page because my HelloTag class has no Java package name and needs to be imported even if it is located in the class path Dr Herong Yang updated in 2003 Home Help TOC Herong s Notes on JSP JSP Custom Tag 3 of 3 http www geocities com herong_yang jsp tag_interface html Herong s Notes on JSP Dr Herong Yang Version 3 03 2003 Home Help TOC JSP Tag Java Interface javax servlet jsp tagext Package javax servlet jsp tagext is a Java package defined in J2EE I saw it in J2EE 1 3 1 This package contains e Tag interface
149. when you close Internet Explorer The cookie can be read by the Web site that created it when you visit that site again You can use cookie setMaxAge s to set the cookie to be persistent for s seconds A temporary or session cookie is stored only for your current browsing session and is deleted from your computer when you close Internet Explorer You can use cookie setMaxAge 1 to set the cookie to be temporary Other properties of a cookie object that you can set and get e setPath Defines the path name so that when a pages under this path name is requested the browser will send this cookie to the server The path name is the url without the server name and the port number parts e setDomain Defines the domain name so that when a page under this domain name is requested the browser will send this cookie to the server The default domain name is the server name from which the cookie was created e setMaxAge Defines how long the cookie should be stored on the browser s machine MaxAge value is in unit of second A negative value tells the browser to not save it to the harddisk A zero value tells the browser to delete it e setVersion Defines the version number to which this cookie is compliant with The following JSP page shows you how to set a persistent cookie and how to use other properties lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt CookieProperties
150. y name b property count value 5 gt Line 3 count lt jsp getProperty name b property count gt lt br gt lt lt jsp setProperty name b property total value 9 gt gt Line 4 total lt jsp getProperty name b property total gt lt br gt lt jsp setProperty name b property size value 14 gt Line 5 size lt jsp getProperty name b property size gt lt br gt lt jsp setProperty name b property x value Herong gt Line 6 size lt jsp getProperty name b property y gt lt br gt lt body gt lt html gt lt jsp root gt Make sure to run your Tomcat under JDK 1 4 1 Then open this JSP page with IE you will get Line 1 author Nobody Line 2 status false Line 3 count 5 Line 4 total 1 Line 5 size String 14 Line 6 y Herong Note that e Property names are case sensitive Property name Author can not be mapped to getAuthor method e Two set methods without any one taking String as input parameter type is giving me problem to set total e Two set methods with one taking String as input parameter type is ok Output line 5 is the prove Using JavaBeans as Objects in Scripting Elements As I mentioned in the previous section JavaBean is just a normal Java object with some special method Once a JavaBean is created we should be able to use it as Java object in any scripting elements 8 of 12 http www geocities com herong_yang jsp us
151. y the class file to the Tomcat class path Remember to store the class file under a sub directory named as herong gt local j2sdk1 4 1 bin java TempratureConvertorBean java gt copy TempratureConvertorBean class local jakarta tomcat 4 1 18 webapps root web inf classes herong Now we are ready to test this JavaBean with an JSP page TempratureConvertor jsp lt xml version 1 0 gt lt jsp root xmlns jsp http java sun com JSP Page version 1 2 gt lt TempratureConvertor jsp Copyright c 2003 by Dr Herong Yang gt lt jsp directive page contentType text html gt lt html gt lt body gt 4 of 5 http www geocities com herong_yang jsp tomcat_jdk141 html lt jsp useBean id b class herong TempratureConvertorBean gt lt jsp expression gt b getInfo lt jsp expression gt lt br gt Setting property fahrenheit to 70 0 lt br gt lt jsp setProperty name b property fahrenheit value 70 0 gt Getting property celsius back lt jsp getProperty name b property celsius gt lt br gt lt body gt lt html gt lt jsp root gt Open this JSP page with IE you will get My TempraturConvertorBean Version 1 00 Setting property fahrenheit to 70 0 Getting property celsius back 21 11111111111111 It works Note that there is no need to use the import statement if you use the fully qualified class name in the jsp useBean action element Conclusions e Using JavaBean classes i

Download Pdf Manuals

image

Related Search

Related Contents

SAS-DVRODR30 Wildlife camera  Mode d`emploi et instructions de montage Lave-linge W 58  Plan de formation 2013-2015 - Communauté de Communes de  Sennheiser CEHS-CI 02  16-point Input Sink • Source Type" (FN-X16TS41)  IM Controller board  Anleitung  Série Delta™  GRANDO EVO (41035382), page 1 @ Preflight  Tren SAFARI - Crown Leisure  

Copyright © All rights reserved.
Failed to retrieve file