1 / 139

JavaServer Pages

What is a JSP?. JSP are html pages which contain both static (like traditional html) and dynamic content. Content may vary with the client request, identity or browser type.JSP elements are executed by the server and merged with the page's static contents and sent to the client.Accessing beans, s

hop
Download Presentation

JavaServer Pages

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web

    2. What is a JSP? JSP are html pages which contain both static (like traditional html) and dynamic content. Content may vary with the client request, identity or browser type. JSP elements are executed by the server and merged with the page’s static contents and sent to the client. Accessing beans, sharing information between users and pages and requests are a few possible JSP actions. JSP syntax is also extensible to deal with application-specific concerns.

    3. Why JSP? A number of technologies have arisen to challenge CGI programming – the only choice in the early 90s. CGI is not efficient. Each incoming request spawns a new server process. A script must be loaded, interpreted (executed) and then disposed. As traffic increases the problems inherent in this model worsen.

    4. CGI alternatives FastCGI Mod_perl NSAPI ISAPI Java servlets All these improve on CGI performance but at the cost of embedding html in the programming language. This means only programmers can develop server pages.

    5. JSP JSP may contain java code embedded in the scripting elements, though this is rarely needed. Too much code in a JSP results in the same lopsided application modularization as placing the html in the servlet. Recent innovations in JSP are the Expression Language (EL) and the standard tag library (JSTL).

    6. JSP- benefits JSP are compiled, not interpreted. Typically, they are compiled on the first load and, unless changed, available to subsequent requests without another compilation. In conjunction with a persistent JVM on a JSP-enabled server, JSP can be delivered very quickly.

    7. Application modularization A good breakdown of an internet application is for JavaBeans to handle application logic (& datatypes), servlets can handle input processing, and JSP can provide the user interface.

    8. JSP power JSP are built on the servlet api (they are actually compiled into servlets) consequently JSP can access JDBC RMI and CORBA JNDI (java naming and directory interface) JMS – java message service JavaMail Java API for XML registries (JAXR), java API for XML-rpc (JAX-RPC) and SAAJ (SOAP with attachments api for java).

    9. ASP vs JSP ASP are Microsoft’s popular technology for developing dynamic sites. The page may include VB- and J-script. COM (ActiveX) components written in C++ can handle complex code. Database access components and more are included in ASP. ASP.NET, the newest version, provides for dynamic content to be delivered via XML. ASP are compiled. Reliance on native COM-code components makes ASP primarily an (MS) windows-platform solution.

    10. Others PHP- an open source scripting language with C style syntax. ColdFusion –Macromedia’s product. XML-type elements provide active content following CFML (cold-fusion-markup-language). Database handling, mailservers, conditional elements (loops) and allows custom elements to be added using C++ or Java. CFML extensions are available from third-party vendors. Java servlet template engine: A number of template engines were developed when programmers realized that embedding the html in the code was not such a great idea. Web scripting handles the presentation and servlets handle processing.

    11. JSP design To stop your JSP code from becoming a maintenance nightmare, you will need to think and ask yourself a few questions. What does this page actually do? Should I have my JSP page doing the tasks for add, update and delete? Would it be better to have them done by different JSPs? How can I reduce the amount of Java code in the JSP so a web designer can keep the front-end looking good? How do I reuse code done by other developers in my team? Has anyone on the Internet already done some of the things I need to do in my JSP pages? If something goes wrong in my application, how will I log the error?  How can I make my JSP page display text in different languages?

    12. An example: Technologies to consider If you were writing a Message Board application, you would think of a front-end dynamically showing messages from registered posters, maybe sending emails to Message Board posters etc.   J2EE technologies that you will probably consider should include: JSP - used for designing the front end. JDBC - as the pages for the Message Board are dynamically produced, it would make sense to store them in a database table. You would use JDBC to connect and do queries on the database. JavaMail - used for sending emails via SMTP.   Now depending on the tasks of the Message Board, you might also what to consider:   Servlets - alternative to JSP. When you want to carry out a task that does not need a frontend. A Servlet is a special Java class which outputs HTML via print statements. You could use a Servlet to send the emails (by also using JavaMail).

    13. JSP or Servlets when developing J2EE applications?     You will probably use Both.   JSP will be used for nearly all your front end web interface with minimal Java code. When you have a form that sends a request to search for results that you display in an HTML table, you would use a JSP. However, if you were sending out an email, you would use a Servlet. Why? The process of sending an email does not require a fancy frontend. The sending email process is a reusable service that would be coded in Java with no need for HTML design.

    14. Why not design the whole application as Servlets?    To answer this question you need to understand the advantages of using JSP. The whole point of using JSP was to quickly produce web front ends. If you wrote an entire web front end application using servlets, it would probably take you much longer than using JSP. This is because every element of the HTML page would need to be in print statements in a Servlet. How can we decide between JSP and Servlets? It really comes down to analysing and designing your application. You need to highlight areas that are more like services (without being fixed to a front end) and other parts that consist of the user's interface.

    15. The problem with servlets Servlets often contain request processing, business logic and code (println) to generate the html response. Servlet creators must be java programmers. Changing look/feel of a web app or upgrading to support new clients is hard if the GUI features are in the servlet. It is very hard to use web tools to develop an interface since the resulting html must still be manually hard-coded into the servlet.

    16. How JSP helps JSP can handle the presentation side and servlets can handle processing. One part of the application can be upgraded/changed without impact to other parts. This modularization enhances portability, maintainability and re-usability of the application and its components.

    17. JSP advantage JSP supports both scripting and element-based dynamic content. JSP are compiled (efficient). JSP can work with servlets which can handle the logic and processing. JSP is a specification, not a product. Competition in providing JSP can improve performance and keep JSP around awhile. JSP is part of J2EE so JSP have the java API to back them up and are scalable.

    18. To run JSP text examples Install Tomcat Examples from O’Reilly’s JSP text (source code and directories) can be downloaded from: http://examples.oreilly.com/jserverpages3/ Hall text has text website and jsp examples not included in this ppt so far Copy ORA directory of extraction into tomcat webapps --- mine is at http://CSCI345.oneonta.edu:8080/ora

    19. A JSP technology overview see Resources for links to additional JSP technology information. In the traditional sense, JSP pages look very much like HTML pages, with a few extra tags. These tags allow the designer to embed Java code (not merely JavaScript) in the page itself. A Web application server will intercept requests for JSP pages. It's tipped off to their existence by the page's extension: .jsp (not .html). The Web application server then preprocesses the JSP page, taking out the JSP tags and any embedded Java code, leaving only the HTML. The extracted JSP tags and embedded Java code are used to build a Java servlet (JSP page servlet) that runs the code and inserts the results back into the original page where the JSP tags used to be. The result is pure HTML. The Java is stripped out and run on the server before the requesting browser sees any result.

    20. Steps to execute JSP The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). The web browser makes the request via the Internet. The JSP request gets sent to the Web server. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file to the JSP Servlet Engine. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to println statements. The Servlet source code is compiled into a class. The Servlet is instantiated, calling the init and service methods. HTML from the Servlet output is sent via the Internet. HTML results are displayed on the user's web browser.

    21. Some URLs with resources Some sites I found just searching: http://java.sun.com/products/jsp/html/JSPXML.html http://www.onjava.com/pub/a/onjava/2001/11/28/jsp_xml.html http://www.visualbuilder.com/jsp/tutorial/

    22. where to put them put jsp into a webapp root directory. I copied them into a directory called my-jsp They need no servlet tags or url patterns in the web.xml and so are available for use as soon as they are copied They are compiled into a “workhorse” servlet, so the first call will be slow.

    23. File Structure: tag libraries and jar files Place jar files (if you’ve created these) in lib and place class files for compiled java in classes. Client browsers can’t see or access this code. Tag libraries can be placed in lib (in jar format). Classes needed can go in classes, following the same hierarchical/derivation structure they have. Alternatively, these files can be zipped and placed in a war file.

    24. File Structure and your own JSP Create your own jsp directory under webapps in Tomcat. Place the *.jsp in subdirectories or directly in this directory. Create a WEB-INF directory in this directory and a lib directory in here. Copy standard.jar, jstl.jar and other necessary tag libraries into lib.

    25. Standard jsp/servlet File Structure Tomcat webapps Your jsp/servlet directory Jsp files here or in subdirectories WEB-INF directory lib (put jar files here, including standard.jar, jstl.jar,…) classes (put class files here)

    26. Notes and examples from Hunter chapter 18 servlets text

    27. hello1.jsp <HTML> <HEAD><TITLE>Hello</TITLE></HEAD> <BODY> <H1> <% if (request.getParameter("name") == null) { out.println("Hello World"); } else { out.println("Hello, " + request.getParameter("name")); } %> </H1> </BODY></HTML>

    28. hello1.jsp

    29. scriplets and other code in the jsp the request for a jsp causes a java compile creating a servlet which is returned for the response. scriptlets have <% open tag and %> close tag and contain servlet code. declarations begin with <%! and end with %> comments have <%-- tags --%> assignments/expressions have the form <%=foo%>

    30. hello2

    31. hello2.jsp <%-- hello2.jsp --%> <HTML> <HEAD><TITLE>Hello</TITLE></HEAD> <BODY> <H1> Hello, <%= getName(request) %> </H1> </BODY> </HTML> <%! private static final String DEFAULT_NAME = "World"; private String getName(HttpServletRequest req) { String name = req.getParameter("name"); if (name == null) return DEFAULT_NAME; else return name; } %>

    32. declarations declarations should contain any code that goes outside a servlet’s service methods. you may declare static or instance variables or define new methods. hello2.jsp defines a getName() method and an expression to print it.

    33. directives directives enable a jsp to have the workhorse (background) servlet set content-type, import a package, set the buffer size, flush the buffer or throw an ioexception when the buffer is filled. Directives also enable a jsp to access user session information. Error-maker throws an exception, error-taker displays an error.

    34. errorMaker.jsp hands error info to errorTaker

    35. Avoid java code in your jsp scriptlets, expressions and declarations allow the placement of java code in jsp. Text recommends AVOIDING their use tag libraries and java beans facilitate separation of presentation and content.

    36. beans – a slightly modified example from the text package beanex.example;//note package public class HelloBean { private String name = "World"; public void setName(String name) { this.name = name; } public String getName() { return name; } }

    37. beans the bean will have to go in the appropriate file under classes. in this case classes/beanex/example

    38. hello3.jsp <%-- hello3.jsp --%> <%-- page import="HelloBean“… note this is a comment --%> <jsp:useBean id="hello" class="beans.HelloBean"> <jsp:setProperty name="hello" property="*" /> </jsp:useBean> <HTML> <HEAD><TITLE>Hello</TITLE></HEAD> <BODY> <H1> Hello, <jsp:getProperty name="hello" property="name" /> </H1> </BODY> </HTML>

    39. same as two previous examples

    40. and with a parameter

    41. Another jsp/bean example running

    42. the form <HTML> <BODY> <FORM METHOD=POST ACTION="SaveFormData.jsp"> Enter your name : <INPUT TYPE=TEXT NAME=userName SIZE=20><BR> Enter a password : <INPUT TYPE=PASSWORD NAME=userPass SIZE=20><BR> Enter PIN : <INPUT TYPE=TEXT NAME=userPIN SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

    43. saveform.jsp

    44. saveform.jsp <jsp:useBean id="user" class="certy.example.UserInfoBean" scope="session" /> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF="DisplayFormData.jsp">Display Entered Data.</A> </BODY> </HTML>

    45. DisplayForm.jsp

    46. DisplayForm.jsp <jsp:useBean id="user" class="certy.example.UserInfoBean" scope="session"/> <HTML> <BODY> You entered : <BR/> Name: <%= user.getUserName() %><BR/> Password: <jsp:getProperty name="user" property="userPass" /><BR/> PIN: <%= user.getUserPIN() %><BR/> </BODY> </HTML>

    47. the bean package certy.example; public class UserInfoBean { String username; String password; int pin; public void setUserName( String value ) { username = value; } public void setUserPass( String value ) { password = value; } public void setUserPIN( int value ) { pin = value; } public String getUserName() { return username; } public String getUserPass() { return password; } public int getUserPIN() { return pin; } }

    48. Creating another form (example off internet tutorial – I think) Here we show how to create and process an html form. Copy the code (next slide) and place in a file named: myform.jsp Go to myform.jsp in your browser You will see the form you just created. It won't do anything yet.

    49. Myform.jsp <html> <head> <!-- Example --> <title>A Form Example</title> </head> <body> <form action="myformconfirm.jsp" method="post"> Enter in a website name:<br> <input type="text" name="website"><br> <input type="submit" name="submit"> </form> </body> </html>

    50. Processing a Form Here we show how to process the html form your just created. Copy the code below and place in a file named: myformconfirm.jsp Go to myform.jsp Fill in some details and submit the form You should see the results of your submission

    51. Myformconfirm.jsp processes myform <html> <head> <!-- Example4 --> <title>myformconfirm</title> </head> <body> <font face=verdana size=3> Your info has been received: <br><br> <% String sName = request.getParameter("website"); out.print(sName); %> </font> </body> </html>

    52. myform

    53. Processing myform

    54. Fullform.jsp in notes <html> <head> <!-- Example5 --> <title>fullform.jsp</title> </head> <body> <h1> Website submission form </h1> <form action="fullformconfirm.jsp" method="post"> Enter in the website name: <input type="text" name="website"> <br> <br> Enter in the url: <input type="text" name="url"> <br> <br> category: <select name="category" size="1"> <option selected value="java">java</option> <option value="ejb">ejb</option> <option value="servlet">servlet</option> <option value="jsp">jsp</option> <option value="jdbc">jdbc</option> </select> <br> <br> Description: <textarea rows="4" cols='42' name="desc"></textarea> <br> <br> Search engines: <input type="checkbox" name="yahoo" value="T">Yahoo <input type="checkbox" name="google" value="T" CHECKED>Google <input type="checkbox" name="altavista" value="T">Altavista <br> <br> <input type="submit" name="submit" value="Go"> </form> </body> </html> <html> <head> <!-- Example5 --> <title>fullform.jsp</title> </head> <body> <h1> Website submission form </h1> <form action="fullformconfirm.jsp" method="post"> Enter in the website name: <input type="text" name="website"> <br> <br> Enter in the url: <input type="text" name="url"> <br> <br> category: <select name="category" size="1"> <option selected value="java">java</option> <option value="ejb">ejb</option> <option value="servlet">servlet</option> <option value="jsp">jsp</option> <option value="jdbc">jdbc</option> </select> <br> <br> Description: <textarea rows="4" cols='42' name="desc"></textarea> <br> <br> Search engines: <input type="checkbox" name="yahoo" value="T">Yahoo <input type="checkbox" name="google" value="T" CHECKED>Google <input type="checkbox" name="altavista" value="T">Altavista <br> <br> <input type="submit" name="submit" value="Go"> </form> </body> </html>

    55. Fullformconfirm.jsp in notes When you run fullform, and fill in fields, fullformconfirm will acknowledge data entry <html> <head> <!-- Example4 --> <title>fulformconfirm.jsp</title> </head> <body> <font face=verdana size=3> Thank you for your submission, it has been successfully received: <br><br> <% String sName = request.getParameter("website"); String sUrl = request.getParameter("url"); String sCategory = request.getParameter("category"); String sDesc = request.getParameter("desc"); String sGoogle = request.getParameter("google"); String sYahoo = request.getParameter("yahoo"); String sAltavista = request.getParameter("altavista"); %> Name:<%=sName%><br> Url:<%=sUrl%><br> Desc:<%=sDesc%><br> Category:<%=sCategory%><br> Desc:<%=sDesc%><br> Google:<%=sGoogle%><br> Yahoo:<%=sYahoo%><br> Altavista:<%=sAltavista%><br> </font> </body> </html> <html> <head> <!-- Example4 --> <title>fulformconfirm.jsp</title> </head> <body> <font face=verdana size=3> Thank you for your submission, it has been successfully received: <br><br> <% String sName = request.getParameter("website"); String sUrl = request.getParameter("url"); String sCategory = request.getParameter("category"); String sDesc = request.getParameter("desc"); String sGoogle = request.getParameter("google"); String sYahoo = request.getParameter("yahoo"); String sAltavista = request.getParameter("altavista"); %> Name:<%=sName%><br> Url:<%=sUrl%><br> Desc:<%=sDesc%><br> Category:<%=sCategory%><br> Desc:<%=sDesc%><br> Google:<%=sGoogle%><br> Yahoo:<%=sYahoo%><br> Altavista:<%=sAltavista%><br> </font> </body> </html>

    56. Beans The useBean action gives the bean a name and the getProperty action can be used to insert a property value directly into your JSP. Here it is the src attribute from an html <img> element. The way this bean works, a new cartoon is loaded on each access.

    57. Beans & JSP, another example: The java (bean) class package beanex; public class UserData { String username; String email; int age; public UserData(){ username="xyz";email="abc@yahoo.com";age=21;} public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ){age = value;} public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; }}

    58. JavaBeans   A Javabean is a special type of class that has a number of methods. The JSP page can call these methods so can leave most of the code in these Javabeans. For example, if you wanted to make a feedback form that automatically sent out an email. By having a JSP page with a form, when the visitor presses the submit button this sends the details to a Javabean that sends out the email. This way there would be no code in the JSP page dealing with sending emails (JavaMail API) and your Javabean could be used in another page (promoting reuse).   To use a Javabean in a JSP page use the following syntax: <jsp : usebean id = " ...." scope = "application" class = "com..." /> The following is a list of Javabean scopes: page - valid until page completes. request - bean instance lasts for the client request session - bean lasts for the client session. application - bean instance created and lasts until application ends.

    59. About the java It is a bean: it has a default constructor get/set methods for the fields Belongs to a package (beanex)

    60. Index.html to get us started <html> <body> Welcome, <A HREF="GetName.html">Start here</A> </body> </html>

    61. Getname.html --- a form <HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

    62. A savename.jsp which uses a bean <jsp:useBean id="user" class="beanex.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML>

    63. The java bean package certy.example; public class UserInfoBean { String username; String password; int pin; public void setUserName( String value ) { username = value; } public void setUserPass( String value ) { password = value; } public void setUserPIN( int value ) { pin = value; } public String getUserName() { return username; } public String getUserPass() { return password; } public int getUserPIN() { return pin; }}

    64. Nextpage.html which uses the same bean <jsp:useBean id="user" class="beanex.UserData" scope="session"/> <HTML> <BODY> You entered<BR> Name: <%= user.getUsername() %><BR> Email: <%= user.getEmail() %><BR> Age: <%= user.getAge() %><BR> </BODY> </HTML>

    65. deployment In webapps place a directory for this application. (I called mine getnamebean).

    66. Deployment continued Drop the html and jsp files into this directory. The directory images is empty and META-INF contains a manifest which can be omitted.

    67. Deployment continued: WEB-INF contents

    69. SaveName

    70. NextPage

    71. More about deployment directories Src is optional, it contains the java bean source. Lib is empty, but could contain the jar file for the class(es) needed. Classes contains a directory called beanex which contains UserData.class

    72. Web.xml is also optional <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <!– this is a comment: no special configuration required --> </web-app>

    73. FormBean:display form <HTML> <BODY> <FORM METHOD=POST ACTION="SaveFormData.jsp"> Enter your name : <INPUT TYPE=TEXT NAME=userName SIZE=20><BR> Enter a password : <INPUT TYPE=PASSWORD NAME=userPass SIZE=20><BR> Enter PIN : <INPUT TYPE=TEXT NAME=userPIN SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

    74. A do-nothing jsp <jsp:useBean id="user" class="certy.example.UserInfoBean" scope="session" /> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF="DisplayFormData.jsp">Display Entered Data.</A> </BODY> </HTML>

    75. Displaying the data stored in the bean <jsp:useBean id="user" class="certy.example.UserInfoBean" scope="session"/> <HTML> <BODY> You entered : <BR/> Name: <%= user.getUserName() %><BR/> Password: <jsp:getProperty name="user" property="userPass" /><BR/> PIN: <%= user.getUserPIN() %><BR/> </BODY> </HTML>

    76. A variation

    77. Last jsp

    78. The same java bean package beanex; public class UserData { String username; String email; int age; public UserData(){ username="xyz";email="abc@yahoo.com";age=21;} public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; }}

    79. Helloworld.jsp (in root directory of tomcat) <html> <head> <title>My first JSP page </title> </head> <body> <%@ page language="java" %> <% out.println("Hello World"); %> </body> </html>

    80. Running Hello.jsp Place it in an appropriate directory, like tomcat/root

    81. Text examples page off your Tomcat server

    82. Click on examples links to run http://localhost:8080/ora/ch5/easy.jsp

    83. Easy.jsp source <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

    84. JSP elements There are 3 types of elements: directive, action and scripting. EL (expression language) might be treated as a fourth type.

    85. Directives JSP begin with a directive indicating page content type: <%@ page contentType="text/html" %> Text/html, text/plain and text/xml are some possible attributes. The next line of easy.jsp specifies a custom tag library: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> Jsp directives have format <%@ content%> and are processed at translation time.

    86. Comments Comments have the form: <%-- put comment here --%> JSP elements like directives and comments do not go to the browser.

    87. Template text Besides JSP elements, a JSP page may contain html, xml or any markup language content. This is called template text and it is sent to the browser (after compilation of JSP elements and re-assembly) as is. The JSP container doesn’t process or parse this content.

    88. Action Elements A JSP may display shopping cart, search results, personalized news or bulletin board messages which are dynamically generated and specific to a client. An action is executed when the page is requested. (Request processing phase). The only action element in easy.jsp is <c:out value=“${1+2+3}” />

    89. Action Elements If the action element has a body, then it will have an opening tag (possibly with attribute/value pairs), a body, and a closing tag. If there is no body, then shorthand notation can be used as in the previous example, in a syntax equivalent to xml. The action element has no spaces, and consists of a prefix:name pair. The prefix is defined in the tag library directive and is the prefix that will be used for this library. The taglib’s URI is used by the container to find the information needed for processing.

    90. Action Elements There are standard, custom and JSTL actions. Standard actions are part of the jsp specification and require no tag library. (text pg 53 has a table). JSP specification allows for definition of custom actions as well. JSTL is meant to obviate the need for custom actions for mundane tasks and includes categories Core (control processing and imports), XML processinf, internationalization and ofrmatting, SQL database actions, and functions.

    91. JSTL EL EL start with ${ delimiter and end with } Literals, booleans, strings, null keyword and variables are supported. There are a number of EL implicit variables, too, like pageScope, param, header. (pg 56 table.) Special characters must appear in quotes. Variables are typed, as in Java.

    92. Standard operators may appear. These have some variations: / or div % or mod <= or le == or eq && or and ! or not And so on (table in text pg 56-57)

    93. Implicit Objects So far we know that the developer can create Javabeans and interact with Java objects. There are several objects that are automatically available in JSP called implicit objects.   The implicit objects are   Variable Of type Request Javax.servlet.http.httpservletrequest Response Javax.servlet.http. httpservletresponse Out Javax.servlet.jsp.JspWriter Session Javax.servlet.http.httpsession PageContent Javax.servlet.jsp.pagecontext Application Javax.servlet.http.ServletContext Config Javax.servlet.http.ServletConfig Page Java.lang.Object  

    94. objects Page object   Represents the JSP page and is used to call any methods defined by the servlet class.   Config object   Stores the Servlet configuration data.   Request object   Access to information associated with a request. This object is normally used in looking up parameter values and cookies.   <% String devStr = request.getParameter("dev"); %> Development language = <%= devStr %>   This code snippet is storing the parameter "dev" in the string devStr. The result is displayed underneath.

    95. Some examples from text and tutorials: a loop example For the next example, we will make use of the different tags we have learnt. This example will declare two variables; one string used to stored the name of a website and an integer called counter that displays the number of times the page has been accessed. There is also a private method declared to increment the counter. The website name and counter value are displayed.

    96. Jsp example 2 <HTML> <HEAD> <!-- Example2 --> <TITLE> JSP loop</TITLE> </HEAD> <BODY> <font face=verdana color=darkblue> JSP loop <BR> <BR> <%! public String writeThis(int x) { String myText=""; for (int i = 1; i < x; i++) myText = myText + "<font size=" + i + " color=darkred face=verdana>JSP Tutorial</font><br>" ; return myText; } %> This is a loop example from the <br> <%= writeThis(8) %> </font> </BODY> </HTML> <HTML> <HEAD> <!-- Example2 --> <TITLE> JSP loop</TITLE> </HEAD> <BODY> <font face=verdana color=darkblue> JSP loop <BR> <BR> <%! public String writeThis(int x) { String myText=""; for (int i = 1; i < x; i++) myText = myText + "<font size=" + i + " color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br>" ; return myText; } %> This is a loop example from the <br> <%= writeThis(8) %> </font> </BODY> </HTML><HTML> <HEAD> <!-- Example2 --> <TITLE> JSP loop</TITLE> </HEAD> <BODY> <font face=verdana color=darkblue> JSP loop <BR> <BR> <%! public String writeThis(int x) { String myText=""; for (int i = 1; i < x; i++) myText = myText + "<font size=" + i + " color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br>" ; return myText; } %> This is a loop example from the <br> <%= writeThis(8) %> </font> </BODY> </HTML>

    97. Running loop.jsp

    98. Get client’s computer information <html>   <head> <!-- Example5 --> <title>clientinfo.jsp</title>   </head> <body> Client computer details: <br><br> <b>Ip address</b>: <br> <%=request.getRemoteAddr()%> <br><br> <b>Computer name</b>: <br> <%=request.getRemoteHost()%> <br><br> </body> </html>

    99. Clientinfo.jsp

    100. Tomcat’s example jsp files Tomcat comes with a number of JSP examples in a directory: Web-apps/jsp-examples These can be run by entering http://IP:port/jsp-examples/subdir/file.jsp On my IP/tomcat server, it would be http://csci345.oneonta.edu:8080/jsp-examples/file.jsp

    101. JSP examples on Tomcat http://localhost:8080/jsp-examples/checkbox/check.html

    102. submit

    103. A get date example: http://localhost:8080/jsp-examples/dates/date.jsp

    104. http://localhost:8080/jsp-examples/colors/colrs.jsp

    105. Using Javabeans in J2EE Design.   If you thought that Javabeans were only useful in doing Swing Java applications then you are wrong.   To minimise the (presentation logic) code in your JSP, Javabeans are used to produce reusable methods.   The JSP specification provides clear ways of using Javabeans in JSP pages.

    106. JavaBeans JavaBeans are java classes satisfying the bean specification: Must have a no argument constructor Package name is recommended Properties (fields) are accessed via get() and set() methods Should implement serializable interface

    107. JavaBeans –an example package something; public class Name implements java.io.Serializable { private String theName; public Name(){theName=“Bob”;} public void setName(String n){theName=n;} public String getName(){return theName;} }

    108. Cartoon JSP using a bean: http://localhost:8080/ora/ch6/cartoon.jsp <html> <head> <title>A dose of Dilbert</title> </head> <body bgcolor="white"> <h1>A dose of Dilbert</h1> <jsp:useBean id="cartoon" class="com.ora.jsp.beans.motd.CartoonBean" /> <img src="images/<jsp:getProperty name="cartoon" property="fileName" />"> </body> </html>

    110. Cartoon.jsp source <html> <head> <title>A dose of Dilbert</title> </head> <body bgcolor="white"> <h1>A dose of Dilbert</h1> <jsp:useBean id="cartoon" class="com.ora.jsp.beans.motd.CartoonBean" /> <img src="images/<jsp:getProperty name="cartoon" property="fileName" />"> </body> </html>

    111. Stealing a JSP example from the text http://localhost:8080/my-jsp/cartoon.jsp Need to copy images directory and tags from this chapter examples to my-jsp directory structure.

    112. Using JSP tags There are four main tags: Declaration tag Expression tag Directive tag Scriptlet tag Action tag

    113. Declaration tag ( <%! %> ) This tag allows the developer to declare variables or methods. Before the declaration you must have <%! At the end of the declaration, the developer must have %>   Code placed in this tag must end in a semicolon ( ; ).   Declarations do not generate output so are used with JSP expressions or scriptlets.   For Example,   <%!   private int counter = 0 ; private String get Account ( int accountNo) ; %>

    114. Expression tag ( <%= %>)   This tag allows the developer to embed any Java expression and is short for out.println().   A semicolon ( ; ) does not appear at the end of the code inside the tag.   For example, to show the current date and time.     Date : <%= new java.util.Date() %>

    115. Directive tag ( <%@ directive ... %>)   A JSP directive gives special information about the page to the JSP Engine.   There are three main types of directives:   1)     page - processing information for this page. 2)     Include - files to be included. 3)     Tag library - tag library to be used in this page.   Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the page.

    116. Directives 1.     Page directive This directive has 11 optional attributes that provide the JSP Engine with special processing information. The following table lists the 11 different attributes with a brief description:  

    117.    Include directive   Allows a JSP developer to include contents of a file inside another. Typically include files are used for navigation, tables, headers and footers that are common to multiple pages.   Two examples of using include files:   This includes the html from privacy.html found in the include directory into the current jsp page.  <%@ include file = "include/privacy.html" %>  or to include a naviagation menu (jsp file) found in the current directory.   <%@ include file = "navigation.jsp" %>  Include files are discussed in more detail in the later sections of this tutorial.

    118.      Tag Lib directive   A tag lib is a collection of custom tags that can be used by the page.   <%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>   Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complex server side code from web designers.   This topic will be covered in the Advanced JSP tutorial at visualbuilder.com

    119. Scriptlet tag ( <% ... %> ) Between <% and %> tags, any valid Java code is called a Scriptlet. This code can access any variable or bean declared. For example, to print a variable. <% String username = "visualbuilder" ; out.println ( username ) ;   %>

    120. Action tag     There are three main roles of action tags :   1)     enable the use of server side Javabeans 2)     transfer control between pages 3)     browser independent support for applets.        

    121. Text chapter 7

    122. Custom Action for a bean: classpath environment variable to compile javax.servlet.jsp classes C:\xerces-j-bin.2.7.0\xerces-2_7_0\xercesimpl.jar;C:\xerces-j-bin.2.7.0\xerces-2_7_0\resolver.jar;C:\jakarta-tomcat-5.5.10\common\lib\activation.jar;C:\jakarta-tomcat-5.5.10\common\lib\mail.jar;c:\program files\java\jdk1.5.0_03\bin;c:\progra~1\java\jdk1.5.0_03\lib;C:\Progra~1\Java\jdk1.5.0_03\bin;c:\soap\soap\lib\soap.jar;C:\jakarta-tomcat-5.5.10\webapps\ROOT\WEB-INF\classes;c:\jakart~1.10\common\lib;c:\jakart~1.10\common\lib\jsp-api.jar;c:\jakart~1.10\common\lib\servle~1.jar

    123. Custom Action for a bean: a simple bean package beanex2; public class SomeBean{ String field; String message; public SomeBean(){ message="Hello"; field="nobody"; } public void setField(String x){ field=x; } public String getMessage(){ return message+field;} }

    124. Custom Action for a bean: java TagHandler class package beanex2; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class TagExample extends SimpleTagSupport{ private SomeBean sb= new SomeBean(); private String field; public void setField(String fvalue){ field=fvalue;} public void doTag() throws IOException{ sb.setField(field); JspWriter out =getJspContext().getOut(); out.println(sb.getMessage()); } }

    125. Compile the java files C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>javac beanex2\TagExample.java C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>

    126. sample tld files from ora (in notes below also) <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>examples</short-name> <uri>C:\jakarta-tomcat-5.5.10\webapps\myfolder\WEB-INF\examples</uri> <description> A simple tab library for the examples </description> <!-- A simple Tag --> <!-- foo tag --> <tag> <name>foo</name> <tag-class>examples.FooTag</tag-class> <tei-class>examples.FooTagExtraInfo</tei-class> <body-content>JSP</body-content> <description> Perform a server side action; uses 3 mandatory attributes </description> <attribute> <name>att1</name> <required>true</required> </attribute> <attribute> <name>att2</name> <required>true</required> </attribute> <attribute> <name>att3</name> <required>true</required> </attribute> </tag> </taglib> <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>examples</short-name> <uri>C:\jakarta-tomcat-5.5.10\webapps\myfolder\WEB-INF\examples</uri> <description> A simple tab library for the examples </description> <tag> <name>ShowSource</name> <tag-class>examples.ShowSource</tag-class> <description> Display JSP sources </description> <attribute> <name>jspFile</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!-- A simple Tag --> <!-- foo tag --> <tag> <name>foo</name> <tag-class>examples.FooTag</tag-class> <tei-class>examples.FooTagExtraInfo</tei-class> <body-content>JSP</body-content> <description> Perform a server side action; uses 3 mandatory attributes </description> <attribute> <name>att1</name> <required>true</required> </attribute> <attribute> <name>att2</name> <required>true</required> </attribute> <attribute> <name>att3</name> <required>true</required> </attribute> </tag> </taglib><?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>examples</short-name> <uri>C:\jakarta-tomcat-5.5.10\webapps\myfolder\WEB-INF\examples</uri> <description> A simple tab library for the examples </description> <tag> <name>ShowSource</name> <tag-class>examples.ShowSource</tag-class> <description> Display JSP sources </description> <attribute> <name>jspFile</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!-- A simple Tag --> <!-- foo tag --> <tag> <name>foo</name> <tag-class>examples.FooTag</tag-class> <tei-class>examples.FooTagExtraInfo</tei-class> <body-content>JSP</body-content> <description> Perform a server side action; uses 3 mandatory attributes </description> <attribute> <name>att1</name> <required>true</required> </attribute> <attribute> <name>att2</name> <required>true</required> </attribute> <attribute> <name>att3</name> <required>true</required> </attribute> </tag> </taglib>

    127. Chapter 15 JSP & XML You’ll need to copy jstl.jar plus the text’s tags directory and mytags.tld to appropriate places in your jsp directory.

    128. A jsp containing xml Remember, jsp may contain any markup language, not just html In this example, the jsp contains names, ids and emails in xml. We use an xsl file (import) to generate an html page from the xml.

    129. Emails_html.jsp <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>Email List</title> </head> <body bgcolor="white"> <c:import url="emailtable.xsl" var="stylesheet" /> <x:transform xslt="${stylesheet}"> <?xml version="1.0" encoding="ISO-8859-1"?> <students> <student id="123"> <first-name>Katie</first-name> <last-name>Higgins</last-name> <email>HigginKM</email> </student> …. </students> </x:transform> </body> </html> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>Email List</title> </head> <body bgcolor="white"> <c:import url="emailtable.xsl" var="stylesheet" /> <x:transform xslt="${stylesheet}"> <?xml version="1.0" encoding="ISO-8859-1"?> <students> <student id="123"> <first-name>Katie</first-name> <last-name>Higgins</last-name> <email>HigginKM</email> </student> <student id="456"> <first-name>Aimee</first-name> <last-name>Wolons</last-name> <email>WoloAM95</email> </student> <student id="789"> <first-name>Matthew</first-name> <last-name>Becker</last-name> <email>BeckMJ82</email> </student> </students> </x:transform> </body> </html> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>Email List</title> </head> <body bgcolor="white"> <c:import url="emailtable.xsl" var="stylesheet" /> <x:transform xslt="${stylesheet}"> <?xml version="1.0" encoding="ISO-8859-1"?> <students> <student id="123"> <first-name>Katie</first-name> <last-name>Higgins</last-name> <email>HigginKM</email> </student> <student id="456"> <first-name>Aimee</first-name> <last-name>Wolons</last-name> <email>WoloAM95</email> </student> <student id="789"> <first-name>Matthew</first-name> <last-name>Becker</last-name> <email>BeckMJ82</email> </student> </students> </x:transform> </body> </html>

    130. Emailtable.xsl (in notes,too) <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="students"> <table border="1" width="100%"> <tr> <th>ID</th> <th>Student Name</th> <th>Email</th> </tr> <xsl:for-each select="student"> <tr> <td> <xsl:value-of select="@id"/> </td> <td> <xsl:value-of select="last-name"/>, <xsl:value-of select="first-name"/> </td> <td> <xsl:value-of select="email"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="students"> <table border="1" width="100%"> <tr> <th>ID</th> <th>Student Name</th> <th>Email</th> </tr> <xsl:for-each select="student"> <tr> <td> <xsl:value-of select="@id"/> </td> <td> <xsl:value-of select="last-name"/>, <xsl:value-of select="first-name"/> </td> <td> <xsl:value-of select="email"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="students"> <table border="1" width="100%"> <tr> <th>ID</th> <th>Student Name</th> <th>Email</th> </tr> <xsl:for-each select="student"> <tr> <td> <xsl:value-of select="@id"/> </td> <td> <xsl:value-of select="last-name"/>, <xsl:value-of select="first-name"/> </td> <td> <xsl:value-of select="email"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>

    131. In tomcat

    132. Another xml/xsl example in jsp In the notes I placed a jsp containing xml markup for the courses I teach (titles, numbers, and texts) I created a stylesheet to traverse this xml and return course titles, numbers and so on to populate an html table <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>About my schedule</title> <body bgcolor="white"> <c:import url="myschedule.xsl" var="stylesheet" /> <x:transform xslt="${stylesheet}"> <?xml version = "1.0"?> <courses> <CSCourse> <coursetitle> Internet programming </coursetitle> <number>CSCI 345</number> <books> <book> <booktitle> Java Server Pages </booktitle> <author>Hans Bergsten</author> </book> <book> <booktitle> Servlet programming </booktitle> <author>Jason Hunter</author> </book> <book> <booktitle> XML </booktitle> <author>Dietel</author> </book> </books> </CSCourse> <CSCourse> <coursetitle> Programming Fundamentals in Java 2 </coursetitle> <number>CSCI 116</number> <books> <book> <booktitle> Java How to Program: Third Edition </booktitle> <author>Deitel</author> </book> </books> </CSCourse> <CSCourse> <coursetitle>Numerical Computing</coursetitle> <number>CSCI 321</number> <books> <book><booktitle>Numerical Mathematics and Computing</booktitle> <author>Cheney and Kincaid</author> </book> </books> </CSCourse> <CSCourse> <coursetitle>Assembly Programming</coursetitle> <number>CSCI 231</number> <books><book><booktitle>Assembly Language for Intel-based computers</booktitle> <author>Chip Irvine</author> </book> </books> </CSCourse> </courses> </x:transform> </body> </html><%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>About my schedule</title> <body bgcolor="white"> <c:import url="myschedule.xsl" var="stylesheet" /> <x:transform xslt="${stylesheet}"> <?xml version = "1.0"?> <courses> <CSCourse> <coursetitle> Internet programming </coursetitle> <number>CSCI 345</number> <books> <book> <booktitle> Java Server Pages </booktitle> <author>Hans Bergsten</author> </book> <book> <booktitle> Servlet programming </booktitle> <author>Jason Hunter</author> </book> <book> <booktitle> XML </booktitle> <author>Dietel</author> </book> </books> </CSCourse> <CSCourse> <coursetitle> Programming Fundamentals in Java 2 </coursetitle> <number>CSCI 116</number> <books> <book> <booktitle> Java How to Program: Third Edition </booktitle> <author>Deitel</author> </book> </books> </CSCourse> <CSCourse> <coursetitle>Numerical Computing</coursetitle> <number>CSCI 321</number> <books> <book><booktitle>Numerical Mathematics and Computing</booktitle> <author>Cheney and Kincaid</author> </book> </books> </CSCourse> <CSCourse> <coursetitle>Assembly Programming</coursetitle> <number>CSCI 231</number> <books><book><booktitle>Assembly Language for Intel-based computers</booktitle> <author>Chip Irvine</author> </book> </books> </CSCourse> </courses> </x:transform> </body> </html>

    133. Xsl in notes See notes below for the stylesheet <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="courses"> <table border="1" width="100%"> <tr> <th>Course</th> <th>Number</th> <th>Texts</th> </tr> <xsl:for-each select="CSCourse"> <tr> <td> <xsl:value-of select="coursetitle"/> </td> <td> <xsl:value-of select="number"/> </td> <td> <span class = "node">books</span> are: <xsl:apply-templates select = "books/node()"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet> <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="courses"> <table border="1" width="100%"> <tr> <th>Course</th> <th>Number</th> <th>Texts</th> </tr> <xsl:for-each select="CSCourse"> <tr> <td> <xsl:value-of select="coursetitle"/> </td> <td> <xsl:value-of select="number"/> </td> <td> <span class = "node">books</span> are: <xsl:apply-templates select = "books/node()"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>

    134. http://csci345.oneonta.edu:8080/myfolder/schedule.jsp

    135. Scriptlets: chapter 16 A random color function: String randomColor() { java.util.Random random = new java.util.Random(); int red = (int) (random.nextFloat() * 255); int green = (int) (random.nextFloat() * 255); int blue = (int) (random.nextFloat() * 255); return "#" + Integer.toString(red, 16) + Integer.toString(green, 16) + Integer.toString(blue, 16); }

    136. A random color jsp: generates an html table with random colors: entire jsp in notes <html> <head> <title>Random Color</title> </head> <body bgcolor="white"> <h1>Random Color</h1> <table border="1" width="100%"> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> </table> </body></html> <%@ page language="java" contentType="text/html" %> <%! String randomColor() { java.util.Random random = new java.util.Random(); int red = (int) (random.nextFloat() * 255); int green = (int) (random.nextFloat() * 255); int blue = (int) (random.nextFloat() * 255); return "#" + Integer.toString(red, 16) + Integer.toString(green, 16) + Integer.toString(blue, 16); } %> <html> <head> <title>Random Color</title> </head> <body bgcolor="white"> <h1>Random Color</h1> <table border="1" width="100%"> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> </table> </body> </html> <%@ page language="java" contentType="text/html" %> <%! String randomColor() { java.util.Random random = new java.util.Random(); int red = (int) (random.nextFloat() * 255); int green = (int) (random.nextFloat() * 255); int blue = (int) (random.nextFloat() * 255); return "#" + Integer.toString(red, 16) + Integer.toString(green, 16) + Integer.toString(blue, 16); } %> <html> <head> <title>Random Color</title> </head> <body bgcolor="white"> <h1>Random Color</h1> <table border="1" width="100%"> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> <td bgcolor="<%= randomColor() %>" width="100" height="100"> </td> </tr> </table> </body> </html>

    137. In tomcat: http://csci345.oneonta.edu/myfolder/colors.jsp

    138. Init and destroy (see servlet notes) used in a jsp <%@ page language="java" contentType="text/html" %> <%@ page import="java.util.Date" %> <%! Date orig; int globalCounter = 0; public void jspInit(){orig=new Date();} public void jspDestroy(){ ServletContext context=getServletConfig().getServletContext(); context.log("greeting.jsp visited"+globalCounter+"times between" +orig+"and"+(new Date())); } private String getGreeting() { Date now = new Date(); String greeting = now.toString(); if (now.getHours() < 12) { greeting +="Good morning"; } else if (now.getHours() < 18) { greeting += "Good day"; } else { greeting += "Good evening"; } return greeting; } %>

    139. The rest of greeting.jsp <html> <head> <title>Using several techniques</title> </head> <body bgcolor="white"> <%= getGreeting() %> <% if (request.getParameter("name") == null) { %> stranger! <% } else { %> partner! <% } %> <p>How are you?</p> <% String userAgent = request.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") != -1) { %> You're using Internet Explorer. <% } else if (userAgent.indexOf("Mozilla") != 1) { %> You're probably using Netscape. <% } else { %> You're using a browser I don't know about. <% } %> <p>This page has been visited: <%= ++globalCounter %> times since <%= orig %>.</p> </body> </html>

    140. csci345.oneonta.edu:8080/myfolder/greeting.jsp

More Related