Monday, February 20, 2012

Portlet Preference

Portlet Preference is a feature provided by portal in order to provide persistent data storage.Persistent data storage means that data once set in portlet preference will remain available even after server re-starts.

Details about the interface can be found at
http://www.bluesunrise.com/portlet-api/javax/portlet/PortletPreferences.html#getMap%28%29

Preference can be of 2 types

1) Read-only : they cannot be changed at runtime  are are defined in deployment descriptor or portlet.xml

2) Dynamic Preference : they can be set in process Action phase of life cycle of portlet and can be read in Render phase.

Following is the example to set and retrieve preference dynamically

public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
        if( request.getParameter(FORM_SUBMIT) != null ) {
            // Set form text in the session bean
            PreferencePortletSessionBean sessionBean = getSessionBean(request);
            if( sessionBean != null )
                sessionBean.setFormText(request.getParameter(FORM_TEXT));
        }
       
        PortletPreferences preferences = request.getPreferences();
        preferences.setValue("myVal","mohit");
        preferences.store();
    }


public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        // Set the MIME type for the render response
        response.setContentType(request.getResponseContentType());

        // Check if portlet session exists
        PreferencePortletSessionBean sessionBean = getSessionBean(request);
        if( sessionBean==null ) {
            response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
            return;
        }
       
        PortletPreferences pref = request.getPreferences();
        pref.getValue("myVal", "no data found");

        // Invoke the JSP to render
        PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
        rd.include(request,response);
    }



1 comment:

  1. it doesn't work
    the value we are specifying in the do view method will return the same value ,the value set in the processAction is doesnt appear in the doview

    i mean it returns the same value as "no data found"

    PortletPreferences pref = request.getPreferences();
    pref.getValue("myVal", "no data found");

    ReplyDelete