JSF with Ajax, Phase Listener vs Servlet Comparison

When I first heard about Ajax, I thought the asynchronous call to the server can be handled by a servlet in a jsf application.At first sight the servlet idea was the only one that came up to my mind and I saw several examples that uses a servlet to embed ajax in jsf. After a while, I’ve observed another method to use AJAX with JSF; “phaselistener”. I’ve decided to write the same application with these techniques seperately in order to figure out the possible pros and cons of both. The example is simple, redirecting the request to response, the user clicks a button and an ajax request is sent to the server side.The response is sent back to the client as a string defining the technique being used and the string message is displayed in a simple textfield.

Here is the important part of the jsf page; A textfield to display the response and a button to send the request. The sndReq javascript function takes the technique name as an argument like ‘PhaseListener’ or ‘Servlet’;

        <inputText id=”text1″></h:inputText>
        <BUTTON onclick=”sndReq(‘Servlet or PhaseListener here’)”>Submit</BUTTON>

And here are the javascript functions to create the request and handle the response, the sending of the request is given seperately in the description of the techniques.

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == “Microsoft Internet Explorer”){
        ro = new ActiveXObject(“Microsoft.XMLHTTP”);
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        document.getElementById(‘form1:text1′).value = response;
    }
}
       

PhaseListener

Following is the javascript function to send the request to the server side.

function sndReq(requestString) {
    http.open(‘get’, ‘PROJECTNAME/faces/technique-comparison?technique=’+requestString);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

And the PhaseListener to handle the Ajax request.

public class AjaxListener implements PhaseListener {

    private static final String AJAX_VIEW_ID = “technique-comparison”;

    public void afterPhase(PhaseEvent event) {
        String rootId = event.getFacesContext().getViewRoot().getViewId();
        if (rootId.indexOf(AJAX_VIEW_ID) != -1)
            handleAjaxRequest(event);
    }

    private void handleAjaxRequest(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
        String name = request.getParameter(“technique”);
        try {
        response.getWriter().write(name);
        context.responseComplete();
        }catch(Exception exception) {
            exception.printStackTrace();
        }
    }

    public void beforePhase(PhaseEvent arg0) {
       
    }

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}

The idea is exciting, when the request reaches the server, the phase listener takes the scene and after the restore view phase, it checks whether is an Ajax request or not. If it is, it creates a response and forces the life cycle to jump to the render response phase.

Servlet

Now the function is changed and the url target is a servlet;

function sndReq(requestString) {
    http.open(‘get’, ‘/PROJECTNAME/servlet/ResponseServlet?technique=’+requestString);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

And the handling servlet;

public class ResponseServlet extends HttpServlet {   

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String technique = request.getParameter(“technique”);
         response.getWriter().write(technique);
    }
}

As you see, servlet code is much shorter than the PhaseListener and looks simpler however we should consider the simplicity of the example. Servlet does not need to understand whether it is an ajax request or not because it is the servlet’s only job, however the phase listener must catch an ajax request. On the other hand the phase listener is a native solution but the servlet is in the external context. This gives the advantage to accss the stuff in context of faces easier. Also if you are writing a custom component that uses external sources like javascript files or css, phaselisteners can serve these for you from a single jar file which also contains your code.
Since I am a phaselistener fan I would suggest to use the phaselistener method whenever you try to add some ajax magic to your jsf application.

Posted in Java. 27 Comments »

Duplicate component id found in view

I was trying to add an id attribute to a custom JSF component I’ve created, it has also several other custom attributes. I’ve added an attribute id to the tld file, and defined the id attribute in the tag class like the way I do for the custom attributes. When I ran the application to test the component, the page loaded ok but when I submit it, it gave the duplicate component id in view exception.

When trying to figure out the cause of the problem, I realized that I made a mistake in my tag class because there is no need to define an id attribute, creating getters-setters and putting the variable in the attributes map. setProperties method already set the id for the component, manually putting the id attribute to the map, will threw the duplicate component id found in view exception.

When I removed everything about id in the tag class everything worked ok. Long story short, in order to add an id attribute to your custom component, the only thing you need to do is to add the id attribute tags to the tld file. I think this method will also work for the other common attributes like rendered because UIComponentTag class takes care of these attributes. 

Posted in Java. Comments Off

JSF component's value, local value and submitted value

I’ve observed that some people who are trying to create custom components, seem to be confused with the three different value types of an uiinput component. These are, “value”, “local value” and “submitted value”

* Actually the differences are simple and come from the life cycle, when the user submits a form all the values are passed
to the server as strings. In the apply request values phase, these string values must be converted and validated before the
model update phase can begin.

* At first the value is retrieved from the request and during decoding the “submitted value” is set by the component. This submitted value has nothing to the with the model and is all about the component. This means the request value is first stored in the component.

* Later the conversion stage begins, if there are any converter is defined, this converter takes this submitted value and applies the getAsObject method on this value. Now the submitted value of the component is converted and set as the “local value”.

* Finally if any, validators come up and validate the local value. Rest is trivial from now on.  if the local value is valid, it is set to the binded model variable. This happens in update model phase.

* Component’s value refers to the “binded model value” actually, so whenever you call getValue, it will bring it to you. Local value and submitted value are the ones used to change it. You must use getValue() during encoding because submitted value and local value are set to null already.

That’s all about the three “value” types of a jsf component, as seen above it is all about the lifecycle of JSF :)

Posted in Java. 3 Comments »

How to Write Your Own Custom JSF Variable and Property Resolver

Value binding is a powerful feature of JSF that implicitly creates the data and makes the model ready for the developers to process. Value binding expressions are simple strings like #{somebean.somevariable}, jsf processes this expression and creates the value to be used in later phases of the lifecycle. The facilities that extracts the value from these value binding expressions are resolvers called Variable Resolver and  the Property Resolver. Variable Resolver finds what the leftmost segment of the expression corresponds to. It looks at the several scopes of the application like application, session etc. When it finds a match, property resolver takes the step and extracts the remaining expression.When the variable resolver could not find a match, faces will use another variable resolver if defined in the faces-config.xml. For example Spring’s delegating variable resolver.
 
These resolvers are linked together and responsibility is passed to another.(Chain of Responsibility Design Pattern) If nobody could find a match than property not found exception will be thrown. Most JSF developers could remember the message that begins with Error getting property…:) What I like about resolvers that you can extend them, actually this is what I like about JSF generally. There are lots of extension points like resolvers, navigation and view handlers, components etc.

In our project we have lots of readonly lookup data that we bind to comboboxes or listboxes. We are using service methods that returns all the relative data from the db. The idea is to make a service call that actually calls Hibernate.loadAll(Class) method then we get the data in the lookup table as a list and bind it to a combobox or whatever. Day by day, many new entities come up and as you may guess for each one we need a new service method returning all of the corresponding the db. At this point I’ve decided to create a resolver that will work as a lookup resolver doing what the service method does without calling it:) For example, we have an entity called Job, and there is a lookup table T_JOB full of readonly Job records like engineer, doctor, nurse, other etc. Using the resolver we could retrieve all the Job objects like this and bind them to a combo by this;

<h:selectOneMenu id=”menu1″>
 <f:selectItems value=”#{lookup.some.package.domain.job.jobname.this.all}” >
</h:selectOneMenu>

The keywords I’ve used are lookup and all. lookup takes the attention of the variable resolver I’ve written and it answers yes when faces asks the resolver whether it knows what lookup means or not. all is another word that enables me to stop parsing the expression. Between these two keywords, class name and key-value pair are located. There are three classes that I’ve used;

You can download the sources above.

Finally declaring the custom resolvers in the faces-config is needed in order to put them to the responsibility chain:)
 <application>
  <variable-resolver>resolver.LookupVarResolver</variable-resolver>
  <property-resolver>resolver.LookupPropResolver</property-resolver>
 </application>

The flow is as follows;
1) When faces tries to resolve the expression it asks all the resolvers defined, the default resolvers will not resolve the expression since it begins with a lookup word, then faces will ask the lookupvarresolver and the resolving process begins.
2) The lookup property resolver will put each token after the lookup word to the LookupWrapper’s tokens list until it sees the token named “all”.When it sees the “all” word, the property resolver will return the lookupwrappers’s getAll method in the getValue method of its own.
3) LookupWrappers getAll method creates the object list by parsing the the class name and key-value pair. The wrapper has a Crud Service that we use in our project injected. Using the class name, wrapper reads all the data in the db and returs as a list.
4) For all the objects in the list, a select item is created. SelectItem is an entity of Faces. Each select item has a key and a value. The key and values are also in the expression thus using java reflection the getter of the key is called. Finally all of the selectitems are put in an array and returned.

Writing a custom variable and a property resolver will be tricky and in my view one should have a look at the source code of JSF and observe what the default variable and property resolver of JSF does actually. 

Posted in Java. 1 Comment »

Integrating JSF and Spring

We’re currently using JSF and Spring together and I could say that integration of these two frameworks is not so hard thanks to the Springs facilities. I am using two different ways when I need to access the beans managed by spring. One is to use the delegating resolver and the other is to the FacesContextUtils

Update: See this post about a better alternative, using Spring to manage JSF Beans.

1) Delegating Resolver
For example you have a facade called FacadeService and it has a dependency to another service called “SomeService” which implements “ISomeService”. Also “SomeService” is managed by spring. The first is to define the FacadeService as;

package yourpackagename;

public class FacadeService {

private ISomeService someService;

public ISomeService getSomeService() {
return someService;
}

public void setSomeService(ISomeService someService) {
this.someService = someService;
}

}

The next step is to define this FacadeService as a managed bean in the faces-config.xml by; The other bean definition is a backing bean of your jsf page.
<managed-bean>
<managed-bean-name
>facadeService</managed-bean-name>
<managed-bean-class>
yourpackagename.FacadeService
</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<property-name>someService</property-name>
<property-class>
packagename.ISomeService
</property-class>
<value>#{someService}</value>
</managed-property>
</managed-bean>

<managed-bean>
<managed-bean-name
>backingBeanName</managed-bean-name>
<managed-bean-class>
yourpackagename.backingBeanClass
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>facadeService</property-name>
<property-class>
packagename.FacadeService
</property-class>
<value>#{facadeService}</value>
</managed-property>
</managed-bean>

* Also the delegating resolver must be defined in faces-config.xml between the application tag as following;

<application>
<
variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>;
<
/application>

* Next step is putting the listener of spring goes into the web.xml and telling the location of spring’s xml

<context-param>
<param-name>contextConfigLocation </param-name>
<param-value>/WEB-INF/applicationContext.xml </param-value>
</context-param>

The place of applicationContext.xml is optional, you should also put it under classes and refer it like classpath:/applicationContext.xml.

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

* Here is the spring’s xml to manage the someService bean

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE beans PUBLIC
“-//SPRING//DTD BEAN//EN”
“http://www.springframework.org/dtd/spring-beans.dtd”>

<beans default-autowire=”no” default-lazy-init=”false”
default-dependency-check=”none”>
<bean id=”someService” class=”yourpackagename.SomeService”></bean>
</beans>

* So thats all metadata you need to configure, the final step is to add the FacadeService to the code behind of your jsf page by simply adding this; For example you have a backing bean called YourBackingBean.java, Faces inject facadeService to this bean since we have configured it. Also the spring bean (some service) is injected via the delegation variable resolver when creating the facadeService.

public class YourBackingBean{

protected FacadeService facadeService;

public FacadeService getFacadeService() {


return facadeService;
}

public void setFacadeService(FacadeService facadeService) {
this.facadeService = facadeService;

}

}

There is an important note here, using the #{facadeService} you can get the value of the FacadeService managed by Faces, the default variable resolver of JSF will bring it for you. Also you can get the SomeService object by writing the appropriate accessor methods and replacing the value binding expression with #{someService}. The default variable resolver will not find “someService” and the responsibility will pass to the DelegatingVariableResolver of Spring which will return the someService name. Long story short, here comes the fun part, accessing the spring bean from code behind, for example at anywhere in your jsf code behind you can reach the spring bean by;

getFacadeService().getSomeService().someMethod(); //If everything is ok, hopefully no npe

These steps allows the JSF-Spring integration, inversion of control is applied both by spring and faces, facadeservice is managed by Faces and these are wired using the delegating variable resolver of spring. Important thing is spring bean is not injected by spring, the wiring is done by faces. Spring’s role is a container in this case.

2) Using the FacesContextUtils
I always see this one as the alternative and I dont use it unless I have to. For example, I have created a custom jsf component and a custom variable resolver. Both of these needed to use spring beans. So thats why I’ve reached spring directly. FacesContextUtils is an utility class that is located in spring framework.

ISomeService someService = (ISomeService) FacesContextUtils
.getWebApplicationContext(FacesContext.getCurrentInstance())
.getBean(“someService”);
someService.someMethod();

To sum up, I could say using these two frameworks is fun and spring’s mechanisms make it very easy.You can either use the delegating resolver or FacesContextUtils to use the beans managed by Spring and Faces together.

Posted in Java. 21 Comments »

Head First Design Patterns Book

Studying design patterns was never an interesting thing for me although I’ve always wanted to improve my skills on patterns. I’ve tried to read several books and articles on patterns, frankly speaking that was nothing more than pain. Boring uml diagrams, lots of text and ordinary examples. However I came across to the book ‘Head First Design Patterns’ and suddenly I figured out, this book is the one I was looking for a long time.

The book is like a comic book, it contains puzzles, lots of  pictures, interesting examples and more. For example I have never seen a decorator and an adapter talking to each other before :) Reading this book is so much fun even it is talking about design patterns. I hope more Head First books will come up on different topics that I found boring.

Posted in General. 1 Comment »

Dynamically adding components to a custom composite JSF component

When writing a custom JSF component, you might want to include other components in yours. JSF provides different ways to achieve this, the hard way is to encode-decode the other component you want to include. The easy way is to create and add the component programatically you want to include, to your composite component. For example you want to add a input text component dynamically.

private void encodeInputText(FacesContext context) {
     
HtmlInputText inputText = new HtmlInputText();
      inputText.setParent(this);
      inputText.setId(this.getId() + “:_text1″);
      inputText.encodeBegin(context);
      inputText.encodeEnd(context);

}

This code will render an input text to the page, in this example you can also manipulate several properties of the inputText before calling encode, you can set converters, validators, style classes, and other component specific attributes to inputText here without coding html. Calling encode will give this job to the renderer of the inputText.

This was a simple example, if the component being added dynamically renders it’s children you should also check for the getRendersChildren() of the component and call encodeChildren if necessary. I’ve tried the code above many times and did not have any problem, however there seems to be a better alternative to this, an opposite way actually, using

getChildren().add(the_component_to_be_added);

Updated: After adding the child component dynamically, like the first way, the encoding methods must be called in order to render the children.