JSP is an extensible web technology that uses template data, custom elements, string languages, and server-side Java objects to return dynamic contents to a client.  Typically the template data or static data is HTML or XML elements. JSP is a text-based document capable of returning both static and dynamic content to a client browser. Static content and dynamic content can be intermixed. Static content can be HTML, XML, Text. Dynamic content could be Java code, displaying properties of JavaBeans.

A Simple JSP Page:
  Hello World!
 Current time is <%= new java.util.Date() %>

JSP Benefits

  • Content and display logic are separated
  • Simplify web application development with JSP, JavaBeans and custom tags
  • Supports software reuse through the use of components (JavaBeans, Custom tags)‏
  • Automatic deployment – Recompile automatically when changes are made to JSP pages à L
  • Easier to author web pages
  • Platform-independent

Why JSP over Servlet?

Servlets can do a lot of things, but it is pain to:

  • Use those println() statements to generate HTML page.
  • Maintain that HTML page

In JSP, there is no need for compiling, packaging,CLASSPATH setting.

How Does JSP Work?

When a HTTP request is mapped to a JSP page, it is handled by a special built-in servlet (that is provided by a container) that first checks whether the JSP page’s servlet is older than the JSP page. If it is, the container translates the JSP page into a servlet Java code and compiles the servlet code into servlet class.  And this is done automatically by the container.  This is one of the advantages of using JSP over servlet from deployment standpoint.

Translation/Compilation Phase

In this phase, a JSP page gets translated and compiled automatically if there is no complied class already.  So if you deploy your JSP page for the first time, or if you modified the JSP page, then translation and compilation will occur.  This is why sometimes you observe the response time takes a bit longer  when  you access a relatively sophisticated JSP page for the first time, because the container has to do translation and compilation before it can handle your request.  Usually in order to reduce this first-time delay, developers call their JSP pages at the time of deployment or in many cases the container might do that anyway.

Static Template data is transformed into code that will emit data into the stream. JSP elements are treated differently
  • Directives are used to control how Web container translates and executes JSP page
  • Scripting elements are inserted into JSP page’s servlet class
  • Elements of the form <jsp:xxx …/> are converted into method calls to JavaBeans components

Example: initdestroy.jsp

<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%--  Declare initialization and finalization methods using JSP declaration --%>
  private BookDBAO bookDBAO;
  public void jspInit() { 
    // retrieve database access object, which was set once per web application
    bookDBAO =
    if (bookDBAO == null)‏
        System.out.println("Couldn't get database.");
  public void jspDestroy() {     
    bookDBAO = null;

Comparing Servlet and JSP code


What happens in this code is pretty simple.  It basically receives a HTTP request, then create output stream object and write HTTP response to the output stream.

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

 * This is a simple example of an HTTP Servlet.  It responds to the GET
 * method of the HTTP protocol.
public class GreetingServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,
                       HttpServletResponse response)‏
                       throws ServletException, IOException

      PrintWriter out = response.getWriter();

      // then write the data of the response
      out.println("<html>" +

      // then write the data of the response
      out.println("<body  bgcolor=\"#ffffff\">" +
         "<img src=\"duke.waving.gif\">" +
         "<h2>Hello, my name is Duke. What's yours?</h2>" +
         "<form method=\"get\">" +
         "<input type=\"text\" name=\"username\" size=\"25\">" +
         "<p></p>" +
         "<input type=\"submit\" value=\"Submit\">" +
         "<input type=\"reset\" value=\"Reset\">" +
      String username = request.getParameter("username");
      // dispatch to another web resource
      if ( username != null && username.length() > 0 ) {
            RequestDispatcher dispatcher =
            if (dispatcher != null)‏
            dispatcher.include(request, response);

    public String getServletInfo() {
        return "The Hello servlet says hello.";



Now this is the Hello web application this time using JSP.  As you can see, JSP includes HTML tags so you are not creating HTML response in your Java code, instead they are part of JSP page.  Then some dynamic contents are created through embedded Java code within the JSP page.

<body bgcolor="white">
<img src="duke.waving.gif">
<h2>My name is Duke. What is yours?</h2>
<form method="get">
<input type="text" name="username" size="25">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
    String username = request.getParameter("username");
    if ( username != null && username.length() > 0 ) {
    <%@include file="response.jsp" %>


This is the web component, ResponseServlet,  that was dispatched from the GreetingServlet.

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

// This is a simple example of an HTTP Servlet.  It responds to the GET
// method of the HTTP protocol.
public class ResponseServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,
                       HttpServletResponse response)‏
                       throws ServletException, IOException{
        PrintWriter out = response.getWriter();

        // then write the data of the response
        String username = request.getParameter("username");
        if ( username != null && username.length() > 0 )
          out.println("<h2>Hello, " + username + "!</h2>");

    public String getServletInfo() {
        return "The Response servlet says hello.";


This the corresponding JSP page.  As you can see, as far as displaying is concerned, JSP is a much simpler to use.

<h2><font color="black">Hello, <%=username%>!</font></h2>

JSP “is” Servlet!

Just to reiterate how JSP and Servlet are closely related, I would say that JSP is in fact Servlet.

First JSP pages get translated into servlet class when they get deployed. Second, the scriptlet which is Java code within JSP page ends up being directly inserted into the jspService() method of the resulting servlet class without any modification.  Third, the implicit objects that are available to servlet programmers such as HttpSession object, ServletContext objects are also available to JSP page designers, JavaBeans developers, custom tag designers.


So this is the greeting.jsp’s corresponding servlet class that was created by the container.

package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;

public class greeting$jsp extends HttpJspBase {
  static {
  public greeting$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_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="/greeting.jsp";from=(38,4);to=(53,0)]
        out.write("\n\n<html>\n<head><title>Hello</title></head>\n<body bgcolor=\"white\">\n<img src=\"duke.waving.gif\"> \n<h2>My name is Duke. What is yours?</h2>\n\n<form method=\"get\">\n<input type=\"text\" name=\"username\" size=\"25\">\n<p></p>\n<input type=\"submit\" value=\"Submit\">\n<input type=\"reset\" value=\"Reset\">\n</form>\n\n");

      // end
      // begin [file="/greeting.jsp";from=(53,2);to=(56,0)]

           String username = request.getParameter("username");
            if ( username != null && username.length() > 0 ) {
      // end
      // HTML // begin [file="/greeting.jsp";from=(56,2);to=(57,4)]
        out.write("\n    ");

      // end
      // HTML // begin [file="/response.jsp";from=(38,4);to=(40,31)]
        out.write("\n\n<h2><font color=\"black\">Hello, ");

      // end
      // begin [file="/response.jsp";from=(40,34);to=(40,42)]
      // end

      // HTML // begin [file="/response.jsp";from=(40,44);to=(55,0)]

      // end
      // HTML // begin [file="/greeting.jsp";from=(57,37);to=(58,0)]

      // end
      // begin [file="/greeting.jsp";from=(58,2);to=(60,0)]

      // end
      // HTML // begin [file="/greeting.jsp";from=(60,2);to=(63,0)]

      // end
    } catch (Throwable t) {
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null)‏

Dynamic Content Generation Techniques in JSP

There are several dynamic contents generation techniques you can use.  And you choose these techniques depending on the size and complexity of your project.  And these techniques provide different levels of code reusability, maintenability, and robustness.

  1. Call Java code directly within JSP
  2. Call Java code indirectly within JSP
  3. Use JavaBeans within JSP
Similarly, there could some more techniques that can be used are:
  • Develop and use your own custom tags
  • Leverage 3rd-party custom tags or JSTL (JSP Standard Tag Library)‏
  • Follow MVC design pattern
  • Leverage proven Model2 frameworks

(1) Call Java code directly 

The least sophisticated method is to place all the Java code within a JSP page.  Place all Java code in JSP page. Suitable only for a very simple Web application.

  • hard to maintain
  • hard to reuse code
  • hard to understand for web page authors
  • Not recommended for relatively sophisticated Web applications
  • weak separation between contents and presentation

(2) Call Java code indirectly 

Now the next level of sophistication can be achieved by developing utility classes and then insert only the Java code need to invoke those utility classes while maintaining those utility class outside of the JSP page.

  • Develop separate utility classes
  • Insert into JSP page only the Java code needed to invoke the utility classes
  • Better separation of contents generation from presentation logic than the previous method
  • Better re usability and maintainability than the previous method
  • Still weak separation between contents and presentation, however

(3) Use JavaBeans

Now in the next level, you can develop those utility classes in the form of simple component, JavaBeans in this case.

  • Develop utility classes in the form of JavaBeans
  • Leverage built-in JSP facility of creating JavaBeans instances, getting and setting JavaBeans properties
  • Use JSP element syntax
  • Easier to use for web page authors
  • Better re usability and maintainability than the previous method

JSP Scripting Elements

Scripting elements let you insert raw Java code into the JSP page directly and this code will be in turn  inserted into the Servlet code that will be generated from the JSP page.

Lets you insert Java code into the servlet that will be generated from JSP page. Minimize the usage of JSP scripting elements in your JSP pages if possible. There are three forms.

  1. Expressions: <%= Expressions %>
  2. Scriptlets: <% Code %>
  3. Declarations: <%! Declarations %>

1. Expressions

During execution phase, expression is evaluated and converted into a String. The String is then Inserted into the servlet’s output stream directly. Results in something like out.println(expression)‏. Can use predefined variables (implicit objects) within expression.

  • <%= Expression %>  or // JSP 1.1
  • <jsp:expression>Expression</jsp:expression> // JSP2.0
  • Semi-colons are not allowed for expressions

2. Scriptlets

A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. When the scripting language is set to Java programming language, a scriptlet is transformed into a Java programming language statement fragment and is inserted into the service() method of the JSP page’s servlet. A programming language variable created within a scriptlet is accessible from anywhere within the JSP page.

  • <% Java code %>  or
  • <jsp:scriptlet> Java code</jsp:scriptlet>

3. Declarations

Used to define variables or methods that get inserted into the main body of servlet class. Outside of _jspSevice() method. Implicit objects like HttpSession are not accessible to declarations. Usually used with Expressions or Scriptlets. For initialization and cleanup in JSP pages, use declarations to override jspInit() and jspDestroy() methods.


  • <%! method or variable declaration code %>
  • <jsp:declaration> method or variable declaration code </jsp:declaration>

Including Contents in a JSP Page

Two mechanisms for including another Web resource in a JSP page

  1. include directive
  2. jsp:include element

1. JSP Include Directive

Is processed when the JSP page is translated into a servlet class. Effect of the directive is to insert the text contained in another file– either static content or another JSP page–in the including JSP page. Used to include banner content, copyright information, or any chunk of content that you might want to reuse in another page

Syntax and Example

  • <%@ include file=”filename” %>
  • <%@ include file=”banner.jsp” %>

2. jsp:include Element

Is processed when a JSP page is executed. Allows you to include either a static or dynamic resource in a JSP file. static:  its content is inserted into the calling JSP file. dynamic: the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page.

Syntax and example

  • <jsp:include page=”includedPage” />
  • <jsp:include page=”date.jsp”/>

Use include directive if the file changes rarely. It is faster than jsp:include. Use jsp:include for content that changes often. Use jsp:include if which page to include cannot be decided until the main page is requested

Three Types of Directives


Communicate page dependent attributes and communicate these to the JSP container

  • <%@ page import=”java.util.* %>


Used to include text and/or code at JSP page translation-time

  • <%@ include file=”header.html” %>


Indicates a tag library that the JSP container should interpret

  • <%@ taglib uri=”mytags” prefix=”codecamp” %>

Tagged with: JAVA

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.