A Java Server Page is a text file that looks like a regular HTML web page with embedded JSP code. This file is compiled into a Java servlet (similar to a CGI program) which runs on a web server.
JSP defines several tags or delimiters that are relevant to the JSP compiler:
- The delimiter set <%@ ... %> indicates a JSP server directive, such as a Java import directive to import class libraries.
- The delimiter set <%-- ... --%> indicates a JSP comment.
- The delimiter set <%! ... %> indicates a Java definition, such as a variable initialization or a method definition.
- The delimiter set <% ... %> indicates Java code that is to be executed.
- The delimiter set <%= ... %> indicates Java code that will ultimately emit a Java String. This code might name a String object, or a method that returns a String. Note that all objects in Java have a toString method that is called when a string is expected. So writing the JSP code <%Foo%> ultimately results in a call to Foo.toString, where Foo is the name of a Java object.
When the JSP page is compiled, the data in the server page is inserted into a skeleton Servlet class. Any functions defined in the server page become methods of the resulting class. HTML content is converted into a set of Java String literals. The servlet will send these HTML strings back to the clients browser, interspersed with the output of the toString methods discussed above.
When following the logic of a JSP page, you can think of the order of execution as being from top to bottom. For example, when a browser requests the page shown in Listing 1, the servlet corresponding to this page is activated. The servlet first constructs a String object named Hello. Then the servlet outputs the HTML code shown. When it gets to the delimiter set <%=Hello%>, it outputs the contents of the String object named Hello. Thus, the HTML sent to the browser looks like this:
<HTML> <BODY> <FONT COLOR=Red>Hello, world!</FONT> </BODY> </HTML>