Introduction to Java Server Pages – JSP

October 21 2009one Commented

Categorized Under: Java

This tutorial is based on the following software environment.

Windows Vista Home Premium, Eclipse 3.5, JDK 1.6, Tomcat 6

In a web application, JSP file resides along with other static files in application folder. Unlike Servlets which should be compiled and put in WEB-INF/classes folder, JSP do not require manual compilation. This is done by application server in run time using JSP compiler. When a client request JSP page, server first checks whether the JSP is compiled or not. If it is not compiled, JSP compiler compiles it into Servlet class and processes the request. Because of this process, it may take small amount of time to process first request. Rest of the requests are handled by generated JSP Servlet class. However, for performance improvement we may precompile JSPs using tools like Ant.

 JSP file is normally created with .jsp as extension. Broadly JSP file consists of static and dynamic content. Static content includes HTML and XML. Dynamic content is produced by embedding Java code within specials tags like <% and %>

JSP Expressions:-

Expressions are Java expressions included within tags <%= ….. %> in order to generate dynamic content. These may be embedded within static content. Java expressions are converted into string and delivered along with static content. For eg, the following line of code in JSP file,

The sum of 1+1 is <%= 1+1 %>

returns the output as

The sum of 1+1 is 2

Here 1+1 is evaluated to 2 and is combined with static content.

JSP Scriptlets:-

 JSP Expressions have limitation in the sense that it allows minimal amount of Java code embedded within static content. Scriptlets allows to write blocks of Java code within static content. Java code should be placed between tags <% and %> For eg,

<%
    out.println("The square root of 4 is "+Math.sqrt(4));
    out.println("<br>");
    out.println("The absolute value of -2 is "+Math.abs(-2));
%>
 

The above block of Java code generates a series of output. out is a predefined object variable available in JSP of type javax.servlet.jsp.JspWriter which do not require explicit declaration. println() method is used to write content to output. You just can’t place static content inside scriptlets. If you want to write any static content, you have to use out variable.

JSP Declarations:-

Declarations are used to declare variables and methods inside JSP page. These are embedded within tags <%! and %> These variables and methods have application level scope like class variables and methods. We may initialize the variable during declaration. But you have to remember that this declaration is called only once during lifecycle of generated Servlet which is shared by multiple threads. For eg,

<%!  
     java.util.Date currentDate=new java.util.Date();
%>
Current time is <%= currentDate %>

returns current time. Reload the page again. You may note that time is not changing. This is because currentDate variable initialization happens only once.

JSP Implicit Objects:-

In order to make scripting much easier Java provides some predefined objects which you may use in scriptlets and expressions. These do not require explicit declaration. The following variables represent different objects which are helpful in JSP coding.

  • request – It is HttpServletRequest object used for managing request. This variable may be used for accessing parameter values, HTTP headers etc.
  • response – HttpServletResponse object for managing response. For eg, you may set the response header, content type using setContentType() method.
  • out – JspWriter object for writing content to the output. This is mainly used in scriptlets not in expressions because the value of expression is automatically written to the output stream. This is the buffered version of PrintWriter object.
  • session – is of type javax.servlet.http.HttpSession. This is used for managing session object in JSP. As you know HTTP is a stateless protocol. It do not keep track of users. How do you know that the request is coming from a user who already made requests in past. HttpSession object is used for managing sessions which allows to keep track of users and requests.
  • application – used to get reference for ServletContext object. This object has application level scope which is shared by all servlets (and of course JSPs).
  • config – ServletConfig object which is sepecific to current JSP page. Each JSP is assciated with unique ServletConfig object unlike ServletContext object which is shared by all dynamic resources.
  • pageContext – this variable allows to get references to namespaces, other implicit objects etc. This variable may be used to redirect the request to another resource in server like JSPs, Servlets.
  • page – variable to get reference to current JSP page which is equivalent to this which do not have much importance.

 JSP Directives:-

Directives are special instructions to JSP Engine for processing the JSP page. For eg, if you want to write import statements for classes and packages, you may write the same using page directive. The syntax of directive is <%@ directive attribute %>

Three directives are available.

  • page directive
  • include directive
  • taglib directive

Some of the attributes for page directive are given below.

  • language – used to represent the language of the file. For eg,
    <%@ page language="java" %>

    represents Java language.

  • extends – If you want to override the parent class of generated Servlet, you may use this attribute.
  • import – used to import classes and packages. For eg,
    <%@ page import = "java.util.Date" %>
  •  session – If you want to use session object you may set the value of this attribute to true. By default this is set to true, so that you may use session object in JSP page. If you set the value as false you could not be able to use session object. For eg,
    <%@ page session = "false" %>
  • contentType – used to set the mime type of content. You may optionally provide character encoding also. For eg,
    <%@ page contentType = "text/html; charset = utf-8" %>

In a typical web application, you may use header and footer content like menus, privacy policy, license information etc. Rather than writing these information in each and every page, you may prefer to put the content in separate file and include the file in all other files. include directive is used to embed the content of a file in JSP page. For eg,

<%@ include file = "header.html" %>

includes the content of header file in JSP page. You may use relative URL of the file to include in JSP page. The file may be static or dynamic in nature. The content of the included file is embedded in generated Servlet during compilation time.

What is tag library? JSP allows to create custom tags which are used to execute specific actions. taglib directive is used to refer tag library in your JSP file. After onwards you may use any custom tag defined in your tag library. The syntax is

<%@ taglib uri="URI of tag library descriptor file" prefix="prefix for custom tags" %>

where uri is the absolute or relative URI of tag library descriptor file usually with .tld extension. prefix is used distinguish tags from other tag libraries. For eg,
cTag:message
where cTag is the prefix and message is the custom tag.
JSP Actions:-

In addition to the flexibility given by Java for creating custom tag libraries, JSP provides some standard tags for specific actions. These tags are used with prefix jsp. Some of the action tags are given below.

  • include – used to include static or dynamic content. For eg,
    <jsp:include page = "footer.html" />

    includes the content of footer.html file.

  • param – used to pass parameters in included dynamic resource like JSP file. All request parameters are available in included file also. You may change or add parameters to included file using param action tag
  • forward – redirect to another static or dynamic page. For eg,
    <jsp:forward page = "result.jsp" />

    Here it transfer the control to result.jsp page.

  • useBean – used to locate or instantiate Java bean class. JavaBean a simple Java class with getter and setter methods. For eg,
    <jsp:useBean id = "employee" class = "example.Employee" />

    instantiates Employee class.

JSP and JavaBeans:-
JavaBeans are reusable components. A simple JavaBean is a POJO with getter and setter methods for accessing and changing the properties. JSP provides action tags for instantiating bean class. It also provides two tags for accessing and modifying bean properties.

<jps:useBean id = "object name" class = "fully qualified class name" 
     scope = "request|page|sesion|application" />

This tag is used to instantiate bean class. id is the name of the object which we may refer in our JSP file. class attribute is the fully qualified class name. scope is the time in which bean resides in memory. For eg, if the scope is request, the bean may be available in other page if it is forwarded to it because the bean object is bound to request object which we may access later.

<jsp:setProperty name = "bean id" property = "property name" 
     param = "request parameter name" value = "value of the property" />

This tag is used to set the value of a property defined in JavaBean class.

<jsp:getProperty name = "bean id" property = "name of the property" />

This tag returns the value of property defined in bean object. You may use the bean object in scriptlets and expressions once it is defined using jsp:useBean tag. One of the valuable use of bean class is mapping form elements with bean properties while processing HTML form.

OK, now let us put everything into a practical example.  If you haven’t had Eclipse IDE with Tomcat , refer the following tutorial.
Installing and Configuring Eclipse with Tomcat in Windows

Open Eclipse. Java EE perspective is the default perspective. If you are not sure go to Window–>Open Perspective–>Other. Select Java EE and click OK. Go to File–>New–>Dynamic Web project. Project Wizard appears.

servletexample_1

Give the project name as JSPExample. All other options do not require modification if you are using Eclipse with Tomcat as server. If you have configured multiple servers you may change the target runtime.

jspexample_1  

Click Finish button. Now we have to add the project under server. Go to server window, right click on server entry and select Add and Remove. Move the project from left to right window in properties box. Click Finish button.

jspexample_2

Let us now create a JavaBean class. As I have previously mentioned its a simple class with getter and setter methods.In project explorer expand the project. Right click on src folder and select New–>Class. Java Class wizard appears. Specify the package name as example and class name as Employee. Press Finish button. Employee.java opens in editor. Replace the entire code with following code snippet.

package example;
 
public class Employee {
 
 private String name;
 private String designation;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 } 
 
}

Here two private instance variables (name, designation) are declared. Access of these private variables are resricted through public getter and setter methods. The name of getter method is created using following pattern,

get<variable name> where variable name starts with upper case. Similarly setter method name is generated using pattern set<variable name>

Save the file. Now let us create JSP file. Right click on WebContent under JSPExample project and select New–>JSP.

jspexample_3

 New JSP page window appears. Give the file name as index.jsp and press finish button. Now index.jsp appears in editor. Replace the entire content with the following code snippet.

<%@ page language = "java" contentType = "text/html; charset=ISO-8859-1" %>
 
<jsp:useBean id = "employee" class = "example.Employee" scope = "request" />
<jsp:setProperty name = "employee" property = "name" value = "Jinoy P George" />
<jsp:setProperty name = "employee" property = "designation" value = "programmer" />
 
<%!
	String department = "Information Technology";
 
%>
 
Department is <%= department %> <p>
<%
	out.println("Employee name is "+employee.getName()+"<p>");	
%>
Employee designation is <jsp:getProperty name = "employee" property = "designation" />

Save the file. Start the server. Once it is started type the following URL in browser and hit enter. 

http://localhost:8080/JSPExample/

If everything is OK, you get the following output.

Department is Information Technology
 
Employee name is Jinoy P George
 
Employee designation is programmer

Now let us walk through the code.

 First line is a page directive. Language is given as java and content type of the output is defined as text/html. We have provided character encoding also.

Next three lines are about JSP actions. We instantiate Employee bean class which we already declared. Then we set the values of properties name and designation using jsp:setProperty action tag.

In next line we declare and initialize a string variable named department within JSP declaration tags.

Department is <%= department %>

The above line generates output regarding department name. The variable department declared in declaration is available in expressions. The variable is added with string literal to generate output.

Employee name is printed using scriptlets. Since employee object is already instantiated using action tag, you may use it in scriptlets.

Employee designation is printed using action tag jsp:getProperty

Well, I think you got basic introduction to JSP. Refer advanced JSP tutorials once you are comfortable with basics.

cheers,

One Response to “Introduction to Java Server Pages – JSP”

  1. Vidya Moger says:

    Easy to understand . Really helpful

Leave a Reply

*