Servlet v JSP (Java Server Page). What is the difference?
Archive - Originally posted on "The Horse's Mouth" - 2013-02-06 16:58:13 - Graham EllisA servlet is a web program that generates output (normally HTML) and returns it to a browser.
A JSP (Java Server Page) is a page of HTML ... with some extra bits of code where programatic elements are added as it's returned to the browser
So on the surface, it looks like there's a fundamental difference. Internally, however, Tomcat converts your .jsp pages into servlets, by taking all the elements which are outside the extra bits and putting them into out.print statements in Java source, which is then compiled. So - in reallity - a .jsp is a servlet in disguise.
You can see this in action if you wish. Tomcat's work directory is used for the conversion to Java source, and the compiling into class files, of your servlets, and (by default) the source code is left there for you to look at if you wish. Here's an example of where to look - default configuration, application called "wetfeet", host "locathost", file called "together.jsp" ...
/usr/local/tomcat/work/Catalina/localhost/wetfeet/org/apache/jsp/together_jsp.java
Taking some examples, a line like
Here is the <%= number %> times table
converts to
out.write("Here is the ");
out.print( number );
out.write(" times table \n");
and
<% for (int k=1; k<=maxtimes; k++) {
int result = k * number; %>
<tr><td><%= k %></td><td><%= result %></td></tr>
<% } %>
converts to
for (int k=1; k<=maxtimes; k++) {
int result = k * number;
out.write("\n");
out.write("<tr><td>");
out.print( k );
out.write("</td><td>");
out.print( result );
out.write("</td></tr>\n");
}
Complete example - .jsp source [here] and the generated servlet source [here].
Example from today's private Apache htpd and Tomcat course, which has been tailored for this customer from our public httpd and Tomcat class.