JavaServer Pages (JSP) is a technology that is using to write dynamic and data-driven pages for your Java web applications. JSP works by the Java Servlet specification. In old Java projects, Servlet and JSP technologies work together. When you write servlets you write Java code and embed client-side markup (like HTML) into that code. When you write JSP, you write the client-side script or markup and embed JSP tags to connect your page to the Java backend.
JavaServer Pages are based on HTML, XML, SOAP, or other document types.
In a nutshell, JSP technology is the extension of Servlet technology. We can use all the features of the Servlet there. In addition, we can use implicit objects, predefined tags, expression language, and Custom tags in JSP, which makes JSP development easy.
The same as Servlets, JSP is running on a web server. An example of a web server is Apache Tomcat, Jetty, Apache TomEE, Oracle WebLogic, WebSphere, Apache Geronimo, etc. JSP is an abstraction of Java servlets. It is translated into servlets at runtime, therefore JSP is a Servlet.
JavaServer Pages can be used independently. Also, you can use it in the model–view–controller design as the view component. It can be used normally with the JavaBeans model and Java servlets (or a framework such as Apache Struts) as the controller.
JavaServer Pages technology allows creating web content with static and dynamic components. JSP technology has dynamic capabilities but provides a more natural approach for static content creation.
The main features of JSP technology are:
- JSP pages are pages written as text-based documents that describe how to process a request and to build a response.
- In JSP you can access server-side objects with an expression language.
- There are mechanisms to create extensions for the JSP language.
JavaServer Pages have many advantages over the Servlet as follows:
We can use all the features of the Servlet in JSP. In addition, we can use implicit objects, predefined tags, expression language, and Custom tags in JSP, which makes JSP development easy.
JSP is easier to maintain. It can be easily managed because we can easily separate our business logic and presentation layer. In Servlet technology, we mix our business and the presentation logic.
The development of JSPs is quicker then Servlets because you don’t need to recompile and redeploy them. If the JSP page is modified, we don’t need to recompile and redeploy the project.
JavaServer Pages technology has less code than Servlet technology. There we can use many tags such as action tags, JSTL, custom tags, etc. All of the reduce the code. Moreover, we can use expression language, implicit objects and even more features.
JavaServer Pages are built on Java Servlets API, therefore, they have access to all the powerful Enterprise Java technologies, including JDBC, JNDI, EJB, JAXP, etc.
JSP is a part of a complete platform for enterprise-class applications, Java EE. This means that JSP can be used in the simplest applications and also in the most complex and demanding.
JSP Processing
Let’s understand how the web server creates the Webpage using JSP. Initially, you send an HTTP request via browser to the webserver.
The web server receives and recognizes that the HTTP request is to some particular JSP page. It forwards the HTTP request to a JSP engine. The request is doing by using the URL or JSP page (ends with .jsp).
The JSP engine is responsible for loading the JSP page from disk and after it converts JSP into a servlet content. During conversion, all template text is simply converting to println( ) statements, and all JSP elements are converted to Java code that provides a corresponding dynamic behavior of the web page.
The JSP engine converts the servlet into an executable class. After, the request is forwarding to the servlet engine.
 The servlet engine is a part of the webserver. The servlet engine loads the Servlet class and is responsible for its execution. The servlet executes and produces an output in HTML format. After, the servlet engine passes the output to the web server inside an HTTP response. Further, the webserver forwards the HTTP response to your browser in terms of static HTML content.
The web browser receives the HTTP response with the dynamically-generated HTML page and handles it as if it were a static page.
The JSP engine checks whether the JSP file already has the corresponding servlet. It also checks the modification date on the JSP and on the servlet. If the JSP modification date is before the modification date of its generated servlet, the JSP container will think that the JSP hasn’t changed. The servlet generated before will be still valid for the JSP contents. The new servlet wouldn’t be generated, which makes the process faster and more efficient than with the other scripting languages (such as PHP).
The Lifecycle of a JSP
A JSP life cycle is pretty similar to a servlet life cycle with an additional step that is required to compile a JavaServer Pages into a servlet.
JSP Compilation is the first step. When a browser requests a JSP, the JSP engine checks whether the compilation of the page is needed. In case the page has never been compiled or it was modified since the last compilation, the JSP engine is going to compile the page.
The compilation process has three steps: parsing the JSP, conversion of the JSP into a servlet, and compilation of the servlet.
After the compilation, we have the JSP Initialization phase. Before processing any requests the web container loads a JSP and calls the jspInit() method. In this method, we can do any initialization. It is performed only once. If you need to initialize database connections, open files, and create lookup tables better to do this in the jspInit() method.
To perform your JSP-specific initialization, you need to override the jspInit() method:
public void jspInit(){
// Initialization code...
}
JSP Execution phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. When a browser requests a JSP and the page is loaded and initialized, the JSP engine invokes the _jspService() method of a corresponding JSP.
This method has two parameters HttpServletRequest and HttpServletResponse:
void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Service handling code...
}
The _jspService() method is responsible for generating a response for a request. Actually, this method can generate responses to all seven of the HTTP methods (GET, POST, DELETE, etc).
JSP Cleanup phase is the destruction phase of the JSP life cycle. It is
coming when a JSP is being removed from use by a web container.
JSPs have the jspDestroy() method. This method is the JSP equivalent of the servlet destroy method. If you need to perform any cleanup, override the jspDestroy method. It is usually a good idea to do such action in the destroy method as releasing database connections, releasing resources, closing open files.
The jspDestroy() method looks like:
public void jspDestroy() {
// Your cleanup code goes here.
}
Environment Setup
A development environment is where you develop your JSP, test, and run them.
First of all, you need to set up the Java Development Kit. You can download SDK from the Oracle Java site. After, you need to add JAVA_HOME variable to the Environment Variables of your Windows operating system.
In the case of Unix OS(Solaris, Linux, etc.), you need to add JAVA_HOME into the .cshrc file.
There is a number of available Web Servers that support JavaServer Pages and Servlets development. A lot of web servers are free, One of such web servers is the Apache Tomcat. It is open-source software. To set up it, you need to download it and set the CATALINA_HOME environment variable.
JavaServer Pages Document
A JSP document is written in XML syntax. Therefore, it gives you all the benefits of the XML standard. The one is that you can create a JSP document using one of the many tools on the market that support XML format. It helps you to ensure that your JSP document is well-formed XML. It is easier for you to correct mistakes in a user-friendly environment. There is a possibility to validate the JSP document with a document type definition (DTD). Within a JSP document, you can nest and scope namespaces.The XML syntax gives to the JSP page less complexity and more flexibility. You can use any XML document as a JSP document.You can also write tag files in XML syntax.
Here is an example of JSP document:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="/functions" prefix="f" %> <html> <head><title>Localized Dates</title></head> <body bgcolor="white"> <form name="localeForm" action="index.jsp" method="post"> <c:set var="selectedLocaleString" value="${param.locale}" /> <c:set var="selectedFlag"      value="${!empty selectedLocaleString}" /> <b>Locale:</b> <select name=locale> <c:forEach var="localeString" items="${locales.localeNames}" > <c:choose>     <c:when test="${selectedFlag}">         <c:choose>             <c:when                  test="${f:equals(selectedLocaleString, localeString)}" >                 <option selected>${localeString}</option>             </c:when>             <c:otherwise>                 <option>${localeString}</option>             </c:otherwise>         </c:choose>     </c:when>     <c:otherwise>         <option>${localeString}</option>     </c:otherwise> </c:choose> </c:forEach> </select> <input type="submit" name="Submit" value="Get Date"> </form>
<c:if test="${selectedFlag}" > Â Â Â Â <jsp:setProperty name="locales" Â Â Â Â Â Â Â Â property="selectedLocaleString" Â Â Â Â Â Â Â Â value="${selectedLocaleString}" /> Â Â Â Â <jsp:useBean id="date" class="mypkg.MyDate"/> Â Â Â Â <jsp:setProperty name="date" property="locale" Â Â Â Â Â Â Â Â value="${locales.selectedLocale}"/> Â Â Â Â <b>Date: </b>${date.date}</c:if> </body> </html>
In the next articles we will explain in details how to build JSP pages.