Friday, June 24, 2011

A sample JSP

We looked how servlet look here. Here, we are going to take a look at a sample JSP file and the contents of the file.

A JSP File Contents:

A JSP file can contain the following:
a. HTML contents
b. JavaScript
c. Java Code

Combining the features of the above 3 mentioned items; we get a powerful entity called the JSP. JSPs are used for the User Interface layer or the more colloquially called Front End layer of any J2EE application.

JSP Skeleton

Below is how a Skeleton JSP File would look like. (The file has to be saved as .jsp)
// Page Imports
<%@ page import = “ %>

// Tag Library References
<%@ taglib URI = “path to Taglib file” prefix = “xx” %>
// here xx refers to the prefix with which the tag library will be referred to

// HTML Head & Title Content

// Java Script Content

// HTML Body & Form Contents

Note: Java code can be placed within the <% %> tags in the body part of the JSP page within the Body tags.

As you can see, a JSP file is pretty straightforward. Also, an important point to note here is the fact that, not all of the entities mentioned above are mandatory. You can include or exclude any of the entities mentioned above, based on your requirement and convenience.

Tomcat will now convert the Java embedded in the JSP to the following:

// begin [file="/jsp/my_first_jsp.jsp";from=(7,3);to=(7,31)]
int val1 = 10, val2=5;
// end

It also generates this version of the try block, which differs slightly from the previous servlet code:

try {

if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_inited = true;
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this,
request, response,
"", true, 8192, true);

application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();

// HTML // begin [file="/jsp/my_first_jsp.jsp"...]
out.write("" +
"\r\n< html >\r\n< body >\r\n" +
"I Like Cars, Especially < b > Ferrari < / b >.

// end
// HTML // begin [file="/jsp/my_first_jsp.jsp";from=...]
out.write("\r\n ");

// end
// begin [file="/jsp/my_first_jsp.jsp";from=...]
out.print(val1 * val2);
// end
// HTML // begin [file="/jsp/my_first_jsp.jsp";from=...]

// end


As you can see, Tomcat now takes our val1 and val2 variables that were declared at the top of our JSP page and generates declarations as class variables in the servlet.

So, < % - val1 & val2 % > becomes


Once the conversion is complete, this servlet will be compiled and loaded to memory. Every call to invoke this JSP will make Tomcat compare the modification date of the loaded servlet with the date of the JSP. If it is the same, the compiled servlet is executed and contents displayed on screen. Else, if it sees that the JSP has changed, it will recompile the JSP and load the newly converted Servlet instead of the older version.

No comments:

Post a Comment