Hello JSP

We now transition from servlet examples to JSP examples. One of the shortcomings of any servlet that produces nontrivial output is that they often contain embedded HTML tags locked up within Java classes where web designers cannot get to them. JSP is designed to improve this situation: instead of embedding HTML within Java code, it embeds Java code within HTML pages. (And, as we’ll see, JSP 2.0 and the Java Standard Tag Libraries dramatically reduce the amount of Java code that must be intermixed with HTML.)

Example 20-4 is a simple JSP page that performs a function similar to the HelloNet servlet of Example 20-1. If invoked with a parameter named “name”, it simply greets the named user. If there is no parameter, it displays an HTML form to request the user’s name and then greets the user when the form is submitted.

Example 20-4 uses JSP 1.x, and the main thing to note about the example is that it consists of HTML code intermingled with Java code which is contained within pseudotags. Remember that JSP pages are compiled into servlet classes. <% and %> delimit blocks of Java code, which are inserted literally into the body of the servlet’s doGet( ) or doPost( ) method. Note that these “scriptlet” tags can contain code fragments that are not complete statements. A fragment may end in the middle of an if block, to be followed by HTML tags (which are inserted literally into the servlet’s output) and then followed by another <%...%> scriptlet that closes the if block.

The tag ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.