Sunday, April 29, 2007

Making a simple JSF application

Here's how we build a simple JSF application:

  1. Configure web.xml for FacesServlvet
  2. Create faces-context.xml (This is the file from where FacesServlet reads navigation rules, details of managed beans and other JSF specific configuration details)
  3. Create a controller or controllers for the application. Here is where JSF differs from Struts. Struts had a front controller, the ActioServlet which delegated requests to Action classes. JSF does not have the notion of a front controller. A JSF application uses an event model. The UI is tied to the backend with events. Controller classes (also known as backing beans in JSF) accept these events and also hold properties that accept user supplied values from a form. These properties will also be used to display data on pages. For example if we have a simple application that allows employees to put in a leave request, a backing bean will have properties that will be populated with the request that the user enters on the form. The same backing bean may also be responsible for displaying the leave status to the user. Essentially we will have one backing bean class for a related set of UI views. The view pages for adding, editing, viewing, and deleting "leave requests" will be mnaged by the same backing bean class. A JSF application can have many backing beans, thus resulting in many controllers. Even though we can code business logic in these backing beans, we should desist from doing so. The business logic must in other application classes which are invoked from the backing bean. This way the backing bean acts as a glue between the view and the model (which is what a controller should be doing anyways).
  4. Create the view (JSP) files.
    1. All the JSF tags should be put within an f:view tag. Components placed within this tag are managed by the JSF system. If we not use f:view, then the JSF system will remain oblivious of the components.
    2. Fields in a JSF form can be associated with beacking bean properties using JSF - EL. For example #{BeanName.PropertyName}. JSF-EL is similar to JSTL-EL, however, it directly associates a field (within which it is used) with a backing bean property (or a properties property). These properties are used to hold values submitted by users as well as hold values that will be displayed to the user on a form.
    3. We can associate commandButtons to methods in the backing beans, using JSF-EL. I believe we can associate them with events, in which case appropriate event handlers will be invoked[verify this].
    4. The JSF system can also run simple validations on the form fields automatically. Things like required fields, or fields that represent numbers can be validated automatically. More complex validations can be defined in custom validators.

Friday, April 27, 2007

Creating a custom component

The primary responsibility of a component is to decode and encode data.
encode = convert request parameters to component attributes
decode = render component attributes to the view (render html mostly...)

The rendering can be directly implemented by the component or can be delegated to a renderer. We use a special renderer(s) when we want different types of rendering for that component (maybe for different display devices).

So a JSF component has 2 parts: the component + renderer


Image by Rick Hightower explaining on where rendering fits in the JSF lifecycle - Ref


All custom components have to be subclasses of UIComponent. However, we subclass UICOmponentBase which is an abstract class that gives us a skeletal implementation of UIComponent.

Creating the custom component:
As an exercise, I will create a simple custom component that renders a 5x5 grid (as an html table). Here are the steps:
  1. Create a subclass of UIComponent (I chose UIOutput, since this is an output only component, ie. we do not modify the component from the view). This class does not have any properties at the moment, since the component is a simple display component that spits out a simple table. Since we do not have any properties I have not overriden the methods for saving and restoring state. Overriding encodeEnd() and decode() and returning null from them.
  2. Implemented LabelComponentTag as a subclass of UIComponentTag. The responsibility of this class is to return the component_family and component_renderer.
  3. Wrote the TLD file defining the spanningTable tag
My custom component is throwing a NullPointerException. This is because the server was not able to locate the projects tld file. When the app reads the JSP pages, it will try to locate and load all referenced tld files. Our JSP pages, declare tags with their corresponding URI's, and web.xml maps the URI's to tld files. The app gets the tld file names from web.xml, and loads the files. When a tag needs to be rendered, the server looks up the tld file to validate the tag, and if valid it gets the UIComponentTag subclass for this tag. This files in turn tells the server the name of the JSF component. This name is mapped to an actual class in faces-config.xml. That's how the server loads the component class (some subclass of UIComponent).

Anyways, so far my problem was an improperly named tld file in web.xml.
Fixed the problem, and got the simple table exercise to run.

This seems to be the order in which various methods of the Tag class, Component class, and Backing Bean are invoked.
  1. The Tag class is instantiated
  2. Properties specified in the JSP page for that tag are set in the Tag class
  3. The runtime tries to get the type of the component by invoking the getComponentType() method of the Tag class
  4. The runtime looks in faces-config.xml (it must be looking elsewhere also because core components are not defined in faces-config.xml) to see if a component has been defined with that type (nexted tag, in the tag). It gets the fully qualified class name of the component
  5. The component is instantiated
  6. The Tag class' setProperties() method is invoked. This method is responsible for setting properties from the Tag class to the component class. Not all properties in the Tag class will have corresponding properties in the component class. Some may in which case, they will be set directly (or after some conversions). Some properties may be set in the attributes Map of the component. These properties are usually those that will not be needed directly by the component but will be used by other classes such as the Renderer. Some properties may be bound to the backing bean. These properties are saved in the component using ValueBindings (The ValueBinding class interprets the JSF-EL and figures out the property of the backing bean we want to bind to).
  7. The component is Rendered by either invoking encodeBegin() or by invoking a custom Renderer. Here we may use properties from the backing bean. We can retrieve them by using the ValueBinding object.
  8. The save of the component is saved after rendering is complete.

Thursday, April 26, 2007

Details of JSF's MVC implementation:

Still reading Rick Hightower's article on JSF.


This image has been referenced from Rick Hightower's article.

The JSP page (essentially the tags) is bound to a server side view_root that maintains the state of the UI components. The view root is a composite just like Swing components. Any changes a user makes in their browser's view get reflected in the state of the view root. The view is also linked to properties (or nested properties) of a backing bean. It is recommended that we do not put business logic in the backing bean, they are meant to mediate between the view and the model. At first I thought, why do we need these backing beans? The properties can be set in the View Root objects, and they can handle the events as well, but I think there is a good reason for them. The View Root components are written by the component provider. We do not have control on them. However our application needs to have event handlers, and maybe transfer objects. These are bound to the view through the backing beans. So the backing beans act as the glue between the view and the model. Is there a cleaner way to do this? Maybe not.

How do the values from the front end actually get set in the backing bean? I think the components in the view root will invoke the setters when they are updated. Then exactly what role does the faces Servlet play?

Learning Java Server Faces

Resources:
  • Marty Hall has a good JSF tutorial here.
  • Rick Hightower has a very good 4 part series on JSF here.

Reading the first part of Rick's tutorial.

JSF provides component tags for every input field available in standard HTML. [Ref]

Well I guess, JSTL also did this.

JSF components are stateful. The statefulness of the components is provided through the JSF framework. JSF uses components to produce HTML responses.
Were JSP tags also stateful? No. Assuming we are using Struts, let's say we change the state of a form, the state change is transmitted to the backend as an HTTP request. This causes some bean properties to be set. The original form can now be displayed again, using the form bean as a a source for the state of the form. This form will reflect the new change as long as form bean is accessible to the JSP tag. So the state is saved in the form bean, and the fact that the form bean is made accessible to the Tag helps us manage the state of the UI.
In JSF, I believe the state of the view is saved in a corresponding server side component [need to check this].

JSF's component set includes an event publishing model
This is a big change from Struts and the earlier frameworks. However, I remember reading somewhere, that JSF apps do not support plain old GET requests (links). Could this be because of the event based approach? [need to check this]

The JSF framework also has:
  • A lightweight IoC container
  • Server side validation
  • Data conversion

JSF and JSP:


JSF uses JSP as the UI rendering technology (not quite, but read along...)

Each JSP page contains JSF components that represent the GUI functionality. You use JSF custom tag libraries inside JSP pages to render the UI components, to register event handlers, to associate components with validators, to associate components with data converters, and more

I am not sure about the rendering part. From what I understand the JSP pages are used because they support tags. JSF tags create a representation of the component on the server. This representation saves the state of the component, and certain server side classes are responsible for rendering the component as well. So the JSP seems to be used simply because it supports tags. That said, it is possible to use other technologies for the UI, such as Facelets and xml namespaces (instead of tags). One implication of this, is that if a JSP page is changed and dropped into the server, the server will not reflect the changes if the server side component representation has already been created. This is because JSP is not used for rendedring, but simply to set up a server side component tree to represent every component coded in the view with JSF tags. Rick does go on to breifly explain this.

JSF and MVC:
The main complaint against Struts is that it can feel more procedural than object-oriented
Hmmm this may be true, but it was to accomodate the (stateless) HTTP protocol. True JSF does seem more OO because it abstracts the web behind a component based model. But it still has to be seen how well the creases are ironed out. It is still premature to say that JSF's component based model is superior (because it is less procedural... use the methodology that is best suited for the job... and it is possible that the procedural methodology might just be better suited to accomodate a stateless protocol... ).

JSF offers a richer MVC environment:

That does seem to be true. User interactions on the UI are transmitted to the backend as events, whereas in Struts they are request parameters. Are events better than request parameters? They surely are more OO. Maybe they are better, but there could be a downside. Many applications need support for link based entry points. For example when someone tries to connect to a LinkedIn member, the application sends the member links to approve the request ot reject the request. This works because we have not abstracted the underlying protocol. Would this work just as well in a JSF application? I do not think so, because a JSF backend needs events, and events cannot be generated when a user clicks on a link from their mail client. I am sure there is a workaround though.

JSF's fine-tuned event model allows your applications to be less tied to HTTP details and simplifies your development effort.
I am not sure. Maybe writing simple CRUD applications will become much simpler, but writing complex applications might become significantly more difficult.

SF also improves somewhat on the traditional Model 2 architecture by making it easier to move presentation and business logic out of your controller
I don't believe either presentation or business logic was in the controller in traditional model 2 apps. Though people did put business logic in the view (JSP pages), and I agree that JSF makes that more difficult (because the view is rendered from a server side component model, so it is difficult to mix html with tags on the view pages in the JSP's).


Unlike a true MVC architecture it is unlikely that the JSF model tier is issuing many events that have to be resolved in more than one viewport;
True. Though if we need this, remoting [link] does give us the capability.

Tuesday, April 24, 2007

Would you like to take a pay-it-forward course?

Those of you who have seen my services section, will have noticed a virtual learning offering. I have been offering 2 courses: Java Programming Best Practices, and Object Oriented Design. Till now the fees for each course was $100 for a 6 - 8 week period. However, I have had the desire to work on the Pay-It-Forward model from a long time.

I first read about the Pay-It-Forward concept on Liegh Blackall's wiki. What it really means is every participant has the option to not pay the course fees if they volunteer to mentor future participants or volunteer in other ways towards development/maintenance of the course. What a wonderful idea. This way we can create a community of mentors and move towards peer-taught, outcome-based courses. (Just as an aside Mark Shuttleworth and others are planning some very interesting things using the concept of peer taught and outcome based courses to help school students gain analytical skills.)

Please send a mail to adaptives[at]gmail[dot]com, if you are interested in taking the course. I may not be able to mentor everyone who signs up immediately, but we will accomodate everyone a batch at a time. Please mention which course you would like to take, along with some background information about yourself, like whether you are a student or a professional developer, the technologies you work with, and your experience in the industry.

If you are planniing to take the "Java programming best practices" course, then you must be already be familiar with Java. If you are taking the "Object oriented design" course, a very basic exposure to OO concepts will help, but is not a prerequisite.

The primary prerequisite I request, is sincereity in learning, and sincerity in sharing your knowledge with future students.

Here is how we will proceed with the course.

When you sign up, I will mail you a document containing recommended reading. A lot of it are posts on this blog, and some from elsewhere on the Internet.  You should read every section, and reflect on it by writing a blog post on your blog. I will follow your blog and converse with you by adding my comments to your posts. If you have any questions/doubts, you must post them on the learning forum, where they will be answered by the community. If you wish, you can also announce your blog on the forum. This way you will get feedback from other participants as well. Periodically, I will mail you assignments, which you can mail back to me for feedback. I also have some mindmaps and other learning artifacts, which I will post on this blog, soon.

To sum it up, learning is grasping new information, increaseing your understanding by reflecting and practicing the concepts, and deepening your understanding by communicating with others. Teaching is also a very important aspect of learning, when you teach something, you retain the information for a longer time, and also increase your own level of understanding. The basic grasping of information will happen by reading the material I mail you. Reflection, and critical thinking will happen on your own blog, resolution of your doubts and queries will happen on the newsgroup, practice will be through the assignments, and to close the loop you will mentor future students, thus helping them as well as yourself.

If you have any comments or suggestions, please feel free to share them as comments on this post. 

 

Discuss this post in the learning forum.



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Monday, April 23, 2007

Polymorphism

Polymorphism is the ability of an object to assume multiple forms. The example below assumes a class heirarchy with Appender as the superclass. For now it is sufficient to know that the Appender class is responsible for appending log statements to a certain destination. This class has three subclasses, ConsoleAppender, FileAppender, and DatabaseAppender, each of which implement the 'append' of the superclass to direct the log statement to the console, file, and database respectively. The audio explains polymorphism with this simple example.






[Time: 3 mins 40 secs]






Watch a simple animation of how Polymorphism works.



Discuss this post in the learning forum.



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net


 


 



Commercial Links


Friday, April 20, 2007

Inheritance

Logging frameworks like Log4J allow us to send logs to a multitude of destinations. The code responsible for logging to a destination is usually encapsulated into seperate classes.






Without inheritance



With inheritance




When to use inheritance:

  • IS-A relationship
    • An Employee is a Person
    • A BumperSale is a Sale
    • A Square is a Shape
  • IS-LIKE-A relationship

But if the relationship between them is HAS-A (eg: Car has an Engine), then we use composition instead of inheritance.


Reflections:


What is the relationship between the following objects?

  • Bathroom - Bathtub
  • Car - Engine
  • Person - Professor
  • Vehicle - Car



Discuss this post in the learning forum.



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

 



Commercial Links


Monday, April 16, 2007

Encapsulation and information hiding

Encapsulation and information hiding are often used interchangeably. But they are actually different. Information hiding is a design principle, whereas encapsulation is a langauge facility. Encapsulation is the process of bundling code and the data it acts on together in one entity. David Parnas describes information hiding as "hiding of critical design decisions", so that the client code does not have to understand the intricacies of the design, and is also oblivious to any changes in design. Encapsulation can happen without information hiding, but will not be effective. Encapsulation facilitates, but does not gaurantee information hiding. Following some simple guidelines will help us create better classes


 



Rules for encapsulation:








Rules for information hiding:




These rules have been taken from this JavaWorld article on encapsulation. It's an excellent article that explains the concepts very well with relevant and well thought of code samples.

Something on the side:

In the above article, the author explains the concept of currying functions. If you find many functions in your source code that are likely candidates for currying, then you may have a load of procedural code in an OO language. Something to be aware of and also a signal that the code warrants refactoring.

Resources:

 


 


Notes: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

 



Commercial Links


Saturday, April 14, 2007

Abstraction

According to Wikipedia - Abstraction is the process of reducing the information content of a concept, typically in order to retain only information which is relevant for a particular purpose. For example, abstracting a premiership football to a ball retains only the information on general ball attributes and behaviour. Similarly, abstracting an emotional state to happiness reduces the amount of information conveyed about the emotional state.



Click on the audio player below to listen to an explanation of what abstraction means in object oriented development.


 










This photograph is attributed to gautamnguitar, and is posted on Flickr with a Creative Commons license.



Discuss this post in the learning forum.



Resources:



 


 



Commercial Links


  • Buy programming books from our Amazon.com powered storefront.


Monday, April 09, 2007

What does object oriented design promise?

In this section we will refresh basic object oriented concepts, to ensure that everyone understands the basics before proceeding. 

Let us start with a brief history of object orientated programming. Object orientation is a step in the evolution of software design



The purpose of object orientation is to create programs that are flexible, maintainable, and robust.



Discuss this post in the learning forum.



Notes: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Wednesday, April 04, 2007

Object oriented design

Simula 67 was the first object oriented language, and as it's name suggests was created in 1967. Since then many object oriented languages have been created, all with the purpose of easing software development and making it easier to write robust, maintainable, and flexible programs.

In the next few posts I will cover the fundamental principles of programming with objects and how to apply those principles while coding in real life situations. Remember, even though object orientation gives us constructs for writing maintainable programs, if we do not use them properly, the resulting code will probably be more unmaintainable than simple structured programs.

These are some of the topics that I will post about.

A quick refresher of object oriented principles

In this section we will once again refresh the basic concepts of abstraction, encapsulation, inheritance, and polymorphism. 

Translating requirements into system design

In this section we will understand how to identify classes and their relationships from a requirement specification.

Outcome of good design

This section explains good design and what we hope to achieve with well designed software.

Design principles

In this section we will discuss software design principles and best practices such "keep it simple", "do not repeat yourself", "loose coupling", "high cohesion", etc. We will discuss the principles as well as their practical implications. As of now this section covers some basic principles. Other principles like the ''open closed principle', 'Liskov substitution principle', etc, will be added in the next version of this course.

 

As always I would like to reiterate the importance of reflection and participation in the learning process. As you go ahead, spend a little time reflecting over the concepts, and also participate by asking questions, answering them, and posting your perspectives on the concepts.  I hope you find information useful. Your suggestions are very welcome, please let us know the things we should preserve, and the things we should improve.

 



Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

Monday, April 02, 2007

How to be a great programmer

Recently, someone on the JavaPosse newsgroup asked "how many hours do Java programmers sleep?". Relevant question isn't it? With so many langauge enhancements, API's, frameworks, specifications, and other stuff to learn, one either has to stop learning or stop sleeping. Well maybe not :-)... both can coexist, but what is needed is a great passion for programming.

Heinz Kabutz, author of the famous Java Specialists newsletter shared some very interesting observations on how to be an excellent programmer in his 100th newsletter. I recommend that everyone who aspires to excell in programming should read it. Even though he speakes specifically about Java, the concept holds true not only for other languages, but for other professions as well.

Discuss this post in the learning forum