Wednesday, September 17, 2008

jsf: hidecontent tag - same as aspnet's placeholder

While working on a java project, I needed to hide certain contents and functionalities from a subset of users. I couldn't find a built-in tag to accomplish this functionality.

Here is a sample page that uses this tag to show Access Denied message when a non-privileged user try to access a page


For example consider a simple application with 2 roles.
Editor role can add/remove items (say products). Admin role approves new/edited items, publish for sale on website and can view all reviews of the products.
Assume that we have 3 sections in our web page, one for Product Details (Editor Role has full privilege), Admin (Admin Role has full privilege), Review ratings(Admin Role has full privilege).
This placeholder component is a perfect fit for such a scenario. This is a very simple component which uses a div tag's visibility attribute to hide contents.

Here is how to make such a component. See jsf documentation on a more detailed explanation of each of these items

1. Create a Render Class. I am using 2 properties to check the privilege (just to show you that you can have as many properties as you like to do business logic checks)


2. Create the Tag Class. Nothing fancy here, couple of getter and setters


3. Create Tag Descriptor. Think tld as an explanation of the properties of our tag.


4. Add to faces-config.xml. Add to faces-config to consume in our web pages


5. Add to Page. Add the taglib prefix and set the variables.


download code and rename to .zip

[Child controls' required attribute need to be changed to false if you are enabling a form post for non-privileged users]

That's it!

-Paul