Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Stardeveloper RSS Feed
Newsletter
Enter your email address below to be informed every time a new article is posted at Stardeveloper.com:

You can follow Faisal Khan on Twitter
Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (10)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)
Log In
UserName Or Email:

Password:

Auto-Login:

Miscellaneous Links
  Submit Article

Hosted by Securewebs.com
 
Home : J2EE : JSP : Introducing JavaServer Pages
 

Scriptlets are defined as any block of valid Java code that resides between <% and %> tags.

This code will be placed in the generated servlet's _jspService() method. Code that is defined within a scriptlet can access any variable and any beans that have been declared. There are also a host of implicit objects available to a scriptlet from the servlet environment.

Implicit Objects - Description
Implicit Objects - Description
Implicit Objects - Description

The following snippet shows both how to get a named parameter from the request object, and how to pass a string to the output stream for the page.

<%
	String var1 = request.getParameter("lname");
	out.println(var1);
%>

Having discussed implicit objects, we're in a better position to understand the code featured in the comment for the PageContext source from the JSP 1.0 reference implementation. This shows the code that the JSP 1.0 reference engine injects into the JSP page's _jspService() method.

public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
	JspFactory factory = JspFactory.getDefaultFactory();
	PageContext pageContext = factory.getPageContext(
this, // servlet
request,
response,
null,  // errorPageURL
false, // needsSession
JspWriter.DEFAULT_BUFFER,
true   // autoFlush
);

	// Initialize 
implicit variables for scripting environment
	HttpSession session = pageContext.getSession();
	JspWriter out = pageContext.getOut();
	Object page = this;

	try 
{
	// Body of translated JSP 
here...
	} catch (Exception e) 
{
	out.clear();
	pageContext.handlePageException(e);
	} finally 
{
	out.close();
	factory.releasePageContext(pageContext);
	}
}

JspFactory returns the pageContext implicit object, from which the other implicit objects are obtained for the duration of the _jspService() method.

A JSP expression is a very nice tool for embedding values within your HTML code. Anything between <%= and %> tags will be evaluated, converted to a string, and then displayed. Conversion from a primitive type to a string is handled automatically.

The current price of item A100 is
	<%= request.getParameter("price") %>

Something you'll want to note is that the expression doesn't end with a semi-colon. That's because the JSP engine will put the expression within an out.println() call for you.

JSP expressions allow you to essentially parameterize HTML (just as you would parameterize a SQL query that differs by only a couple of values). Again and again, your code will set up conditions and loops using a one-line JSP scriptlet and then include the HTML code directly beneath it. Simply enclose the beginning and the ending of the condition or loop in separate pairs of <% and %> tags :

<% for (int i = 0; i < 10; i++)
	{ %>
	<br>
	Counter value 
is <%= i %>
<% } %>

Coding JSP Pages
A big advantage in developing a JavaServer Page is that you can code the HTML without enclosing it in Java code, as you must do in a servlet. You can then take advantage of HTML editors to develop your content.

So from the drudgery of coding HTML output in servlets, we've arrived at the flexibility of coding Java snippets into the HTML page. But don't be dragged too far the other way. Heard of the people who can't fit their ASP files into Notepad? And if there's one problem with ASP and JSP, it's debugging the pages, making improvements to them, and untangling the meaning of that section you coded months back.

The "third way" is a mixture of presentation-based calls to a Bean or servlet, which components can be better tested, are well-encapsulated and good OOP citizens. This moves from embedding code to embedding components and action tags in the page.

Note: The current reference JSP implementations don't automatically reload the new Bean if you recompile while the server is running. You'll need to restart the servlet engine.

So, when setting up an application development architecture that involves JavaServer Pages, it is a good idea to try and put all of your business logic inside reusable components. These components can then be 'plugged' into any JavaServer Page that requires them.

What is a JavaBean?
The Java language has implemented the idea of a component as something called a JavaBean. A JavaBean is a Java class that fits the following criteria :

  • Public class.
  • Public constructor with no arguments.
  • Public set and get methods to simulate properties. The get method has no arguments, unless it acts on an indexed property.

The JavaBeans architecture uses reflection to infer the public methods. But you can provide a BeanInfo class, called BeanName BeanInfo to give more explicit information.

A bean can also be serialized and saved for later use. It does this by implementing the Serializable interface. When a bean component is serialized, it saves its current state. The current state of a bean is defined by the current values of its public properties.

Properties are always set and retrieved using a common naming convention. For each property, two methods must exist, a getxxx() and setxxx() method (where xxx is the name of the property).

Apart from that a bean is just like any other Java class. Typically, a bean component is imported into a program, its properties are set and its methods are called.

Most of the time beans are used to encapsulate visual and non-visual elements of a GUI. There's some snazzy stuff to link beans up, to implement drag-and-drop and to save the state of a bean between instances. The ultimate aim is to make them part of graphical application assembly tools. I found that once I stopped thinking about these graphical tools and concentrated on it just being a class that follows a few design patterns, things were easier to understand!

Because of this history, Beans don't sit obviously in JSP. Don't get me wrong - they work well. But it's not what they were originally designed for. If we think of them as components, simple encapsulations of Java code, then their purpose is clearer. Beans mean that your page isn't clogged with code.

Much of the business logic we're hinting at might be better placed in an Enterprise JavaBean, where the transactions and scaling issues are explicitly the problem of the container and not the bean. That kind of heavyweight use may be necessary sometimes but I think that beans will stay around for the lighter work we show here. And beans as graphical components of your final web page, for a richer user interface, will be another expression of their code- and complexity-wrapping role.

To show how to use a simple bean, we're going to develop the alphabet example from earlier, and associate each letter with a color.

The presentation of the letters will remain the responsibility of the JSP page, but the color mapping will be the bean's job.

Scriptlets are defined as any block of valid Java code that resides between <% and %> tags.

This code will be placed in the generated servlet's _jspService() method. Code that is defined within a scriptlet can access any variable and any beans that have been declared. There are also a host of implicit objects available to a scriptlet from the servlet environment.

Implicit Objects - Description
Implicit Objects - Description
Implicit Objects - Description

The following snippet shows both how to get a named parameter from the request object, and how to pass a string to the output stream for the page.

<%
	String var1 = request.getParameter("lname");
	out.println(var1);
%>

Having discussed implicit objects, we're in a better position to understand the code featured in the comment for the PageContext source from the JSP 1.0 reference implementation. This shows the code that the JSP 1.0 reference engine injects into the JSP page's _jspService() method.

public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
	JspFactory factory = JspFactory.getDefaultFactory();
	PageContext pageContext = factory.getPageContext(
this, // servlet
request,
response,
null,  // errorPageURL
false, // needsSession
JspWriter.DEFAULT_BUFFER,
true   // autoFlush
);

	// Initialize 
implicit variables for scripting environment
	HttpSession session = pageContext.getSession();
	JspWriter out = pageContext.getOut();
	Object page = this;

	try 
{
	// Body of translated JSP 
here...
	} catch (Exception e) 
{
	out.clear();
	pageContext.handlePageException(e);
	} finally 
{
	out.close();
	factory.releasePageContext(pageContext);
	}
}

JspFactory returns the pageContext implicit object, from which the other implicit objects are obtained for the duration of the _jspService() method.

A JSP expression is a very nice tool for embedding values within your HTML code. Anything between <%= and %> tags will be evaluated, converted to a string, and then displayed. Conversion from a primitive type to a string is handled automatically.

The current price of item A100 is
	<%= request.getParameter("price") %>

Something you'll want to note is that the expression doesn't end with a semi-colon. That's because the JSP engine will put the expression within an out.println() call for you.

JSP expressions allow you to essentially parameterize HTML (just as you would parameterize a SQL query that differs by only a couple of values). Again and again, your code will set up conditions and loops using a one-line JSP scriptlet and then include the HTML code directly beneath it. Simply enclose the beginning and the ending of the condition or loop in separate pairs of <% and %> tags :

<% for (int i = 0; i < 10; i++)
	{ %>
	<br>
	Counter value 
is <%= i %>
<% } %>

Coding JSP Pages
A big advantage in developing a JavaServer Page is that you can code the HTML without enclosing it in Java code, as you must do in a servlet. You can then take advantage of HTML editors to develop your content.

So from the drudgery of coding HTML output in servlets, we've arrived at the flexibility of coding Java snippets into the HTML page. But don't be dragged too far the other way. Heard of the people who can't fit their ASP files into Notepad? And if there's one problem with ASP and JSP, it's debugging the pages, making improvements to them, and untangling the meaning of that section you coded months back.

The "third way" is a mixture of presentation-based calls to a Bean or servlet, which components can be better tested, are well-encapsulated and good OOP citizens. This moves from embedding code to embedding components and action tags in the page.

Note: The current reference JSP implementations don't automatically reload the new Bean if you recompile while the server is running. You'll need to restart the servlet engine.

So, when setting up an application development architecture that involves JavaServer Pages, it is a good idea to try and put all of your business logic inside reusable components. These components can then be 'plugged' into any JavaServer Page that requires them.

What is a JavaBean?
The Java language has implemented the idea of a component as something called a JavaBean. A JavaBean is a Java class that fits the following criteria :

  • Public class.
  • Public constructor with no arguments.
  • Public set and get methods to simulate properties. The get method has no arguments, unless it acts on an indexed property.

The JavaBeans architecture uses reflection to infer the public methods. But you can provide a BeanInfo class, called BeanName BeanInfo to give more explicit information.

A bean can also be serialized and saved for later use. It does this by implementing the Serializable interface. When a bean component is serialized, it saves its current state. The current state of a bean is defined by the current values of its public properties.

Properties are always set and retrieved using a common naming convention. For each property, two methods must exist, a getxxx() and setxxx() method (where xxx is the name of the property).

Apart from that a bean is just like any other Java class. Typically, a bean component is imported into a program, its properties are set and its methods are called.

Most of the time beans are used to encapsulate visual and non-visual elements of a GUI. There's some snazzy stuff to link beans up, to implement drag-and-drop and to save the state of a bean between instances. The ultimate aim is to make them part of graphical application assembly tools. I found that once I stopped thinking about these graphical tools and concentrated on it just being a class that follows a few design patterns, things were easier to understand!

Because of this history, Beans don't sit obviously in JSP. Don't get me wrong - they work well. But it's not what they were originally designed for. If we think of them as components, simple encapsulations of Java code, then their purpose is clearer. Beans mean that your page isn't clogged with code.

Much of the business logic we're hinting at might be better placed in an Enterprise JavaBean, where the transactions and scaling issues are explicitly the problem of the container and not the bean. That kind of heavyweight use may be necessary sometimes but I think that beans will stay around for the lighter work we show here. And beans as graphical components of your final web page, for a richer user interface, will be another expression of their code- and complexity-wrapping role.

To show how to use a simple bean, we're going to develop the alphabet example from earlier, and associate each letter with a color.

The presentation of the letters will remain the responsibility of the JSP page, but the color mapping will be the bean's job.


Previous ( 1 Gone )( 5 Remaining ) Next

See all comments and questions (post-ad) posted for this tutorial.


Buy This Book From Amazon
Title: Professional Java Server Programming: with Servlets, JavaServer Pages (JSP), XML, Enterprise JavaBeans (EJB), JNDI, CORBA, Jini and Javaspaces
Publisher: Wrox Press Inc
Price: $59.99
Pages: 1121
DatePublished: August 1999



Comments/Questions ( Threads: 4, Comments: 6 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. How to wright XML file using jbean or jsp or java or jdom
  2. Java Beans ( 1 Reply ) This thread contains 1 reply by Faisal Khan.
  3. Where is the property ( 1 Reply )
  4. JSP date&time

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed to.

 
© 1999 - 2009 Stardeveloper.com, All Rights Reserved.