Java Server Pages and Servlet

Java servlet technology is an extremely powerful technology. However, when it is used to generate large, complex HTML code, it becomes a bit cumbersome.

In most servlets, a small piece of code is written to handle application logic and a large code is written using several out.printin() statements that handle output formatting (see Chapter 20). Since the codes for application logic and formatting are closely tied, it is difficult to separate and reuse portions of the code when a different logic or output format is required.

JSP separates the static presentation templates from the logic, to generate the dynamic content, by encapsulating it within external JavaBean components. These components are then instantiated and used in a JSP page using special tags and scriptlets. When the presentation template is changed by the web designer, the JSP engine recompiles the JSP page and reloads it in the Java Runtime Environment (JRE).

Another problem of servlets is that each time the servlet code is modified, it needs to be recompiled and the web server also needs to be restarted. The JSP engine takes care of all these issues automatically. Whenever a JSP code is modified, the JSP engine identifies it and translates it into a new servlet. The servlet code is then compiled, loaded, and instantiated automatically. The servlet remains in the memory and serves requests subsequently without any delay.

JSP uses technologies based on reusable component engineering such as JavaBean component architecture and Enterprise JavaBean (EJB) technology. So, JSP does not require significant developer expertise, like Java servlets. Consequently, in the application development life cycle, page designers can now play a major role. JSP pages can be moved easily across web servers and platforms, without any significant changes or effort.

For these reasons, web application developers turn towards JSP technology as an alternative to servlet technology.

1. Translation and Compilation

Every JSP page gets converted to a normal servlet behind the scene by the web container automatically. Figure 21.3: shows one such translation.

Each type of data in a JSP page is processed differently during the translation phase. The translation and compilation phases may result in errors. These errors (if any) are generated when a user requests the page for the first time.

The JSP engine returns a ParseException, if an error occurs during the translation phase. In such a case, the servlet source file will be empty or incomplete. The last incomplete line describes the cause of error in the JSP page. If an error occurs during the compilation phase, the JSP engine returns a JasperException and a message that describes the name of the JSP page’s servlet and the line that caused the error.

Now, let us take a specific example to understand this translation procedure. Consider the following JSP page. You may not understand the syntax used in this file. We shall discuss it in the rest of this chapter.

<html>

<head><title>Square table</title></head>

<body>

<table border=”1″>

<caption>Temperature Conversion chart</caption>

<tr><th>Celsius</th><th>Fahrenheit</th></tr>

<%

for(int c = 0; c <= 100; c+=20)               {

double f = (c*9)/5.0 + 32;

out.println(“<tr><td>” + c + “</td><td>” + f + “</td></tr>”);

}

%>

</table>

</body>

</html>

This is a simple JSP page that prints temperature conversion (from Celsius to Fahrenheit) chart. If you open this page in Google chrome, it looks as shown in Figure 21.4:

When you request this page for the first time, the JSP engine translates the JSP page into the following servlet source code ( temp_jsp.java created in tomcat_home\work\Catalina\localhost\ net\org\apache\jsp directory).

package org.apache.jsp;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;

public final class temp_jsp extends org.apache.jasper.runtime.HttpJspBase

implements org.apache.jasper.runtime.JspSourceDependent {

private static final javax.servlet.jsp.JspFactory _jspxFactory =

javax.servlet.jsp.JspFactory.getDefaultFactory();

private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

private javax.el.ExpressionFactory _el_expressionfactory;

private org.apache.tomcat.InstanceManager _jsp_instancemanager;

public java.util.Map<java.lang.String,java.lang.Long> getDependants() {

return _jspx_dependants;

}

public void _jspInit() {

_el_expressionfactory =

_jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).g

etExpressionFactory();

_jsp_instancemanager =

org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletC onfig());

}

public void _jspDestroy() {

}

public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)

throws java.io.IOException, javax.servlet.ServletException {

final javax.servlet.jsp.PageContext pageContext;

javax.servlet.http.HttpSession session = null; final

javax.servlet.ServletContext application;

final javax.servlet.ServletConfig config;

javax.servlet.jsp.JspWriter out = null;

final java.lang.Object page = this;

javax.servlet.jsp.JspWriter _jspx_out = null;

javax.servlet.jsp.PageContext _jspx_page_context = null;

try {

response.setContentType(”text/html”);

pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);

_jspx_page_context = pageContext; application =

pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

out.write(“<html>\r\n”);
out.write(“\t<head><title>Square table</title></head>\r\n”);
out.write(“\t<body>\r\n”);
out.write(“\t\t<table border=\”1\”>\r\n”);
out.write(“\t\t\t<caption>Temperature Conversion chart</caption>\r\n”);
out.write(“\t\t\t<tr><th>Celsius</th><th>Fahrenheit</th></tr>\r\n”);
out.write(“\t\t”);

for(int c = 0; c <= 100; c+=20){

double f = (c*9)/5.0 + 32;

out.println(“<tr><td>” + c + “</td><td>” + f + “</td></tr>”);

}

out.write(“\r\n”);

out.write(”\t\t</table>\r\n”);

out.write(”\t</body>\r\n”);

out.write(”</html>\r\n”);

} catch (java.lang.Throwable t) {

if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out;

if (out != null && out.getBufferSize() != 0)

try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) jspx_page_context.handlePageException(t);

else throw new ServletException(t);

}

} finally {

_jspxFactory.releasePageContext(_jspx_page_context);

}

}

}

The JSP page’s servlet class extends HttpJspBase, which in turn implements the Servlet interface. In the generated servlet class, the methods _jspinit(), _jspService(), and _jspDestroy() correspond to the servlet life cycle methods init(), serviced , and destroy(), respectively which were discussed in Chapter 20. The _jspService() method is responsible for serving client’s requests. JSP specification prohibits the overriding of the _jspService() method. However, the developers are allowed to override the _jspInit() and _jspDestroy() methods within their JSP pages, to initialize and shut down servlets, respectively.

By default, the servlet container dispatches the _jspService() method using a separate thread to process concurrent client requests, as shown in Figure 21.5:

The static HTML part is simply printed to the output stream associated with the servlet’s service() method. The code in <% and %> is copied in the _jspService() method.

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *