Monthly Archives: April 2009

Using Jsp Technology

I wouldn’t be biased if I were to say that JSP technology is one of the most favorite presentation/web tier technologies at present. After it’s introduction in JEE technology platform, there has been considerable change in the middle tier technology and data access technology, but the front end tier is mostly built using a JSP. There may  be a wrapper in which the JSP is embedded to achieve few additional features, but the base still remains a JSP. Let us take a close look at the different uses of JSP technology at the front end tier.

Plain JSP:

By plain JSP, we are talking about a JSP not surrounded by any other technology. Here when it comes to displaying a page to the client, the response is presented using a jsp page. When the middle tier finishes its processing, it sends/forwards the result to a JSP page (XYZ.jsp). This single page does everything to present the result. This page may arrive at the final result using following options.

  • Jsp using HTML: Jsp is constructed using HTML for static/text contents and JSP elements for dynamic contents.
  • Jsp using XML: In this approach, a jsp is constructed using XML (eXtensible Markup Language). By using XML, we can make the jsp code look neat, as well as we can use features of XML.
  • Jsp with SVG: This is a specialized use of Jsp technology to build presentation tier of two dimensional graphics and graphical applications. Scalable Vector Graphics targets front end of mobile devices.
  • Jsp with WML: This is another specialized use of Jsp in mobiles. Wireless Markup Language is used to write pages which are displayed in devices that implement Wireless Application Protocol (WAP). In short jsps built using WML are displayed in WAP browsers.
  • Including reusable components like stylesheets, javascript, other jsp pages, custom tags: These components provide support to build a single page using jsp technology.
  • o Stylesheets separate the look and feel or formatting definition classes to a file so that it can be reused.
  • o Similarly javascript files separate javascript functions in a different file, which can be included in many jsps and reused.
  • o There may be some code which will be common in all/many jsps in an application. We can separate this code in another jsp file and include it in each jsp (in static or dynamic way).
  • o Custom tags is another powerful way of reusing jsp code. In addition to reuse, these components make the jsp look neat by replacing large chunks of code with a tag. This also reduces the jsp writing time.

Details of Jsp technology can be found in this Jsp Tutorial.

JSP with Servlet:

If we look at the lifecycle of a jsp, we can see, that the jsp has actually a generated a servlet which is doing the job for us. Hence, a jsp gets converted into a servlet and the sevlet runs in the web container. But there is this interesting design pattern which uses a jsp with servlet. You may ask why do we need two servlets when a jsp can do the job of a servlet? The answer is – two important concerns are separated in this approach, viz. presentation and navigation. Jsp is used to handle the presentation business only. Servlet deals with navigation logic and the logic to call services in middle and database tier (if applicable).

Jsp Templates:

This is another way of reusing jsp code. Here we define jsp template that is in line with the standard layout of our application. Each jsp is constructed by replacing the template elements with appropriate components.

Jsp and Tiles:

Tiles take the jsp template to the next level. Tiles ask us to define a layout (s) which is (are) the base for the jsps we write. These layouts contain string and jsp elements placeholders that can be dynamically injected. There is an xml file which has a definition, that tells the container, how to construct a page. The construction includes usage of layout, and replacement of the placeholders. E.g. in layout we define placeholders for headers, footers, left menu and body of a jsp. Whenever we construct a page, we replace these place holders with appropriate pages.

Jsp and Struts:

To integrate a Jsp with Struts, we need to specify the forward path to a jsp either in struts-config.xml or in an Action class itself. Struts does allow us to use tiles. In that case, the integration is done through tiles definition. Also, Sturts has action form, which can be used while the data gets submitted to server. This form is populated and made available through the request object.

Jsp and Java Server Faces:

Java server faces creates a difference in the way we use jsp. When we integrate these two, a jsp page will contain Java Server Faces (JSF) tags. These tags are linked to server side registered components. Each component may have associated listeners, validators and converts with it. We need to be careful while integrating these two technologies as now we are having two server-side components. The first server-side components are the dynamic elements of a jsp and the second are the JSF tags. If we do not consider compilation, execution and rendering mechanism of these two technologies, then it is possible that we end up in a performance problem.

Jsp and Spring MVC:

This is similar to Struts, difference being the implementation is a bit light. Some of us may find Struts a little complicated as compared to Spring MVC, but as long as our scope is jsp integration, they are same.

Here is a good example of Jsp with Tiles and Spring MVC.

Implicit Objects in JSP

Implicit object are those objects which are available in jsp by default. Developer does not need to declare these objects, the web container creates them. What would be rational behind creation of such objects? Why would thecontainer create these objects? Can we not work without these objects? We will try to find answers to these questions in this article.

Web container executes the JSP page as a servlet. Servlet operates in request – response model. All objects, that are associated with any servlet by default, are part of this implicit object group. Each servlet has information related to the container’s environment, the servlet itself, the interaction session with user, definitely the request and response, etc. This information along with information related to the jsp page itself, is made available to the jsp via the implicit objects. The following is a list of jsp implicit objects:

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

Let us look at these objects in detail.

request:

  • Request object represents the request made by a client to the servlet.
  • This request is passed as an instance of javax.servlet.HttpServletRequest object.
  • This is an input parameter to the jspService() method.
  • Contains http header, request attributes, session etc.

response:

  • It represents the response generated by the servlet.
  • This is an instance of javax.servlet.HttpServletResponse class.
  • This is another input parameter to the jspService() method of the generated servlet.

pageContext:

  • Using this object, we can interact with the servlet container.
  • It is an instance of javax.servlet.jsp.PageContext class.
  • Container can manage page attributes like error pages, forwarding pages and including pages using this object.

session:

  • Represents the session between client and servlet (server).
  • Instance of HttpSession class.
  • Can be used to store attributes applicable to user session and not request.

application:

  • It is an instance of ServletContext class.
  • Used to share data amongst servlets, jsps and html pages in an application.

out:

  • This object is used to send output to the client.
  • It is an instance of javax.servlet.jsp.JspWriter class.
  • Based on the content type defined, the output will be generated.
  • Some of the methods available are print, println, flush, etc.

config:

  • This represents the servlet configuration.
  • It is an instance of javax.servlet.ServletConfig class.

page:

  • Represents the instance of generated servlet – “this”.

exception:

  • It is an instance of java.lang.Throwable class.
  • It encapsulates the exception thrown by the servlet.
  • If the jsp contains page directive for error page, then this exception is forwarded to that page.

To summarize, implicit objects are available in the jsp by default, and these objects can be used to serve a definite purpose which would otherwise be difficult.

<<Previous   Home   Next>>

Request Handling in JSP

A JSP works using http request – response model. Client browser sends a http request to the web container which is handled by the servlet from JSP. The request is executed by jspService() method and generated response is sent back. This transaction involves many data objects, which are used to encapsulate specific data. These objects may contain business data or environment data. It is important to define the extent of data sharing allowed by these objects. Defining scope of these object puts restriction on sharing of these objects in this request-response cycle. In addition to this, the request itself can be forwarded or redirected before generating final response. In this article, we will look as these request processing aspects. Following four main points are discussed in detail.

  • Scope
  • Include
  • Forward
  • Redirect

Scope:

Scope attribute defines the context in which any object will be available. Based on this availability information, we can use different objects. In a Jsp, there are following four scopes identified.

  • page: page maps to the jspService() method of generated servlet. Hence an object with page scope is available in service method only.
  • request: Request originates from a client browser and is executed in the jspService() method of generated servlet, to result in a response. Objects with this scope are available as long as the request object is available. These objects can be retrieved from the request object using getAttribute method.
  • session: This scope is larger than the request scope. Session scope lasts as long as the user session exists. Similar to request scope, these objects can also be retrieved using getAttribute method.
  • application: In this scope, the object is bound to ServletContext object. This scope is higher than the session scope and the object will get shared amongst different sessions of same user or sessions of different users. Here also ‘getAttribute’ method can be used to retrieve the object.

The scope goes on increasing in sequence from page, request, session to application.

Include:

Jsp components are included to increase reuse of code. We can include these components using either static include or using dynamic include. Static include is implemented using <%@include file=”filename”%> syntax. This include inserts the contents of included file in the jsp. Thus a new jsp is created after all inclusions. Requests are handled by the servlet generated from this new jsp. There is no other change in request-response model. Here the file can be html, jsp, image, etc.

Dynamic include is different from static include in many aspects. It is implemented using <jsp:include page=”filename”/> action element. While translating the jsp, container converts this include into a method call. During runtime, the method will be executed to render the page. This included page will have access to all implicit objects of the parent jsp. Only html and jsp pages can be included using this method.

Forward:

<jsp:forward page=”url”/> is used to forward request to another page. Target page will execute the request and send response to client. Attributes to be forwarded to target page can also be included in this tag.

Redirect:

In this scenario, the request will be redirected to a new resource. HttpServletResponse object’s sendRedirect() method is used to implement this. In redirect, the response of first request is returned to client browser and browser issues a new request all together.

<<Previous   Home   Next>>

Java Server Pages Standard Tag Library (JSTL)

Along with JSP technology, Sun offered a standard tag library called JavaServerPages Standard Tag Library (JSTL). In the previous article on custom tags, we have gone through the advantages of using custom tags. This tag library provides all those standard tags that will lead to any kind of javascript in the JSP. This tag library also covers conditionals, iterators, XML document manipulation tags, internationalization and DB access tags. These tags are grouped in following categories

  • Core
  • XML
  • Internationalization
  • SQL
  • Function

Using JSTL:

This tag library can be used in the same way as any other custom tag library. Jsp using this custom tag will look like this.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Custom Tag Example</title>
</head>
<jsp:useBean id="customer" scope="page" class="com.myorg.jsptutorial.Customer"></jsp:useBean>
<body>
  <h1><c:out value="${customer.name}"/></h1>
</body>
</html>

First, we are using the taglib directive to declare the tag library. Next is the prefix=”c”, this is used to make a call to the tag library through tag <c:out…./>. This tag just prints value of the customer object’s name attribute. It calls getName() method on this object.

Now let us look at the details of each of the above tag library.

Core:

XML:

  • Uri – http://java.sun.com/jsp/jstl/xml
  • Prefix – x
  • Used for core, flow control and transformation of xml

Internationalization:

  • Uri – http://java.sun.com/jsp/jstl/fmt
  • Prefix – fmt
  • Used for internationalization tasks like locale, message formatting, number and date formatting.

SQL:

  • Uri – http://java.sun.com/jsp/jstl/sql
  • Prefix – sql
  • Used for database interaction related tags.

Function:

  • Uri – http://java.sun.com/jsp/jstl/functions
  • Prefix – fn
  • Used for few functions on collection and string.

<<Previous   Home   Next>>

Unified Expression Language for JSP

Expression language (EL) became part of Jsp with verion 2.0. It is mainly for web-side development by providing easy access mechanism to Java beans. In recent version of JEE, it has been changed to Unified Expression Language. In Jsp 2.1, the expression language is unified with expression language for Java Server Faces (JSF) technology (version 1.0). The reason is simple, both the technologies are used to write presentation tier or web tier, hence the language used to write this should be unified. Let us see what are the additional features of JSF, that are combined with EL.

EL allowed access to the Java beans using ${expression}. In addition to this, following JSF expression language features are integrated now.

  • Deferred evaluation of expressions
  • Ability to get and set data
  • Ability to invoke methods

Important features of the Unified Expression language are discussed below.

Evaluation:

Two options are possible here, immediate evaluation where the expression is evaluated immediately and the value is printed in jsp, deferred evaluation where the evaluation is done by the technology using expression language at run time/whenever required. Immediate evaluation is implemented using ${….} while deferred evaluation is implemented using #{….}.

Value Expressions:

Return value after evaluating expressions. Two categories are possible for value expressions, Rvalue- read data and Lvalue – read and write data. Expressions with ${user.firstName} are always Rvalue while #{user.firstName} can be Rvalue or Lvalue depending on underlying technology evaluation.

Method Expressions:

These are similar to the value expressions, except that there would be actual method call on the bean instead of a get or set method call. Hence ${user.validateUser} will result in validateUser() method call on the user object.

Implicit Objects:

These implicit objects are available in unified expression language – pageContext, servletContext, session, request, response, param, paramValues, header, headerValues, cookie, initParam.

Scope Objects:

Objects can be retrieved using these scope objects. Different scope objects available are pageScope, requestScope, sessionScope, applicationScope. Syntax is ${sessionScope.userProfile}.

 <<Previous   Home   Next>>

Using Custom Tags in JSP

If we look at the open source frameworks for presentation tier, you will find most of them providing custom tag libraries for the Jsp development. This should be enough to tell us the importance of custom tags in jsp technology. The biggest advantage of custom tag is improved reusability. There are many other advantages like minimization of Java code in Jsp, ease in usage of custom tag, reduction in the size of jsp code, etc. Considering the importance of custom tag, it is always good to identify the external and internal tag libraries in early design phases. Application specific custom tags will also help in reducing the effort required in development of a jsp. Let us understand the details of custom tag and finally write our own custom tag.

Using Java Beans in JSP

Java bean is a Plain Old Java Object (POJO) having few attributes and getter and setter methods in it. These POJOs can be used in JSPs to send data to the server. It reduces the amount of Java code that exists in a JSP. Also the JSP will contain the presentation details only. Data handling is moved to the Java bean in this approach. This can be achieved using following simple steps.

Elements of Jsp

Elements of jsp are specified like an element in html or xml, i.e. with opening and closing tags. There are many types of elements in jsp. Here is the list of these elements.

JSP Life Cycle

In previous article we wrote our first jsp. In this article, we will go further and see how a jsp is displayed using web container. When a web container or servlet container receives a request from client for a jsp page, it takes the jsp through its various life cycle phases, and then returns the response to the client. What all things these containers should support, is defined by the jsp and servlet specifications. The web containers can be a part of web servers, e.g. tomcat, and application servers.

Introduction to Java Server Pages (JSP)

Java Server Pages (JSPs) technology is to present web contents to users. In addition to presentation of a page to user, jsp technology offers many things.

Powered by WordPress | Designed by: seo service | Thanks to seo company, web designers and internet marketing company