Pages

Tuesday, February 17, 2015

JSF 2.x Tip of the Day: Implementing a ViewMapListener

A map of the lands where the Trobadors flourished. 
"France 1154-en" by Reigen - Own work
Licensed under CC BY-SA 4.0 via Wikimedia Commons.

Introduction

There are a number of SystemEvents supported by JSF 2.x. A question that comes up frequently is how to implement them. In a number of cases on stackoverflow, it is implemented using a PhaseListener. I was looking for a way to cleanup the view map, or just get values from it before it was destroyed. I decided that the simplest way to do so was to implement a ViewMapListener. I also noticed that there were very few posts on how to implement it using the faces-config.xml so I decided to use that approach since it was instructive and more clear to me.

Implementation

The basic implementation requires that you add our listener implementation to the faces-config.xml. The example I have here is designed to get called on a PreDestroyViewMapEvent which is called on a normal navigation. We can force it though by adding a @PreDestroy annotation to a method to invoke before being destroyed. Inside the method we would need to get the UIViewroot view map, and call clear(). This would cause our listener to be invoked too. It would be a good cleanup mechanism for cleaning up resources on session expiration too, but at the moment this does not work on JSF 2.1. The @PreDestroy is not called on session timeout on JSF 2.1. This is expected to be an enhancement in JSF 2.2+.

The code for the project can be downloaded from Bitbuket here: viewmaplistener-example

Conclusion

The example above is just one mechanism of using a SystemEvent listener. You may decide to read values from the map, and add them to the session, or manipulate it in some other way before the data is destroyed.

No comments:

Post a Comment