Tuesday, April 26, 2011

Difference Between Servlets and JSP




A clear and important distinction to make about JSP is that coding one is nothing
like coding a Servlet. From what this chapter has explained, it might appear that
JSP is just a simple version of Servlets. In many respects JSP is in fact a simple
method of creating a text-producing Servlet; however, do not be fooled into
thinking this mindset is always true.As the chapter progresses, it will be clear that
JSP and Servlets are two very distinct technologies. Later, after custom tags are
introduced, the degree of separation between the two will seem even larger. The
use of JSP for easily making a Servlet really only applies in the simplest of cases.
To show how vastly different the code for a JSP can be from a Servlet, Listing
displays the code for the JSP equivalent of the HelloWorld Servlet

HelloWorld.jsp
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

They are quite different! You’ll recall the code for HelloWorld.java and
notice the two look nothing alike. The code for the JSP is actually identical to the
text generated by the HelloWorld Servlet, not the source code. Authoring an
HTML-generating JSP is as easy as just authoring the HTML. Compared to using
print() and println()methods in Servlets,the JSP approach is obviously easier.
This is why simple JSP are usually considered a quick method of creating text-
producing Servlets.
Deploying a JSP is also simpler; a Web Application automatically deploys any
JSP to a URL extension that matches the name of the JSP. Test out HelloWorld.jsp
by saving it in the base directory of the jspbook Web Application then browsing to
http://127.0.0.1/jspbook/HelloWorld.jsp

From looking at the results of the example, it certainly does appear Hello
World.jsp is a simple form of HelloWorld.java. What is not shown, but is very
important to understand, is that HelloWorld.jsp is also actually compiled into
equivalent Servlet code. This is done in what is called the translation phase of JSP
deployment and is done automatically by a container. JSP translation both is and
is not something of critical importance for a JSP developer to be aware of. JSP
translation to Servlet source code is important because it explains exactly how a
JSP becomes Java code. While it varies slightly from container to container, all
containers must implement the same JSP life cycle events. Understanding these
life cycle methods helps a JSP developer keep code efficient and thread-safe.
However, JSP translation is not of critical importance because it is always done
automatically by a container. Understanding what a container will do during the
translation phase is good enough to code JSP. Keeping track of the generated
Servlet source code is not a task a JSP developer ever has to do.
JSP translated to Servlet code can be found by looking in the right place for
a particular container. Tomcat stores this code in the /work directory of the
Tomcat installation. Generated code is never pretty, nor does it always have the
same name. Listing 3-2 was taken from HelloWorld$jsp.java in the /work/
localhost/jspbook directory. It is the Servlet code generated for HelloWorld.
jsp that Tomcat automatically compiled and deployed

Tomcat-Generated Servlet Code for HelloWorld.jsp
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;
public class HelloWorld$jsp extends HttpJspBase {
static {
}
public HelloWorld$jsp( ) {
}
private static boolean _jspx_inited = false;
public final void _jspx_init() throws
org.apache.jasper.runtime.JspException {
}
public void _jspService(HttpServletRequest request,
HttpServletResponse  response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String  _value = null;
try {
if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-
8859-1");
pageContext = _jspxFactory.getPageContext(this, request,
response,
"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
// HTML // begin
[file="/HelloWorld.jsp";from=(0,0);to=(8,0)]
out.write("<html>\r\n<head>\r\n<title>Hello
World!</title>\r\n</head>\r\n<body>\r\n<h1>Hello
World!</h1>\r\n</body>\r\n</html>\r\n");
// end
} catch (Throwable t) {
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (pageContext != null)
pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null)
_jspxFactory.releasePageContext(pageContext);
}
}
}



Do not bother trying to read through and understand the generated code.
The important point to understand is that a container handles a JSP as a Servlet
but does so behind the scenes
. This ties directly back to the greater point that JSP
are really just Servlets. The difference between the two technologies is not in the
life cycles or how a container manages them at runtime. The difference between
Servlets and JSP is the syntax they offer for creating the same functionality. With
JSP it is almost always simpler to create text-producing Servlets, but normal
Servlets are still best suited for sending raw bytes to a client or when complete
control is needed over Java source code.


JSP Basics

JavaServer Pages (JSP) and Servlets are complementary technologies for producing dynamic Web pages via Java. While Servlets are the foundation for serverside Java, they are not always the most efficient solution with respect to development time. Coding, deploying, and debugging a Servlet can be a tedious
task. Fixing a simple grammar or markup mistake requires wading through print() and  println() calls, recompiling the Servlet, and reloading a Web Application.Making a grammar or markup mistake is not hard, and the problem is compounded in complex Servlets. JSP complements Servlets by helping solve this problem and simplifying Servlet development.

JSP Life Cycle
Much like Servlets, understanding JSP requires understanding the simple life cycle that JSP follows. JSP follows a three-phase life cycle: initialization, service,and destruction, as shown in Figure This life cycle should seem familiar and is identical to the one described for Servlets .While a JSP does follow the Servlet  life cycle, the methods have different names. Initialization corresponds to the jspInit() method, service corresponds to the _jspService() method, and destruction corresponds to the jspDestroy() method. The three phases are all used the same as a Servlet and allow a JSP to
load resources, provide service to multiple client requests, and destroy loaded resources when the JSP is taken out of service.
JSP is designed specifically to simplify the task of creating text producing HttpServletobjects and does so by eliminating all the redundant parts of coding a Servlet. Unlike with Servlets there is no distinction between a normal JSP and one meant for use with HTTP. All JSP are designed to be used with HTTP and to generate dynamic content for the World Wide Web. The single JSP _jspService() method is also responsible for generating responses to all seven
of the HTTP methods. For most practical purposes a JSP developer does not need to know anything about HTTP, nor anything more than basic Java to code a dynamic JSP.