JSP Tutorial

JSP (Java Server Pages):

JSP refers to the Java server pages. Before starting the discussion on JSP let us discuss some problems of servlet.

Problems in servlet:

  1. In servlet presentation logic and dynamic content generation logic are intermixed which results in maintain problems.
  2. Whenever the presentation is changed servlet needs to be compiled and deployed again.
  3. A developer needs to write HTML code to the output stream of the servlet.

JSP:

JSP is the extension of the servlet that provides the solution to all the above problems. JSP defines a structure which is Java code inside HTML code. This structure simplifies web development.

Javax.servlet.jsp package.

Javax.servlet.jsp and its sub-packages provide the classes and interfaces that facilitate the development of JSP.

Interfaces in Javax.servlet.jsp package.

  1. JspPage.
  2. HttpJspPage.

Classes in Javax.servlet.jsp package.

  1. JspFactory.
  2. PageContext.
  3. JspWriter.
  4. JspEngineInfo.
  5. JspException.
  6. JspError.

JspPage interface:

JspPage extends the Servlet interface. JSP processor-generated servlet class must implement JspPage interface.

public interface JspPage extends Servlet

Methods of JspPage interface:

1. jspInit(): It is used to perform the initialization process. This method is called by the web container only once when the first request comes.

Syntax:

public void jspInit()

2. jspDestroy(): It is used to perform a cleanup process before destroying jsp page. This method is called by the web container only once.

Syntax:

public void jspDestroy()

HttpJspPage interface:

HttpJspPage interface extends the JspPage interface.

public interface HttpJspPage extends JspPage

Methods of HttpJspPage interface:

1. _jspService(): This method is called by the web container whenever a request comes for the jsp.

Syntax:

 public void _jspService() throws ServletException,IOException

Note: In this method underscore (_) represents that implementation of this method is provided by an auto-generated servlet and it can’t be overridden by the developer.

How does the JSP page work?

  1. A request comes for the JSP page.
  2. Web container translates the JSP page into a servlet.
  3. Compile the auto-generated servlet class.
  4. _JspService()method is called.
  5. Dynamic content will be generated.
  6. Send dynamically generated content as a response to the client.

For the first request, all 6 steps will be executed but for the next requests of this JSP page 2nd and 3rd steps will not execute.   

JSP Basic tutorial:

Alex Martin