Unique portlet ID
Sometimes one need to retreive a unique ID for a particular portlet instance. In my case I needed it to implement configuration storage for each portlet instance independent on the user (see another post for comments on this topic).
The catch is, there is no such thing in the portlet specification. The closest you can find is the getNamespace(). The spec says “to ensure they are unique in the context of the portal page”. However, not neccessarily unique through the whole portal. At least, you don’t know until you have investigated it, for example asking the vendor or reading the code. Let’s say the mthod returns a unique ID. Now, here is the catch; you need that ID in processAction() as well!
In most cases, a portlet goes through render mode (doView) and then after the user clicks a button, which invokes processAction(). That means, in render() you can grab the ID and for example inject it into the session.
public void render(RenderRequest req, RenderResponse res) throws ... {
String ID = res.getNamespace();
//... do something with ID ...
req.getPortletSession().setAttribute("portlet.id", ID);
super.render(req, res);
}
And then pull it out again in processAction()
public void processAction(ActionRequest req, ActionResponse res) throws ... {
String ID = req.getPortletSession().getAttribute("portlet.id");
//. . .
}
So far so good, as they say. Now, consider a lazy user, which stares at the portlet page until the session times out and thenafter clicks that darn button - pow! NullPointerException.
The only solution is to figure out how the portal handles portlet IDs internally. For example, the URL might be annotated with a portlet ID after an action request. For the portal I have been working with (SiteVision) I found out that its ID can be found in the session using the following code snippet.
public String getID() {
String id = (String) getSessAttr("portlet.id");
if (id == null) {
String portletID = "" + getReqAttr("sitevision.portlet");
id = "svid" + portletID.replace('.', '_');
setSessAttr("portlet.id", id);
}
return id;
}
I have to emphasize this again: this is not portal independet code.
Comments
Leave a Reply
