Learn Java Programming
14.0 Java Server Pages – JSP
The following are the objectives of this module
- Understand why we need JSP
- How to add programming logic in JSP
- JSP best practices
- Using the JSP useBean tag
- Using the Java Standard Template Library JSTL
If you look closely at our Servlet examples, you would noticed that the servlet’s doPost() method is generating the page for the user depending on the user input.
While this type of HTML page generation works, it makes it difficult to make changes to the layout. Every time we need to change even a single image on the page, we may have to edit the Java code, and modify the servlet that is generating the HTML. This makes it tedious especially for websites that need to be constantly updated.
The Java Server Pages technology particularly addresses this problem. JSP strives to “enable the separation of dynamic and static content”, so that it is easy for Web page authors to design the pages and not worry about the Java code. Also Java programmers are freed from having to worry about page layout and design and focus on the business logic.
JSP thus enables us to separate presentation from the content – content can vary but the display could be just the same. JSP defines the Presentation layer in a tiered application architecture, with the business layer generally given by the Java code and the Servlets.
The Model 2 Architecture:
A HTML page could post a request to a servlet that could performs business logic and we could have that servlet forward the request for rendering to a JSP page using the RequestDispatcher mechanism.
The above approach is called a Model 2 Architecture
A JSP page for the most contains static HTML. The only difference between a JSP page and a HTML page is that the JSP page allows the direct insertion of Java code along with the static HTML file.
Scriptlets
Java code can be inserted into a JSP page using scriptlets. A scriptlets is defined using the tags <% and %>. Java code can be present a JSP page using the leading tag <% and a closing %>. Each time when the page is rendered, the Java code between the tags <% and %> gets executed.
There are a number of predefined variables that are available to scriptlets. Scriptlets can simply access the following variables as if they have just been created:
- request – HttpServletRequest (The servlet request)
- response – HttpServletResponse (The servlet response)
- session – HttpSession (The user’s session)
- application – ServletContext (The web application)
- out – javax.servlet.jsp.JspWriter (The output writer)
For example,
<html>
<head><title>Hello</title></head>
<body>
<h1>
<%
if (request.getParameter("name") == null) {
out.println("Hello and welcome");
}else {
out.println("Hello " + request.getParameter("name") + " Welcome!");
}
%>
</h1>
</body>
</html>
The above JSP page, whenever it gets executed, checks the request object for the parameter “name” – If name is present, it prints a customized messsage, else it prints a general message Hello and welcome
Behind the screens, each JSP file is compiled into a servlet. The static HTML portions of the JSP are generated using the out.println() calls, while the dynamic portions are included directly.
When you access the JSP page for the first time, you may notice that it takes a short time to respond. This is because of the time necessary for the server to create and compile the background servlet.
Expressions:
JSP allows code to be placed directly into a page using expressions and declarations. A JSP expression begins with <g;%= and ends with %>
Any Java expression between the two tags <%= and %> is evaluated, the result is converted to a String, and the text is included directly into the page.
For example, <g;%= request.getParameter(“greeting”) %> includes the value of the greeting variable in the request object directly in the output.
Declarations:
Declarations enable us to declare static or instance variables or define new methods in the JSP page. A declaration begins with <%! and %>
Remember that the JSP is compiled into a servlet. Whatever code we placed in between the <%! and %> tags, is placed outside the service method of the generated servlet. Hence the best place to define static or instance variables or new methods, is in the declarations block.
For example,
<%!
private static final String DEFAULT_NAME = "Citizen";
private String getName(HttpServletRequest request) {
String name = request.getParameter("name");
if (name == null) return DEFAULT_NAME;
else return name;
}
%>
<html>
. . .
<h1>
Hello, <%= getName(request) %>
</h1>
. . .
</html>
The getName() method is declared in the declaration section. The method is then accessed using Expressions <%= and %> tag in the JSP page.
Directives
A JSP directive allows a JSP page to control certain aspects of its servlet code.
Directives are used to to have the servlet set the content-type or import a package. It also allows the JSP and the servlet to control its output buffering, and session management. A directive is also used to specify the use of a non-Java scripting language.
A directive is defined by surrounding with the <%@ and %> tags. A directive requires a directive name, along with an attribute name and a value pair
<%@ directiveName attribName="attribValue" %>
Let us briefly look at some types of derivatives:
Content type directive:
The contentType specifies the content type of the generated page:
<%@ page contentType="text/plain" %>
The import directive :
The import directive specifies the list of classes and packages the generated servlet should import. Multiple classes can be given in a comma-seperated list. Importing classes allows us to access the methods in the JSP scripplets
For example,
<%@ page import="java.io.*, java.util.Hashtable" %>
The buffer directive:
The buffer directive specifies the minimum required size of the buffer response. The default buffer size is 8kb
For example,
<%@ page buffer="12kb" %>
The session directive:
When we want to access the user’s session in the JSP page, we need to specify the session derivative. The session directive indicates the page wants to have access to the user’s session. A value of true puts the session variable in scope. A false value disables access to the session variable. The default value is true
For example,
<%@ page session="false" %>
The errorPage directive:
The errorPage specifies which page to display if a Throwable is thrown from within the JSP page.
For example,
<%@ page errorPage="/error.jsp" %>
The language directive:
The langauage directive specifes the scripting language used in within the JSP page.
For example,
<%@ page language=”javascript” %>
Well, so far we saw how to include Java code in JSP pages – but here is the paradox!
Avoid Java code in your JSP pages – Java code is used for business logic and should not be used in the Presentation layer.
JSP and JavaBeans
When we say “Do not use Javacode in JSP pages” the next question that generally comes up is “How than are we to show dynamic values in the HTML”? Of course we need <%= request.getParameter(“name”) %> kind of declarations, don’t we?
Well, we can use JavaBeans within JSP pages without declaring any Java code, using the <bean: /> tag
JavaServer Pages offer a powerful way to co-operate with JavaBean components. JavaBeans are reusable Java classes whose methods and variables follow specific naming conventions to give them added abilities.
They can be embedded directly in a JSP page using the <jsp:useBean> tag.
How to embed a JavaBean in a JSP page
Beans are embedded in a JSP using the <jsp:useBean> tag – The syntax is given as follows:
<jsp:useBean id="name"
scope="page|request|session|application"
class="fully qualified className"
type="fully qualifed typeName">
</jsp:useBean>
- id specifies the name of the bean. This is particularly helpful if the bean is saved beyond the scope of the page.
- scope defines the scope of the bean’s visibility. The default value is page
- class defines the class name of the bean. The class name should be a fully qualified name
- type specifies the type of the bean – should be a fully qualified name of a superclass or an interface of the actual class
Here is what happens when we use the <jsp:useBean /> in our JSP pages
The JSP code tries to locate a bean with the scope and name we specified. For example, if we had specified <jsp:useBean id=”address” scope=”session” class=”com.itseasytolearn.beans.Address” /> then it tries to find the bean “address” in the session scope
If the bean is found in the scope (which is session in our example), an object reference variable is defined with the name we have specified. In our example, the reference variable is called address.
If the JSP code cannot find the bean given by the name attribute in the defined scope, it creates a bean object from the class we have specified and stores a reference to it in the variable.
Once we get the reference to the bean in the JSP page, it is now possible to control the properties of the embedded bean within the JSP page.
Controlling the properties of the embedded Bean in a JSP page
The <jsp:setProperty> action provides the ability for request parameters to automatically set the properties on the beans embedded within the JSP page. This gives beans automatic access to the parameters of the request without having to call getParameter() method
Let us now look at some typical usages:
Usage 1:
<jsp:setProperty name="beanName" property="*" />
Any request parameter with the same name and type as property on the given bean, should be used to set that property on the bean.
<jsp:useBean id="address" scope="session" class="com.itseasytolearn.beans.Address" />
<jsp:setProperty name="address" property="*" />
If the user has input the text as “Rio De Janireo” on the text box defined as
<input type="text" name="city" />
and if the bean has a method, setCity(String city) and the request has a parameter called “city” with a value of “Rio De Janireo”, the server will automatically call address.setCity(“Rio De Janireo”) at the beginning of request handling.
All matching HTML elements in the JSP page, having the same name as the attribute of the bean will be used to set the bean properties with the values from the HTML page.
Usage 2:
<jsp:setProperty name="beanName" property="propertyName" />
This statement says that the given property should be set on the bean, if there is a request parameter with the same name and type – but no other property should be set.
<jsp:useBean id="preference" scope="session" class="com.itseasytolearn.beans.Preference" />
<jsp:setProperty name="preference" property="size" />
The value of the preference in the HTML page from the user request from the text
<input type="text" name="size" />
is used to set the size property only. No other property on the bean will be set from the other HTML elements.
Usage 3:
<jsp:setProperty name="beanName" property="propertyName" param="paramName" />
The above statement states that the given property should be set if there is a request parameter with the given name and the same type.
If the request parameter has a parameter with name “paramName” it will be used to set “propertyName” in the bean given by “beanName”
For example,
<jsp:useBean id="address" scope="session" class="com.itseasytolearn.beans.Address" />
<jsp:setProperty name="address" property="zipcode" param="pincode" />
If the request contains a parameter with name as “pincode”, it would be used to set the property “zipcode” on the bean specifed by “address”
Usage 4:
<jsp:setProperty name="beanName" property="propertyName" value="constant />
The above statement states the given property should be set to the given value, which will be converted to the appropriate type if necessary.
<jsp:useBean id="address" scope="session" class="com.itseasytolearn.beans.Address" />
<jsp:setProperty name="address" property="city" value="Mumbai" />
Accessing properties from a bean:
The <jsp:getProperty> action provides a mechanism for retrieving property values without using Java code in the page.
<jsp:getProperty name="beanName "property="propertyName" />
For example, consider the useBean tag defined as follows:
<jsp:useBean id="address" scope="session" class="com.itseasytolearn.beans.Address" />
In JSP HTML code we can use the following
<p>
The name of the city is <jsp:getProperty name="address "property="city" />
</p>
Without using Java code, thus we can access property value of beans using the <jsp:getProperty /> tags
Includes and forwards:
JSP provides support for includes and forwards. It is possible to include a JSP file within another JSP file and also forward the request to another JSP file.
There are two kinds of include and one kind of forward
Static Include:
Static include happens at translation time, meaning it happens during the creation of the background servlet. This means that the include is done, when the JSP is getting compiled into a servlet, so that the included JSP is now part of the enclosing JSP.
<%@ include file="pathToFile" %>
All the content from the external file is included as if it were typed into the JSP page directly.
A classic example of includes are for static content like the Headers and the Footers.
<%@ include file="/header.html" %>
<%@ include file="/footer.html" %>
Dynamic Include:
The other kind of include which is the dynamic include is done using the <jsp:include> action:
<jsp:include page="pathToDynamicResource" flush="true" />
This include happens at request time and not at compile time. The server executes the specified dynamic resource and includes that output into the content sent to the client along with the output generated by the current JSP page.
Behind the screen, this <jsp:include /> action generates code that calls the RequestDispatcher’s include() method.
There are some limitations on the dynamically included JSP pages, that are worth mentioning: The included page set the HTTP status code, and cannot set any HTTP headers.
JSP forward:
A JSP may also forward a request using the <jsp:forward> action:
<jsp:forward page="pathToDynamicResource" />
The <jsp:forward> element forwards the client request information (the response to the client) from one JSP file to another file. The target file to which the forward happens can be an HTML file, another JSP file, or a servlet. The important thing is that the forwarded file must be within the same web application as the forwarding JSP file.
The lines in the source JSP file that makes the forward using <jsp:forward> element are not processed.
Behind the screen, this action is built on the RequestDispatcher’s forward() method.
JSTL – Java Standard Template Library
We were previously told that we should avoid Java code in JSP pages – and we saw one technique of using the <jsp:useBean /> in conjunction with the <jsp:setProperty /> and the <jsp:getProperty /> tags to acheive the effect of setting and getting values from the middle tier (business logic) to the presentation layer (the JSP pages)
JSTL goes one step ahead and gives us programmers an array of powerful tags for output, for control structures like conditions and looping and Java expressions using plain JSP tags, without using any scriplet code.
The purpose of JSTL was to allow JSP programmers to program using tags rather than Java code.
Setting up JSTL
To setup JSTL in our web applications, we need to add the following jars
- Download jstl-impl-1.2.jar from https://jstl.dev.java.net/download.html
- Copy the jstl-impl-1.2.jar to the webapps/<project-name>/WEB-INF/lib folder
- Modify web.xml and add entries for the taglib that we have added to the project lib folder
<webapp>
. . .
<taglib>
<taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
<taglib-location>/WEB-INF/fmt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location>
</taglib>
</taglib>
</webapp>
JSTL provides us with tags to access database code using JSTL tags and also XML manipulation using JSP tags – but we will leave those heavy weightlifting to be done on the middle tier business logic implementation in the Java code. On the JSP pages we will focus only on the Presentation.
The two important tags that we will be looking are the format tag and the core JSTL tags:
The <c:out /> tag
The <c:out> tag is used to print the value of an expression or a constant.
For example:
<c:out value="Hello" />
Expressions are denoted using the syntax as ${expression}
<c:out value="${1+2}" />
evaluates to the value 3
Accessing request parameter values:
Let us say we have a HTML element like this:
<input type="text" name="username" value="${username}" default="Nobody" />
The value for username given in the pageScope or requestScope or sessionScope can be accessed thus:
$ {pageScope.username}
$ {requestScope.username}
$ {sessionScope.username}
If no scope is mentioned, the default pageScope is assumed, and the JSP runtime looks for the username within the page scope.
If we were to look for the user name in the request scope, we would have to access it like this:
<input type="text" name="username" value="${requestScope.username}" default="Nobody in request" />
Similiarly for the session scope, we would have to access it like this:
<input type="text" name="username" value="${sessionScope.username}" default="Nobody in session" />
The <c:forEach /> tag
The forEach tag is used to access (and print) the items in a collection. Let say, we have a list of items called “fruits” in the session scope. Here’s how we access the items in the list:
<c:forEach var="fruit" items="${sessionScope.fruits}">
<c:out value="${fruit.name}" />
</c:forEach>
The if then tag
The if then tag, is used to test conditionality in the presentation layer:
For example:
<c:if test="${user.wealthy == 'true' } >
<p> U r wealthy </p>
</c:if>
Note that we do not have an else equivalent in JSTL – So for the above example, the else condition would have to be given like this:
<c:if test="${user.wealthy == 'true' } >
<p> You are wealthy! </p>
</c:if>
<c:if test="${user.wealthy != 'true' } >
<p> Oh...Pity You! </p>
</c:if>
JSTL provide powerful tag libraries that help us seperate content from the presentation. JSTL thus lets us write JSP presentation code without mixing Java code.
Summary:
JSP bring the separation of the Presentation layer from the business logic – and free the servlets from having to worry about generating HTML output for the user. JSP brings the missing piece in the Model View Controller architecture. This chapter helped us understand the following;
- Why we need JSPs
- Using the JSP bean tags
- Configuring and using JSTL in web applications.