For the benefit of complete beginners to JSP (who may or may not even be interested in databases), here is an example application written in JSP, an excerpt from Chapter 2 of ‘Java Web Database Application Development’:
A trivial JSP application: (Bogus) Stock Quoter
Our first app will consist of just two JSP files. When a user invokes a valid application URL from a browser without specifying the exact file (or servlet) name, the server will either display a directory listing or invoke a ‘welcome file’. Which file serves (or may serve, in order of precedence) as the welcome file depends on the defaults set by your vendor or overridden by the tags in the web.xml descriptor file that is standard for all Java-based web apps (more on web.xml later). Tomcat defaults the welcome filename to index.html or index.jsp. Therefore we use this latter name for our application’s entry-point file.
The first page will identify itself, then ask for the user to send a request back to the server, which will invoke the second file, which will be named BogusStockQuote01.jsp.
The application is deployed under the web application directory ‘BogusStockQuote01’.
Here is the source code for index.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" > <head> <title>index.jsp</title> </head> <body> <h3> This is BogusStockQuote01 index.jsp </H3> <p> <form action="BogusStockQuote01.jsp"> <label for="myRequest">Enter stock symbol here:</label> <input type="text" name="myRequest" value="" /> <input type="hidden" name="myUlteriorMotive" value="Greed" /> <input type="submit" value="Send JSP request" /> </form> </body> </html>
Notice a few things about this file:
• There is no Java code in it, not even a JSP tag. We could have named this file index.html.
• We use all of the standard structural elements of an HTML page here:
<html> <head> <title> </title> </head> <body> </body> </html>
• The page presents an HTML form for the user to enter data to be sent back to the server.
• The ‘method’ form attribute is omitted, so it defaults to ‘GET’; the other option is ‘POST’; more on the significance of this later.
• The HTML form invokes the other JSP page, BogusStockQuote01.jsp, via the Action attribute.
• The HTML form contains a few basic elements:
o A text <input> field, for the user to type something into, to be sent back to the server. This is the fundamental element of dynamic interactivity in HTML-based web applications.
o A <label> associated with the same text field. We could have just used some plain text and placed it ‘near’ the text field, but the <label> tag combined with the ‘for’ attribute having the same value as the name of the <input> item makes the association explicit and structural, rather than a concidence of physical placement (which may not be reliable, depending on the client’s browser and stylesheets applied to the content).
o A hidden field. As the term implies, this element is not displayed to the user, but is tracked behind the scenes and sent back to the server with the form data. Hidden fields are very useful for tracking surrogate keys, programming variables or other elements that shouldn’t clutter the user’s view, for controlling program logic on the client or server side, maintaining state etc. Hidden variables are not secure, however; they are viewable in plain text by the user who chooses to view the uninterpreted source code of any HTML page.
o A <submit> button. This is the familiar device for sending the all the form data back to the web/application server.
When the user clicks the submit button, the target of the form Action (the other JSP file) is invoked. This file contains a couple of JSP expressions (Java variables enclosed in the JSP expression tags <%= and %>, including a random double/decimal number between 0 and 100 for the bogus stock price to be quoted), which couldn’t be done with just a static HTML file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title> Bogus Stock Quote JSP 01</title> <h3> This is BogusStockQuote01.jsp </h3> <p> <h4> Current (bogus) price for stock symbol '<%=request.getParameter("myRequest")%>' is: $<%= (Math.random()*100) %>. </h4> <p> By the way, we have detected an evil ulterior motive ( <%= request.getParameter("myUlteriorMotive") %> ) in your request. <p> <h4> Try again! </h4> <form> <label for="myRequest">Enter stock symbol here.</label> <input name="myRequest" value="" type="text"> <input name="myUlteriorMotive" value="Gluttony" type="hidden"> <input value="Send JSP request" type="submit"> </form> </body> </html>
The first thing to notice about this page is that the value typed into the text field on the previous screen, as well as the identifier and value of the hidden variable, are displayed in the address bar of the browser:
This is because the form submitted the information as an HTTP GET request, no different from the simple URL request for the first page. In a GET request, any parameters and their values are appended to the URL. This can be a very useful technique, for example for bookmarking static pages that you wish to return to. When the number of arguments is large, or when tighter control over the progression of screens within a user session is desired, a POST request is preferred. With a POST request, parameters are not appended to the URL but are encapsulated in the body of the request, invisible to the user. GET is the default.
The next thing to notice about the page is that the HTML source code that reaches the browser is NOT identical to the original JSP file. J.S.P. stands for Java Server Pages. The file is interpreted and processed on the server before the final HTML-only result is sent back to the client’s browser.
In the present case, the server has made three substitutions based on JSP expression tags:
• <%= request.getParameter(“myRequest”) %>
…was resolved into ‘orkl’, just as the user typed it.
• <%= (Math.random() *100) %>
…returned ‘67.417326748’ (this time; the next call will return a completely different value).
• <%= request.getParameter(“myUlteriorMotive”) %>
…was resolved into ‘Greed’.
This example demonstrates the following principles:
• The tag <%= … %> is a Java Server Page directive indicating some processing to be done on the server side, substituting the result for the original text.
• The Java variable ‘request’ is one of a handful of implicit objects in JSP, objects that you the programmer may assume exist even though you didn’t declare them. Specifically, ‘request’ is the standard JSP object representation of the HTTP request as received from the client.
• The method ‘getParameter()’ is the standard means of retrieving single parameter values from an HTTP request. ‘myRequest’ and ‘myUlteriorMotive’ are the argument names used in the HTML form in index.jsp. Note that getParameter()makes no distinction between displayed and hidden input variables.
Both request and getParameter() are Java code elements. The request object is an instance of the class HttpServletRequest, and getParameter() is one of its standard methods. These elements belong to the Java Servlet environment, not to HTML. The JSP page is interpreted on the fly at runtime and compiled as a servlet. The servlet then generates and returns the result of its processing.
You should now practice writing and deploying these two JSP files, with your own desired variations, until you’ve got a solid ‘feel’ for how this works. Observe the results both as interpreted by your browser and in their raw page source code form.
Complete source code to all sample applications is bundled with the premium edition of the book. See the Welcome Page.