Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Server Pages (JSP) Overview

This article gives an overview of JSP technology. We will learn and cover the JSP Overview, architecture, Life Cycle, Directives, Action Elements and Implicit Objects.

JSP stands for JAVA SERVER PAGES. It is a standard java extension used to simplify the creation and management of dynamic web pages. JSP’s allow us to separate the dynamic content of webpage from static presentation content. A JSP page consists of HTML tags and JSP tags. HTML tags are used to create static page content and JSP tags are used to add dynamic content to web pages. JSP pages are compiled into a Java Servlet by a JSP translator.

Why Use JSP?

Building dynamic web pages by using JSP offers the following benefits:

  • Web pages created using JSP are portable and can be used across multiple platforms without making any changes.
  • Programming in JSP in easier than in Servlets.
  • JSP pages are automatically compiled by servers. Developers need to compile JSP pages when the source code of the JSP page is changed.
  • Most important benefit of JSP is the separation of business logic from presentation logic. JavaBeans contain business logic and JSP pages contain presentation logic. This separation makes an application created in JSP more secure and reusable.

Advantages of JSP

  • JSP pages easily combines static templates like HTML or XML fragments.
  • Before execution, JSP pages are compiled into servlets so we can easily update presentation code.
  • If JSP page is modified, then there is no need to recompile and redeploy the project. We only need to recompile and redeploy the servlet code.
  • It is easy to separate business logic from presentation logic. So JSP can be easily managed.
  • It is easy to learn and easy to implement.
  • JSP environment provides compilation of pages automatically.
  • Servlets cannot be accessed directly whereas a JSP page can be accessed directly as a simple HTML page.

JSP Architecture


Figure 1.JSP Architecture

As shown in above architecture, web browser directly accesses the JSP page of web container. The JSP pages interact with the web container’s JavaBeans which represent the application model. When client sends request from a JSP page, the response is sent back to the client depending on the requests which are invoked by the client request. If response requires accessing the database, the JSP page uses JavaBeans to get data from the database.

Life Cycle of JSP

JSP pages follow these phases:

  • Translate the JSP to servlet code.
  • Compile the servlet to byte code.
  • Load the servlet class.
  • Create the servlet instance.
  • Call the jspInit method.
  • Call the _jspService method.
  • Call the jspDestroy method.

JSP Page Translation:In the first step, the web container translates the JSP file into a Java source file that contains a servlet class definition. The web container validates the correctness of JSP pages and tag files.

JSP Page Compilation:In the second step, the web container compiles the servlet source code into a Java class file.

JSP Page Class Loading:In the third step, the servlet class byte code is loaded into the web container’s JVM software using class loader.

JSP Page Servlet Instance:In the fourth step, the web container creates an instance of the servlet class.

JSP Page Initialization:In the fifth step, the web container initializes the servlet by calling the jspInit() method. This method is called immediately after the instance gets created. It is called only once during JSP life cycle.

To perform initialization we need to override jspInit() method:

public void jspInit (){
//code
} 

JSP Page Service:The initialized servlet can now service the requests. The web container calls the _jspService () method to process the user request. This method is called for every request during its life cycle.

This method takes HttpServletRequest and HttpServletResponse parameters.

JSP Page Destroyed:When the web container removes the JSP servlet instance from service, it calls jspDestroy () method to allow JSP page to clean up the resources. This is end of the JSP life cycle.

This method can be written as follows:

 
public void jspDestroy()
{
//code
}

JSP Syntax

This topic defines about basic syntax in Java Server Page such as Scriptlet, Declarative, Expression and Comments.

Syntax Name Code
Scriptlet Tag <%statement or java code%>
Declarative tag <%! Statement %>
Expression tag <% = Statement %>
Comment tag <%-----comments------ %>

The Scriptlet Tag: it is used to include java Technology Code in the JSP. The syntax is as follows:

<% java code %>

Listing 1.Example using scriptlet tag

<% int i=0; %>

The Declarative Tag:It is used to include members in the JSP servlet class either attributes or methods. The syntax is as follows:

<!  Statement %>

Listing 2. Example using declarative tag

<! Int counter=0; %>

The Expression Tag:It holds java language expression that is evaluated during HTTP request and is included in HTTP response stream. The syntax is as follows:

<%= expression %>

Listing 3. Example using expression tag

The current time and date is : <%= new java.util.Date () %>

The Comment Tag:It is used to hide part of code in JSP page or to ignore some statements in the code. The syntax is as follows:

<% - -comment -- %>

Listing 4.Example using comment tag

<%-- This is a JSP comment -- %>

Following example demonstrates use of above scripting elements.

Listing 5.example.jsp

<%!int fontSize=3;%><br>
  <html>
  <head>
  <title>firstexample</title>
  </head>
   <body>
   
  <%-- addition Program --%><br>
  <%
     int a = 5;<br>
     int b = 3; <br>
     int result = a+b;
   
  %><br>
    <font color="green" size="<%= fontSize %>"><br>
  <% 
            out.print(" Total=" +result); 
   
  %><br>
  </font><br> 
  </body>
  </html>

The output of the above program is:

Total=8 

JSP Directives

Directives tell how to translate JSP page into servlet. There are three types of directives:

  • page directive
  • include directive
  • taglib directive

Directives usually in the following form:

<% @ directive attribute =”value” %>

JSP page Directive:It is used to modify translation of Jsp page. Syntax of JSP page directive is as follows:

<%@ page attribute="value"%>

Attributes of JSP page directive are as follows:

  • import
  • contentType
  • extends
  • info
  • buffer
  • language
  • isELIgnored
  • isThreadSafe
  • errorPage
  • isErrorPage
  • autoFlush
  • pageEncoding
  • session
  • Import: It is used to define classes and packages in servlet class. For Example:

Listing 6. Example using import

 <html>   <body>  
  <%@ page import="java.util.Date" %>  
  Today is: <%= new java.util.Date() %>    
  </body>  
  </html>  

  • ContentType: It defines MIME(Multipurpose Internet Mail Extension) of the output stream. Default is text/html. For example:

Listing 7. Example using contentType

<html>  
  <body>  
  <%@ page contentType="text/html"%>      
  </body>  
  </html>   

  • Extends: It defines super class of servlet class generated by Jsp page. It is rarely used.
  • Info: Defines information about Jsp page. Information can be accessed by using getServletInfo() method. For example:

Listing 8. Example using info

<html>  
  <body>  
  <%@ page info="hello world..." %>   
  </body>  
  </html> 
  

It can be accessed with method getServletInfo() in the servlet. For example:

public String getServletInfo() {  
  return "hello world...";   
}  

  • Buffer: Defines size of the buffer used in the output stream. Default buffer size is 8KiloBytes or greater. Here is an example:

Listing 9. Example using buffer

  
<html>   <body>  
  <%@ page buffer="16kb" %> 
  </body>  
  </html>

  • Language: It defines the language used in Jsp page. Default value is "java". For example:

Listing 10. Example using language

<%@ page language="java" %>

  • isELIgnored: It specifies whether EL (Expression Language) elements are not processed on the page. The value could be true or false. Default value is false. For example:

Listing 11. Example using isELIgnored

<%@ page isELIgnored="true"%> 
//If set to true then EL will not be evaluated.

  • IsThreadSafe: To control behavior of Jsp page we can use isThreadSafe attribute. The default value is true. If set to false, it will wait until the JSP finishes responding to a request before passing another request to it. For example:

Listing 12. Example using IsThreadSafe

<%@ page isThreadSafe="false"%>

  • errorPage: It is used to display an error page. If error occurs in current page then it will be redirected to the error page. For example:

Listing 13. Example using errorPage

<html>
  <body>
  <%@ page errorPage="errexample.jsp"%>
  <%=100/0 %>
  </body>
  </html>

Listing 14. errexample.jsp

<html>
  <body>    
  <%@ page isErrorPage="true" %>  
   Exception occurred...The exception is: <%= exception %>    
  </body>  
  </html>  

  • isErrorPage: To declare a current page as the error page. For example:

Listing 15. Example using isErrorPage

 <html>   <body>  
  <%@ page isErrorPage="true" %>  
   Exception occurred…The exception is: <%= exception %>  
  </body>  
  </html>   
  

  • AutoFlush: It defines whether the output should be flushed automatically when buffer is filled. The default is true. For example:

Listing 16. Example using autoFlush

<%@ page buffer="10kb" autoflush="false"%> 
//value of the autoFlush is false. 

So, the page will not be flushed automatically because buffered size should be with at least 8kb.

  • pageEncoding: It defines character encoding of output stream. The default is ISO-8859-1.
  • Session: It defines whether JSP page is involved in HTTP session. For example:

<%=session.getAttribute ("user") %>

JSP include directive: It is used to include contents of files such as JSP file, html file or text file. This happens during translation phase. By using this directive we can reuse the code.

Syntax of JSP include directive is as follows:

<%@ include file="file name" %>

For Example:

Listing 17. Example using include

<html>  
  <body>  
  <%@ include file="hello.html" %>    
  Today is: <%= new java.util.Date () %>  
  </body>  
  </html>
  

JSP taglib directive: It is used to define tag library that defines custom tags. We can use Tag Library Descriptor (TLD) file to define the tags. This directive includes URI and custom tag prefix. The URI is used to specify a location. The prefix is used to distinguish custom tags from libraries.

Syntax is as follows:

<%@ taglib uri=”tag library uri” prefix=”tag library prefix” %>

Example:

Listing 18. Example using taglib

<%@ taglib uri="http://www.google.com" prefix="c"%> 

JSP Action Elements

The Action tags are used to control the flow between pages and to be used with Java Bean. We can insert a file, forward one page to another page or we can create HTML page for java plugin. JSP actions are XML tags that control the behavior of the JSP engine.

Jsp Action Tags are as follows:

jsp : include It is used to include contents of files such as JSP files, html files or text files. This happens during translation phase.
jsp : forward It is used to forward request to another resource or page .It may be html page, JSP page or other resource.
jsp : usebean Used to create specified object
jsp : setProperty Gives details about java bean object
jsp : getProperty It is used to retrieve value of given property
jsp : element To create dynamic xml elements
jsp : attribute To define dynamic XML elements attribute
jsp : body To define dynamic XML elements body
jsp : text Used to write text in JSP pages and documents

<jsp: include> Action Tag:It is used to include files such as JSP, html or servlet. This happens during translation phase. This tag includes file when the page is requested.

The Syntax of this tag is as follows:

<jsp: include page=”relative URL” />

For example, we will create JSP file called newdate.jsp whose content is included in includeexample.jsp.

Listing 19.includeexample.jsp

<html>
  <body>
  <jsp:include page="newdate.jsp"/>
  </body>
  </html>
  

Listing 20.newdate.jsp

  <html>
  <body>
  <%out.println("today's date is:"+new java.util.Date()%>
  </body>
  </html>

The <jsp: forward> Action Tag: It is used to forward request to another page it may be JSP, html or another resource. The Syntax of this tag is as follows:

<jsp: forward page=”Relative URL”/>

The following example creates one JSP file called hello.jsp and forward request to date.jsp page.

Listing 21. hello.jsp

<html>
  <body>
  <jsp: forward page="date.jsp"/>
  </body>
  </html>
  

Listing 22. date.jsp

<html>
  <body>
  <%out.println ("today's date is:"+new java.util.Date () %>
  </body>
  </html>

The <jsp: usebean> Action Tag:It is used to instantiate a bean class. It searches for id and scope variables. If object is not created, then it creates the specified object.

The Syntax of this tag is as follows:

<jsp: usebean id=”name” scope=”page|request|session|application” 
  class=”packageName.classname” type=” packageName.classname” 
    beanName=” packageName.classname”>
  </jsp: usebean>

Attributes of jsp: usebean action tag:

  • id: It represents the identifier of usebean tag
  • scope: It represents the scope of the bean instance. Scopes value may be page, request, session, and application. Default scope is page.
    • page: Using this scope a bean is available within a JSP page until page sends response to client or forwards request to another resource.
    • request: It Indicates a bean can be used from any JSP page that is processing the same request until JSP page sends response to the client.
    • session: It indicates that a bean can be used from any JSP page invoked in the same session .The Page in which we create the bean must have page directive with session=”true”.
    • application: It indicates that the bean can be used from any JSP page in the same application.
  • class: It takes class name to create a bean instance if bean instance not present in given scope. It should have no-argument constructor and should not be an abstract class.
  • beanName: It takes class name or expression.
  • type: It takes a class or interface name. This can be used with class or beanName attribute.

Example: Create one java class called bean1.java

Listing 23. bean1.java

package mrbool.com
public class bean1
{
public int square(int a)
{
return a*a;
}
}

Listing 24.welcome.jsp

 <jsp:usebean id="obj" class="mrbool.com.bean1"/>   
  <%
  int b=obj.square(int 2);
  out.println("square of the number is:"+b);
  %>

The <jsp: setProperty> and <jsp: getProperty> Action tags:The jsp: setProperty action tag is used to set property value in the bean. It sets value in the bean using setter method. The syntax is as follows:

<jsp: usebean id=”uname” class=”package. class”/>
   . . . .
  <jsp: setProperty name=”uname” property=”propertyName”/>

The jsp: getProperty action tag is used to get the property’s value. The syntax is as follows:

<jsp: usebean id=”uname” class=”package. class”/>
   . . . .
  <jsp: getProperty name=”uname” property=”propertyName”/>

Example for setProperty and getProperty: Create one java file called example.java.

Listing 25.example.java

package mrbool.com;
public class example {
   private String msg;
//use getter and setter methods
public String getMsg() {
	return msg;
}

public void setMsg(String msg) {
	this.msg = msg;
}

}

Now create one jsp file and save it as index.jsp

Listing 26. index.jsp

<html>
  <body>
   
  <jsp: usebean id="tek" class="mrbool.com.example" />
   
  <jsp: setProperty name="tek" property="msg" />
   
  <p>hello world!!!!!</p>
   
  <jsp: getProperty name="tek" property="msg" />
   
  </body>
  </html>

The <jsp: element>, <jsp: attribute> and <jsp: body> Action tags:The <jsp: element> tag is used to create dynamic xml elements. The <jsp: element> tag is used to create dynamic xml element’s attribute. The <jsp: element> tag is used to create dynamic xml element’s body. For example:

Listing 27. Example using

<html>
  <body>
  <jsp:element name="tek">
  <jsp:attribute name="tek1"> attribute value </jsp:attribute>
  <jsp:body>
     //body 
  </jsp:body>
  </jsp:element>
  </body>
  </html>

The < jsp: text> action tag:It is used to write text in jsp pages. The syntax can be written like this:

  <jsp: text>
    Data
  </jsp: text>

Listing 28. Example using < jsp: text>

<html>
  <body>
  <jsp: text>hi hello...</jsp: text>
  </body>
  </html>
  

JSP implicit Objects

Implicit objects are java objects that are created by the container while translating JSP pages to servlets. There are 9 implicit objects as listed below:

  • out
  • request
  • response
  • session
  • application
  • config
  • pageContext
  • page
  • exception

  • The out object:It is used to send content or output to the client. This object is instance of javax.servlet.jsp.JspWriter. It sends content in a response.

Listing 29.Example using out object

<html>
  <body>
  <% out.println ("today’s date is:"+new java.util.Date ());
  %>
  </body>
  </html>

The request object:When the client requests a page, the JSP engine creates a new object to that request. It is object of type HttpServletRequest.

Example: Create one html file as index.html

Listing 30.index.html

<html>
  <body>
  <form action="hello.jsp">
  <input type="text" name="username"/>
  <input type="submit" value="submit"/>
  </form>
  </body>
  
</html> 

Now create jsp file as hello.jsp. This file should be the same as the one in html file.

Listing 31.hello.jsp

<html>
  <body>
  <%
  String name=request.getParameter ("username");
  out.println("hi"+name);
  %>
  </body>
  </html>

The response object:It creates an object to respond to the client. It is an object of type HttpServletResponse.

Example: Create one html file: sample.html

Listing 32.sample.html

<html>
  <body>
  <form action="myResponse.jsp">
  <input type="text" name="username"/>
  <input type="submit" value="submit"/>
  </form>
  </body>
  </html>

Now create jsp file as myResponse.jsp

Listing 33.myResponse.jsp

<html>
  <body>
  <%
  response.sendRedirect ("http://www.yahoo.com");
  %>
  </body>
  </html>

The session object:It is used to set or get session information. A session object is created by the container whenever we request a JSP page.

Listing 34.Example using session object

<html>
  <body>
  <%=session.getId () %>
  </body>
  </html>

The application object:It is used to get information and attributes in JSP. It also used to forward the request to another resource or to include the response from another resource.

Listing 35.Example using appli object

<html>
  <body>
  <%=application.getInitParameter ("User") %> 
  </body>
  </html>

The config object:It is used to get configuration message for a jsp page. You can also use it get the init parameter present in web.xml.

Listing 36.Example using config object

<html>
  <body>
  <%=config. getInitParameter ("User") %>
  </body>
  </html>

The pageContext object:It is used to set and get attributes and forward request to other resources.

Listing 37.Example using pageContext object

<html>
  <body>
  <% pageContext.setAttribute ("tek", "buds"); %>
  <p>PageContext attribute</p> :{ Name="tek", Value="<%=pageContext.getAttribute ("tek") %>"}
  </body>
  </html>

The page object:It is an instance of the object class and references the current jsp page. It is rarely used . It is written as:

Object page=this

Listing 38.Example using page object

<html>
  <body>
  <%=page.getClass ().getName () %>
  </body>
  </html>

The exception Object:It is used to display exception in jsp error pages. It is an instance of the Throwable’s subclass. It is available only in error pages.



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login