PortletPreference As Database

Sometime, we’d facing some simple job, such as storing the few portlet setting. If we using database approach, it will like having too much job. So, the following simple example i’ll demonstrate how can we develop something without fully rely on database, such as we can store some simple configuration into portlet itself.

Use case

For instance, your portlet is a feedback form, once the feedback is done. You’d like the form will automatic show the thank you page. And this thank you page will never maintain by you. The admin or liferay content user will create difference version of language page for each feedback form.

First, you will need a form object to hold the URL value

  1. public class WebForm implements Serializable {
  2.  
  3.         private static final long serialVersionUID = 1L;
  4.         private String url;
  5.        
  6.         public WebForm () {}
  7.  
  8.         public String getUrl() {
  9.                 return url;
  10.         }
  11.  
  12.         public void setUrl(String url) {
  13.                 this.url= url;
  14.         }
  15. }
  16.  

Getting data into PortletPreference

Next, In your controller default rendering method, get the portletpreference object form request object. The data store in portletpreference will be key and value. You can specified the default value from preference.getValue(“key”,”value”); For instance, the below example will get empty string if url key has no value.

  1.  
  2. @RenderMapping
  3. public String doView(@ModelAttribute("webForm") WebForm form, ModelMap model
  4.                              RenderRequest request, RenderResponse response)
  5. {              
  6.         PortletPreferences preferences = request.getPreferences();
  7.         String url = preferences.getValue("url","");                                           
  8.         form.setUrl(url);
  9.  
  10.         model.put("form", form);               
  11.         return "form_setting_page";
  12. }
  13.  

Storing data into PortletPreference

  1.  
  2. @ActionMapping(params = "action=updateSetting")
  3. public void doUpdate(@ModelAttribute("webForm") WebForm form, BindingResult result, ActionRequest request, ActionResponse response)
  4.  
  5. throws ReadOnlyException, ValidatorException, IOException
  6.  {
  7.         validator.validate(form, result);
  8.         if(!result.hasErrors()){
  9.                PortletPreferences preferences = request.getPreferences();
  10.                preferences.setValue("url", form.getUrl().trim());
  11.                preferences.store();
  12.         }else{
  13.                response.setRenderParameter("action", "");
  14.         }
  15. }       
  16.  

Done !

You can leave a response, or trackback from your own site.

Leave a Reply

Security Code: