Tag Archives: Jsp

Revised Jsp Best Practices

JSPs are an integral part of a web application. If jsps are not coded properly, then it becomes a most unorganized piece of code. You must have seen huge jsps, which end up as a source of defects, and asking you to change them many times. Maintaining such code becomes a very expensive activity. Also it impacts stability of entire application. Following few simple practices can change working on jsp into a happy activity.

1. Reuse Common HTML

There are two main advantages of it. First is – you are maximising reuse and improving productivity. Second is – you are keeping main jsp as small as possible to maintain them better. Small jsp will also help to easily debug. Better way of reusing code is moving the html code to another jsp, and including that jsp at appropriate place. Mostly header and footer information can be common which can be included in each Jsp. You can identify such reusable html code snippets in your jsps, and seperate those out.

2. Separate Javascript

First good practice would be reducing the java script as much as possible. But under un-avoidable circumstances move it to javascript (js) files and including those in all required jsps. Also, grouping those javascript functions according to functionality is a good idea, this will reduce the amount of javascript you include in each page. Also think of including javascript at the bottom of page instead of top to improve performance.

3. StyleSheets can be Used to Define Themes

This is another component which can be separated out and reused. But there are broader applications of stylesheets. Stylesheets with images and other static contents, contribute to look and feel of a site/all html pages. Now providing theme based styling of site is becoming popular. If you can build some level of theme based stylesheet application some how, then it will be good. Few web tier frameworks (Spring MVC, etc.) offer the feature of theme based look and feel. Depending on other aspects, you can choose one of those. At least you can separate code in stylesheet and include in all jsp pages.

4. Maximise Use of Ready Custom Tags

Select appropriate freely available custom tag library. If possible check if there are any defects in those libraries with respect to the technology set you are selecting. Also see which one provides you maximum number of required features. JSTL tag lib is a mostly used alternative. Also, you can opt for the libraries provided by the selected framework. Struts comes with a rich tag library, which supports many common application features and also advanced features like AJAX.

5. Identify and Build Application Custom Tag Library

This makes life easy of all the developers of application. You put early effort and identify the tag libraries you need in your application. Build those and make available at the time of coding start. This improves productivity considerably and stops all developers from messing up the code in their own style.

6. Use Javabean Based Client Server Data Transfer

Struts, Spring MVC, Tapestry, and JSF provide MVC based frameworks, which enable automatic population of the client submitted data in the defined java beans. This means you don’t need to retrieve all atributes separately from http request in servlet. You can implement your own mechanism for this, if you are not using any framework.

7. Select Appropriate Web-tier Framework

This is clearly a strategic decision to go for a ready framework or not. How your organization permits and how your requirements are satisfied, this will determine which framework you select from Struts, Sprint MVC, Tapestry, JSF, etc. and the supporting frameworks like Velocity, Tiles etc. Identify the benefits according to your needs and select appropriate one. Secondly, also check the support availability for the selected framework.

8. Enable Client Side Caching of Static Contents

Here we come to something related to performance. You may have heavy images and other static contents embedded in your jsp.You may not be changing these everytime the page is loaded. You can enable caching of these items so that the end user gets feel of quick loading of page. Also see how your server’s web container supports this.

9. Define Object Scope Correctly

It is possible that unwanted objects are loitering jsp default objects (session, page, request etc.) un-necessarily, and you get wrong results due to garbage objects. Hence identify scope of objects correctly, and place those in appropriate scope object. This will ensure cleaning of those objects in due time.

10. Identify and Design Special Handling of Browser Buttons

Some times you need to take care of browser buttons separately. It can be refresh button, back button or even browser close button, finalize the requirement and implement it at common place so that all jsp pages can use it.

11. Optimize Amount of Data Getting Displayed

This has to do with identifying and negotiating requirement at right time. If you want the page to be loaded very quickly, then trade off against the amount of data you load on the page. Otherwise, redesiging page after performance testing cycle will be a huge effort.

12. Use Jsp Comment Over HTML Comment

You may not want to send comment data to client. Mostly comments are for developer understanding from maintainability point of view. Hence you don’t want to increase the amount of data getting sent to client side. Hence use jsp comments, which do not get included in the html getting sent to client.

<!– HTML –>
<%– JSP does not go to client to clog network –%>

13. Set Page Caching and Expiry as Required

If you want your page to be loaded everytime a fresh, then set the caching and page expiry meta data directives correctly. Also consider the static data caching point above while doing this.

Java Server Faces (JSF) Tutorial

JSF – Java Server Faces is a web tier technology. This technology is different from other JEE web tier technologies in many aspects. This tutorial helps you to understand building blocks of JSF, compares it with other web tier technologies like Struts, Spring MVC etc. Following detailed articles constitute this tutorial.

JSF Hello World Example on Eclipse and Tomcat: An example code that can be a starting point for your trials of JSF technology.

Mapping JSF with Other Web Tier Technologies: This article explores similarities, and differences amongst JSF and other web tier frameworks.

Applying Java Server Faces Technology (JSF) to JSP: In this article, we find out the changes that we have to make to user jsp with JSF.

JSF Request Handling Life Cycle: Here we discuss the two scenarios of JSF request handling cycles.

Applying Java Server Faces (JSF) Technology to Jsp

Normally, a jsp contains static and dynamic contents. Static contents are written using html while dynamic contents are executed at server side, and the resultant data is presented again in html format. When a page is presented in a browser, it contains sequence of html tags that are nested to present view elements and data. When we are working with JSF, the presented page is still the same, but the way jsp code is written, and the way it is processed by the container, there is major difference. Let us see what we have in Jsf.

Logical Description of Jsp Compoents:

  • Everything is a component. Text fields, tables, rows, columns, hyperlinks, buttons, forms etc. are components. All these components are encapsulated in view component. Also, these components can be nested.
  • Some of the components can be liked to backing bean (POJO) attributes.
  • Each component is eligible for few events. The events can be value change events e.g. in case of text box, we enter something, or action events e.g. button press. Applicable events can be attached to the components.
  • Some of the components will require certain validation. Validators performing such validations can also be attached to the components.
  • Values entered by user will require conversion to a data type of liked backing bean attribute. Such convertors can also be defined for components.
  • Finally, all above components, validators, convertors and components are readily available with JSF framework (mainly in the form of custom tags). If you require anything different, then there is facility to write your own custom elements also.

In next section, let us actually see implementation details of above components.

Implementation Details of Jsp Components:

In this section, we are not going in details of each component. Detail documentation is available in Jsf tag library reference. Here we extract a quick reference for all important components, which mostly we need when we write a Jsp with Jsf framework.

  • Custom Tag Declaration: Jsf provides to core tag library, which is independent of any rendering toolkit. In addition to that, it also provides html tag library, which is actually html rendering kit. If we are using html renderer provided by Jsf then we need to import both the libraries here. We can also opt to use JSTL tag library instead and get rid of these. But this means we don’t want to use component based request handling of Jsf. Add following declaration to the jsp. Wherever applicable, we are going to refer to this declaration prefixs.

<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>

<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>

  • View Tag: Each component we include in our jsp should be enclosed in this view tag. This is the base for everything that is presented on browser. It is also required to enclose all Jsf component tags inside a view tag.

<f:view>

………..

………..

</f:view>

  • Form Tag: Everything that needs to be submitted to the server will be enclosed inside form tag. This tag we are going to use from the html tag library.

<h:form>

………..

………..

</h:form> 

  • UIInput Tags: As the name means, these tags handle the data (mostly user entered data) submission to the FacesServlet. These tags belong to html tag library. There are four possible renderers to these tags – Hidden, Secret, Text and Text Area. We can attach validators and convertors to these components only. Following UIInput component tags are available in Jsf.
    • inputHidden – Renders hidden text
    • inputSecret – Renders password fields
    • inputText – Renders text box.
    • inputTextarea – Renders text area field

<h:inputText id=“firstName”></h:inputText>

  • UIOutput Tags: These html tags are used to render data out. Label, link, outputmessage and text are the renderers available with this tag. Following UIOutput component tags are available.
  • o outputLabel – Renders label
  • o outputLink – Renders a link
  • o outputFormat – Renders message
  • o outputText – Renders output text

<h:outputText value=“First Name”></h:outputText>

  • Linking with Backing Bean: Backing bean is a POJO, which can be used for two purposes. First to link the UIInput tag values to the attributes of it (POJO/backing bean). Second is linking actions to the methods doing processing and returning result.

<h:inputText id=“firstName” value=”#{helloWorldBean.firstName}” required=“true”>

</h:inputText>

<h:commandButton action=”#{helloWorldBean.sayHelloWorld}”

                        value=“Get Complete Name”></h:commandButton>

  • Validators: Validators can be the validators provided by Jsf or we can also build custom validators. These validators are attached to the components that get data input i.e. UIInputs.

<h:inputText id=“firstName” value=”#{helloWorldBean.firstName}” required=“true”></h:inputText>

  • Convertors: Convertors convert the values submitted from client to a data type required by the mapping backing bean attribute. Jsf provides a set of standard convertors. We can also write a custom convertor and attach it to a component derived from UIInput.

<h:inputText id=“id” value=”#{helloWorldBean.id}” required=“true” converter=”javax.faces.convert.IntegerConverter>

                  </h:inputText>

 

  • Displaying Messages: This is another concern a developer needs to handle, display error messages in appropriate language and format. Language concern is explained below. Jsf html tag library has message tag that can be used to render a message. Style attribute of this message is to format the message.

      <h:message id=“errors” for=“firstName” style=“color:red”/>

 

  • Localization: Localization is presenting information in the language of user. Business data localization is to be implemented programmatically through backing beans, but Jsf provides ability to localize the static contents i.e. labels, messages etc. in desired language. Localization can be achieved in two steps.
    • Including resource bundle in desired language.

<f:loadBundle var=”bundle_en”

basename=”messages.CustomerMessages” />

  • ?
    • Using resource bundle contents.

<h:outputText value=”#{bundle_in.firstName}”/>

 

  • Additional Tags: Following additional tags are used for specific component rendering.
    • UIPanel: It provides container to group multiple components.
    • dataTable: Used for data bound tables.
    • graphicImage: Used to render images.
    • selectBooleanCheckbox: Radio button in different formats
    • selectManyCheckbox: Multiple value selection
    • UISelectXXXXX: Select (option/combo box) components having UISelectItem, UISelectItems and UISelectItemGroup components.

Backing Beans:

Similar to Struts and Spring MVC framework, these backing beans are actually Plain Old Java Objects (POJOs). Attributes of these Java classes are liked with components to transfer data between client and server. Other operations can be linked to submit actions on pages. FacesServlet does the job of population of these objects, from the component values and vice versa. It also executes the backing bean method mapped to an action.

Summary:

Jsf does use the Jsp technology to build a view, but now everything is a reusable component with different execution lifecycle.

 

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.

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