Wednesday, April 23, 2014

JSR 168&286 Standards Portlet Development

Introduction:

JSR 168&286 are the portlet standards defined by SUN people.


Download Generic Portlet Examples


According to JSR 168&286 specifications

Portlet is small fragment of dynamic content.

Page is aggregation of dynamic fragments i.e. portal page consist of one or more portlets.

Portal consists of one or more portal pages.

According to the JSR 168&286 Specifications portlet should need following artifacts.
  • Portlet should have configuration file i.e. portlet.xml
  • Portlet should need portlet class that should implement javax.portlet interface.
  • It should contain deployment configuration file

Portlet configuration (portlet.xml) file is core artifact for portlet and it will contain set of portlet tags which follows the portlet 2.0 dtd.

Portlet class is controller class which will handle all actions and render the views.

Deployment configuration file (web.xml) file and it is common for all web applications and portlet is also a type of web application with specific characteristics.

JSR Portlet implementation a basic portlet called Generic Portlet which is a part of sun portlet implementation. Generic Portlet can deploy into any portal which follows the JSR specification.

Sun implemented javax.portlet package which consist of set of classes and interfaces and we will use these implementation to develop Generic Portlet.

Generic Portlet:

Generic Portlet is basic portlet and its implements javax.portlet.Portlet interface.


Each Portlet have its own lifecycle and it has different phases i.e. render phase, action phase, event phase and destroy phase.

The following are the methods in javax.portlet.Portlet Interfaces to represent portlet life cycle

init(--) :  it will handle the portlet initialization phase in portlet lifecycle

doView(--) : it will handle portlet render phase.

processAction(--): it will handle portlet action phase.

processEevent(--): it will handle event generation phase

serveResource(--): it will handle the serving the recourse phase.

destroy(): it will handle the portlet destroy phase.

Note:

All these method was already implemented by Generic Portlet

JSR specification has introduced portlet URLs so that it will call portlet lifecycle methods.
Generally in web application when we call servlet we will use URL mapping in web.xml file, similarly in the portlet we have portlet URLs it will invoke portlet class and execute appropriate lifecycle methods.

We have following Portlet URLs

Portlet Action URL:

To call portlet process Action method we will use Portlet Action URL

Portlet Render URL:

Portlet render URL will call doView(---) method and it will render view content in browser.

Portlet Serve Resource URL:

It will call portlet Sever Resource method and it will serve images, files.

Note:

Portlet URL will be recognized the portlet class by the configuration we have done in portlet.xml file using <portlet-class/> tag.

Portlet Lifecycle Phases will be represent portlet lifecycle with numbers
  • 0:  Portlet render Phase when we use portlet render URL then in the URL we can see portlet lifecycle 0 and it will call doView(--) method
  • 1: it represent portlet action phase when we create URL then in the URL we can see portlet lifecycle 1 and it will call processAction(--)
  • 2: it represent the portlet serve resource phase and we will use resource URL and its lifecycle will be 2 and it will call serveResource(--)

A simple Generic Portlet Example:

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
            <display-name>SampleGeneric-portlet</display-name>        
            <jsp-config>
                        <taglib>
                                    <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
                                    <taglib-location>
                                                /WEB-INF/tld/liferay-portlet.tld
                                    </taglib-location>
                        </taglib>
            </jsp-config>           
</web-app>


portlet.xml


<?xml version="1.0"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd
http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" version="2.0">
            <portlet>
                        <portlet-name>helloworld</portlet-name>
                        <display-name>Hello World</display-name>
                        <portlet-class>com.meera.generic.HelloWorld</portlet-class>
                        <expiration-cache>0</expiration-cache>
                        <supports>
                                    <mime-type>text/html</mime-type>
                                    <portlet-mode>view</portlet-mode>
                        </supports>
                        <portlet-info>
                                    <title>Hello World</title>
                                    <short-title>Hello World</short-title>
                                    <keywords></keywords>
                        </portlet-info>
            </portlet>
</portlet-app>


Portlet class


public class HelloWorld extends GenericPortlet {

   
    public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {
       
        renderResponse.setContentType("text/html");
        PrintWriter writer = renderResponse.getWriter();
        writer.println("<p >Hello Portal World!</p>");
    }

}


Important Points:
  • In the web.xml we will use simple configuration which specify the application display name and some important tag libraries which is required for the portlet development.
  • In the portlet.xml file we will configure all information about portlet and the important one is portlet class. Portlet class acts like controller so that it will handle all portlet lifecycle it was extended the Generic Portlet.
  • In the portlet class we overridden the doView(--) method and we will write some html content that should be display in client or browser.

Portlet deployment:

We will package this portlet as war file and we need deploy into the servers which contains the portlet container. We already know we need portlet container to run portlet.

Based on portal vendors we will have different deployment mechanism and procedure like we can use ANT tool, Maven Tool or some other vendor specific mechanisms.

Calling Portlet:

We will use portlet URL in the browser to call portlet. We already know portlet URL will represents portlet lifecycle.

Apart from portlet lifecycle portlet URL consist of portlet id, portlet window state, portlet mode and portlet position in the page.


Portlet Window States:
normal, maximized, minimized

Portlet Modes:
edit, view and help


The following is simple URL it will call portlet


http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&
p_p_state=noraml &p_p_mode=view


Note:

We will use render phase URL to see the content in the browser. If we want perform any actions then we will use Action URL and finally action phase turn into render phase to view something in browser.

Render Phase or lifecycle 0 is to view some content in the browse i.e. we have written out put in the doView(--) method.

Action Phase or Lifecycle 1 is call the processAction(--)  and then doView(--)
Serve Resource Phase or Lifecycle 2 is call only serveResource(--) method and serve the  images or files.

The following is sample Portlet URL to view content in browser


http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&p_p_state=noraml &p_p_mode=view


Render URL with Window State Normal


http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&
p_p_state=noraml &p_p_mode=view




Render URL with Window State minimized


http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&
p_p_state=minimized &p_p_mode=view





Render URL with Window State maximized


http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&
p_p_state=maximized&p_p_mode=view



Note:

In the URL we will use host name and portal page name after that we will represent all portlet related parameters and its values as URL query string.

About Portlet URLs

Portlet URL will invoke portlet class and it will execute appropriate portlet lifecycle methods.
We will represent all requires parameters and it values as query string so that it will use at the time of portlet lifecycle phases

We already know portlet URL consist of portlet Id, portlet Mode, portlet state

The following is sample URL


http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&
p_p_state=minimized &p_p_mode=view


p_p_id:

It us portlet id and container can recognized the portlet by its id so that it can invoke or insatiate.

How portlet Id generated?


PortletName_WAR_DisplayName


Portlet Name:

 Id available in portlet.xml file and its value of <portlet-name/>

Example:

<portlet-name>helloworld</portlet-name>

_WAR_ is constant String

Display Name:

This is available in web.xml file of portlet and it is value of <display-name/>

 Example:

<display-name>SampleGeneric-portlet</display-name>


Finally portlet Id or p_p_id is

 helloworld_WAR_SampleGenericportlet


p_p_lifecycle:

This represents the portlet lifecycle phase

0: render phase
1: action phase
2: server resource phase.

p_p_state:

It represents the portlet window state and will be one of normal, maximized and minimized

p_p_mode:

It represent portlet mode and it will be one of view, edit and help

Generally in the portlet development we will use portlet tag library to create URL by simply using tags.

Using portlet Tag library:

We need to configure portlet tag library information in portlet web.xml file as follows


<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
<taglib-location>/WEB-INF/tld/liferay-portlet.tld/taglib-location>
</taglib>
</jsp-config> 
          

Note:

Make sure portlet tld should available in specified location and tag implementation jar file should be available in portlet class path location.

Using Tag Library in JSP Page:

We need use following tag to make all tags available to jsp page


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>


Create Portlet URL using Tag Library:

Portlet Action URL:


<portlet:actionURL var="portletActionURL" windowState="normal">
</portlet:actionURL>

http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=1&
p_p_state=normal&p_p_mode=view


Portlet Render URL:


<portlet:renderURL  var="portletRenderUR" windowState="maximized">
</portlet:renderURL>

Actual URL:

http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=0&
p_p_state=maximized&p_p_mode=view


Portlet Resource URL


<portlet:resourceURL var="portletRresourceURL">
</portlet:resourceURL>

Note:

Resource URL does not have window sate attribute is always use exclusive window state and its default one.


Note:

When we create Portlet URL using tag it will use current host name, current page name and current portlet name id where we created URL in the URL creation.We can also create URL other portlet form current portlet.

The following is more about Portlet URLs


Using Custom Parameters in Portlet URL

We will use <portlet:param/> is tag to pass additional parameters in portlet URL as query string parameter.


<portlet:actionURL var="portletActionURL" windowState="normal">
<portlet:param name="name" value="meeraprince"/>
</portlet:actionURL>

Actual URL:

http://localhost:8080/web/guest/test?p_p_id=helloworld_WAR_SampleGenericportlet&p_p_lifecycle=1&
p_p_state=normal&p_p_mode=view
&_helloworld_WAR_SampleGenericportlet_name=meeraprince

Note:

In the above URL we are passing name parameter and its value as query string and here each parameter name will be appended with portlet id or p_p_id


Portlet Name Space:

Portlet Name Space represents portlet Id or p_p_id and we will use portlet name space or portlet Id or p_p_id for each parameter which we passed through portlet URL as query string. So that portlet container will recognize that parameter belongs to specific portlet.

To avoid name collagens portlet have used portlet name space or portlet id for each parameters.
Generally in page we have multiple portlets and some time we may use same names in multiple portlets if we use same name in multiple portlet in same page it may get name conflicts.

To avoid name collagens or name conflicts will use portlet name space or portlet id for each parameter or some tags id values.

We will use <portlet-namespace/> tag to represent portlet id


<portlet-namspace/>  = = _PortletName_WAR_DisplayName_

Example:

_helloworld_WAR_SampleGenericportlet_



Example Usage:


<input name="<portlet:namespace/>employeeName" id="<portlet:namespace/>employeeName"/>


<portlet:defineObjects />:

Portlet define Object tag will provide portlet related implicit objects to the jsp page.

Example:

rednerRequest, renderResponse , request and response.


Using JSP for Views in Generic Portlet

Before example we simply view the html content in browser. We have overridden doView(--) method and we have used print Writer to write out put in browser. Now we will use jsp page for view the content.

Example:


public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {
       
        renderResponse.setContentType("text/html");
        PrintWriter writer = renderResponse.getWriter();
        writer.println("<p >Hello Portal World!</p>");
    }


Render JSP page as Default view in Generic Portlet

Assume as soon as we drag and drop the portlet in page we need render one jsp page to show content in browser.

We will use some init parameter in portlet.xml file there we have specifies the jsp page path then we will use that jsp page in portlet class doView(--) method to render content.

Example:

web.xml file


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
            <display-name>SampleGeneric-portlet</display-name>        
            <jsp-config>
                        <taglib>
                                    <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
                                    <taglib-location>
                                                /WEB-INF/tld/liferay-portlet.tld
                                    </taglib-location>
                        </taglib>
            </jsp-config>           
</web-app>


portlet.xml file


<?xml version="1.0"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd
http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" version="2.0">
       <portlet>
              <portlet-name>helloworld</portlet-name>
              <display-name>Hello World</display-name>
              <portlet-class>com.meera.generic.HelloWorld</portlet-class>
              <init-param>
                     <name>view-template</name>
                     <value>/html/helloworld/view.jsp</value>
              </init-param>
              <expiration-cache>0</expiration-cache>
              <supports>
                     <mime-type>text/html</mime-type>
                     <portlet-mode>view</portlet-mode>
              </supports>
              <portlet-info>
                     <title>Hello World</title>
                     <short-title>Hello World</short-title>
                     <keywords></keywords>
              </portlet-info>
       </portlet>
</portlet-app>


Portlet class


public class HelloWorld extends GenericPortlet {

    public void init() {
        viewJSP = getInitParameter("view-template");
    }
   
    public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {
       
        include(viewJSP, renderRequest, renderResponse);
      
    }

    protected void include(
            String path, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws IOException, PortletException {

        PortletRequestDispatcher portletRequestDispatcher =
            getPortletContext().getRequestDispatcher(path);

        if (portletRequestDispatcher == null) {
            _log.error(path + " is not a valid include");
        }
        else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }

    protected String viewJSP;

}


JSP Page (view.jsp)


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<h1>Welcome to Hello World Generic Portlet</h1>


Important Points:
  • In the portlet.xml class we need to specify the jsp page path as init parameter.
  • We need to override the Generic Portlet init () method in portlet class and we need get the jsp path and assign to global variable i.e. viewJSP
  • As we already know we will use doView(--) method to view content and we will use same method but here we will call include(--) method  to render jsp page.
  • We need override Generic portlet include (--) method there we will use portlet request dispatcher to render jsp page.

Portlet Directory Structure

Portlet Application Root directory


In side WEB-INF Directory


JSP page navigations

In previous example we have seen to render jsp page when portlet is drag and drop in the page and that is called default view page. Now will navigating from one default view page to another jsp page.

In this example portlet.xml and web.xml configuration is same as previous and only we need to change in jsp pages and portlet action class code.

Note:

All portlet jps pages in /html/helloworld directory and the portlet parent directory start with docroot this is specially in liferay portlet development.

We need exclude docroot directory when we use JSP page full qualified path.


Example:

/html/helloworld/addEmployee.jsp
/html/helloworld/displayEmployees.jsp
/html/helloworld/view.jsp




 JSP Page (view.jsp)


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL  var="addEmployee" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/addEmployee.jsp"/>
</portlet:renderURL>
<portlet:renderURL  var="displayEmployees" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/displayEmployees.jsp"/>
</portlet:renderURL>
<portlet:resourceURL var="portletRresourceURL">

</portlet:resourceURL>
<h1>Welcome to Hello World Employee Portlet</h1>

<a href="<%=addEmployee.toString()%>">Add Employee</a><br/>
<a href="<%=displayEmployees.toString()%>">View All Employees</a><br/>


We will use render URL and we will specify custom parameter and there we specified respective jsp path need to be navigate.

When we click links then it will invoke portlet doView(--) method there we capture jsp path and render the page.

The following is Portlet class


public class HelloWorld extends GenericPortlet {

    public void init() {
        viewJSP = getInitParameter("view-template");
    }
   
    public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {
       
       String currentViewPage=renderRequest.getParameter("jspPage");
       if(currentViewPage!=null&&!currentViewPage.equals("")){
              include(currentViewPage, renderRequest, renderResponse);
       }else{
              include(viewJSP, renderRequest, renderResponse);
       }
    }

    protected void include(
            String path, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws IOException, PortletException {

        PortletRequestDispatcher portletRequestDispatcher =
            getPortletContext().getRequestDispatcher(path);

        if (portletRequestDispatcher == null) {
            _log.error(path + " is not a valid include");
        }
        else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }

    protected String viewJSP;

}


In the above code we will get URL parameter value i.e. jsp path. If the jsp page path available then we will render the page otherwise we will render default view page.

Out Put

Portlet Default View Page


Navigate to Add Employee Page


Display All Employees Page



Execute Portlet Action Method:

In the portlet we have processAction(--) method. If we want perform any action related portlet like insert data into the data base or other business logic then we will written code in process Action method. We will use Action URL to invoke portlet processAction(--) method.

Assume we are adding Employee Info to database

JSP Page (view.jsp)


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL  var="addEmployee" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/addEmployee.jsp"/>
</portlet:renderURL>
<portlet:renderURL  var="displayEmployees" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/displayEmployees.jsp"/>
</portlet:renderURL>
<portlet:resourceURL var="portletRresourceURL">

</portlet:resourceURL>
<h1>Welcome to Hello World Employee Portlet</h1>

<a href="<%=addEmployee.toString()%>">Add Employee</a><br/>
<a href="<%=displayEmployees.toString()%>">View All Employees</a><br/>


Add Employee JSP Page


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="addEmployeeActionURL" windowState="normal">
</portlet:actionURL>
<h1>This JSP Page for Add Employee</h1>
<form action="<%=addEmployeeActionURL%>" name="emplyeeForm"  method="POST">
Employee Name<br/>
<input  type="text" name="<portlet:namespace/>employeeName" id="<portlet:namespace/>employeeName"/><br/>
Employee Address<br/>
<input type="text" name="<portlet:namespace/>employeeAddress" id="<portlet:namespace/>employeeName"/><br/>
<input type="submit" name="addEmployee" id="addEmployee" value="Add Employee"/>
</form>


Portlet Action Class


public class HelloWorld extends GenericPortlet {

    public void init() {
        viewJSP = getInitParameter("view-template");
    }
   
    public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {
       
       String currentViewPage=renderRequest.getParameter("jspPage");
       if(currentViewPage!=null&&!currentViewPage.equals("")){
              include(currentViewPage, renderRequest, renderResponse);
       }else{
              include(viewJSP, renderRequest, renderResponse);
       }
    }
   
  public void processAction(ActionRequest request,ActionResponse response)throws PortletException,java.io.IOException{

        String emplyeeName=request.getParameter("employeeName");
        String employeeAddress=request.getParameter("employeeAddress");

        // wrire Business Logis Here to add data in DB

        System.out.println("Emplyee Name:"+emplyeeName);
        System.out.println("Emplyee Address:"+employeeAddress);
      
    }

    protected void include(
            String path, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws IOException, PortletException {

        PortletRequestDispatcher portletRequestDispatcher =
            getPortletContext().getRequestDispatcher(path);

        if (portletRequestDispatcher == null) {
            _log.error(path + " is not a valid include");
        }
        else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }

    protected String viewJSP;

}


Out Put

Portlet Default View Page


Navigate to Add Employee Page


Important Points:

We will use Action URL in add employee jsp page to execute portlet processAction(--) method.

We will submit the form and we are submitting employee details. In the jsp page we have used portlet tag library for creating action URL and we have used portlet name spaces tag for each input element.

Once we submit the form then form will be submitted to processAction(--) method using Portlet Action URL then we will capture form input values using getParameter(--) method.

Capture from input values or URL query string values in portet  processAction(--) method or doView(--) method we will use getParameter() method on request object


String emplyeeName=request.getParameter("employeeName");
String employeeAddress=request.getParameter("employeeAddress");


Send the Data from Process Action method to JSP pages.

Generally we need requirement that need to send some data from process action method to jsp pages.

After perform some business logic we need to send some data from process action to jsp pages
As we know portlet lifecycle always end with render Phase. Even if execute processAction(--) method after this it will execute the doView() method.

We have two ways to send data to JSP Pages or doView(--) method.
  1. setArrtibute and getAttribute on portlet  request object
  2. setRender parameter method on portlet response object


setArrtibute and getAttribute on portlet  request object

We will use set Attribute to set some object or value in process Action method and we will use get Attribute method in jsp page to get value in jsp.

Example:


public void processAction(ActionRequest request,ActionResponse response)throws PortletException,java.io.IOException{
        String emplyeeName=request.getParameter("employeeName");
        String employeeAddress=request.getParameter("employeeAddress");
        // wrire Business Logis Here to add data in DB
        Map<String,String> employeeMap=new HashMap<String,String>();
        employeeMap.put("employeeName",emplyeeName);
        employeeMap.put("employeeAddress",employeeAddress);
        request.setAttribute("employeeMap", employeeMap);
      
    }


In the above processAction(--) method we are passing employee data from map object, we will set map object in request.

Get the map object in JSP page


<%@page import="java.util.Map"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<h1>Display Employee Derails</h1>
<%
Map<String,String> employeeMap=(Map<String,String>)renderRequest.getAttribute("employeeMap");
if(employeeMap!=null){
%>
Emplyee Name: <%=employeeMap.get("employeeName")%>     <br/>
Emplyee Address: <%=employeeMap.get("employeeAddress")%><b/>
<%}%>


Get the map object in doView(--) page


public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {

 Map<String,String> employeeMap=(Map<String,String>)renderRequest.getAttribute("employeeMap");
       if(employeeMap!=null){
       String emplyeeName=employeeMap.get("employeeName");
       String employeeAddress= employeeMap.get("employeeAddress");
       }
       
       String currentViewPage=renderRequest.getParameter("jspPage");
       if(currentViewPage!=null&&!currentViewPage.equals("")){
              include(currentViewPage, renderRequest, renderResponse);
       }else{
              include(viewJSP, renderRequest, renderResponse);
       }
    }


Set Render parameter method on Portlet Response Object

Set Render Parameter method will set the parameter and its values in portlet query string. We can only set the string values using this method.

Example:

In the process action method


public void processAction(ActionRequest request,ActionResponse response)throws PortletException,java.io.IOException{
        String emplyeeName=request.getParameter("employeeName");
        String employeeAddress=request.getParameter("employeeAddress");
        
        response.setRenderParameter("employeeName",emplyeeName);
        response.setRenderParameter("employeeAddress",employeeAddress);  
      
    }


Get the Parameter Values in JSP Page that already set in Process Action


Emplyee Name: <%=renderRequest.getParameter("employeeName")%> <br/>
Emplyee Address: <%=renderRequest.getParameter("employeeAddress")%><br/>


Get the Parameter Values in Portlet doView (--) method that already set in Process Action


String emplyeeName=renderRequest.getParameter("employeeName");
String employeeAddress= renderRequest.getParameter("employeeAddress");


Scenario:1

Generally when we set the parameter values in render URL that will be available in other jsp page

Example:

View.jsp


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />

<portlet:renderURL  var="portletRenderURL" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/displayEmployees.jsp"/>
<portlet:param name="emplyeeName" value="Meera Prince"/>
</portlet:renderURL>

<h1>Welcome to Hello World Employee Portlet</h1>
<a href="<%=portletRenderURL.toString()%>">Execute Render Phase</a><br/>


disPlayEmplyee.jsp


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<h1>Display Employee Derails</h1>
Emplyee Name: <%=renderRequest.getParameter("employeeName")%> <br/>


In above scenario we set some parameter to portlet render URL in view.jsp page and we are navigating to another jsp page then the parameter value available in navigated jsp page.

It means when we set parameter and its value in render URL then it will be available in doView(--) method and navigated jsp page.

Scenario:2

When we apply same scenario for Action URL then values will be null in JSP page. When we set any parameter in action URL after executing processAction(--) method then the values not available in jsp page or doView(--) method.

Example:

view.jsp


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />

<portlet:actionURL var="portletActionURL" windowState="normal">
<portlet:param name="emplyeeName" value="Meera Prince"/>
</portlet:actionURL>

<h1>Welcome to Hello World Employee Portlet</h1>


<a href="<%=portletActionURL.toString()%>">Execute Process Action</a><br/>



After Executing Process Action it will execute default view page i.e. view.jsp again


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="portletActionURL" windowState="normal">
<portlet:param name="emplyeeName" value="Meera Prince"/>
</portlet:actionURL>
<h1>Welcome to Hello World Employee Portlet</h1>
<a href="<%=portletActionURL.toString()%>">Execute Process Action</a><br/>

EmplyeeName: <%=renderRequest.getParameter("employeeName")%>


In the above scenario after execute process it will navigate to view.jsp but parameter value not available it will be null.

The thing is when we use action URL if we set any values to the URL after execute process Action method then it won’t available

Solution:

We have to use set render parameter method in process action method so that the value available to jsp page.

Example:

In the process action method


public void processAction(ActionRequest request,ActionResponse response)throws PortletException,java.io.IOException{
        String emplyeeName=request.getParameter("employeeName");
        String employeeAddress=request.getParameter("employeeAddress");
        
        response.setRenderParameter("employeeName",emplyeeName);
        response.setRenderParameter("employeeAddress",employeeAddress);  
      
    }


Get the Parameter Values in JSP Page that already set in Process Action


Emplyee Name: <%=renderRequest.getParameter("employeeName")%> <br/>
Emplyee Address: <%=renderRequest.getParameter("employeeAddress")%><br/>


Get the Parameter Values in Portlet doView (--) method that already set in Process Action


String emplyeeName=renderRequest.getParameter("employeeName");
String employeeAddress= renderRequest.getParameter("employeeAddress");


Navigate to another JSP page after execute the process Action method

In this example we will navigate jsp page after execute processAction method

After execute process action method we will use set render parameter to set the jsp page to be navigated.

We can also set some data that is to be display in jsp page using set Attribute method.
In doView(--) method we will take that jsp path that already set in processAction(--) method and will navigate to the specified page.

Finally we will use get Attribute method to get the data from request object and we will display in the jsp page.

Example

View.jsp


<%@page import="java.util.Map"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL  var="addEmployee" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/addEmployee.jsp"/>
</portlet:renderURL>
<portlet:renderURL  var="displayEmployees" windowState="normal">
<portlet:param name="jspPage" value="/html/helloworld/displayEmployees.jsp"/>
<portlet:param name="emplyeeName" value="Meera Prince"/>
</portlet:renderURL>
<h1>Welcome to Hello World Employee Portlet</h1>
<a href="<%=addEmployee.toString()%>">Add Employee</a><br/>
<a href="<%=displayEmployees.toString()%>">View All Employees</a><br/>


Add Employee JSP page


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="addEmployeeActionURL" windowState="normal">
</portlet:actionURL>
<h1>This JSP Page for Add Employee</h1>
<form action="<%=addEmployeeActionURL%>" name="emplyeeForm"  method="POST">
Employee Name<br/>
<input  type="text" name="<portlet:namespace/>employeeName" id="<portlet:namespace/>employeeName"/><br/>
Employee Address<br/>
<input type="text" name="<portlet:namespace/>employeeAddress" id="<portlet:namespace/>employeeName"/><br/>
<input type="submit" name="addEmployee" id="addEmployee" value="Add Employee"/>
</form>



Portlet Action Class


public class HelloWorld extends GenericPortlet {

    public void init() {
        viewJSP = getInitParameter("view-template");
    }
   
    public void doView(
            RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {
       String currentViewPage=renderRequest.getParameter("jspPage");
       if(currentViewPage!=null&&!currentViewPage.equals("")){
              include(currentViewPage, renderRequest, renderResponse);
       }else{
              include(viewJSP, renderRequest, renderResponse);
       }
    }
   
     public void processAction(ActionRequest request,ActionResponse response)throws PortletException,java.io.IOException{
        String emplyeeName=request.getParameter("employeeName");
        String employeeAddress=request.getParameter("employeeAddress");
        Map<String,String> employeeMap=new HashMap<String,String>();
        employeeMap.put("employeeName",emplyeeName);
        employeeMap.put("employeeAddress",employeeAddress);
request.setAttribute("employeeMap", employeeMap);      response.setRenderParameter("jspPage","/html/helloworld/displayEmployees.jsp");
    }

    protected void include(
            String path, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws IOException, PortletException {

        PortletRequestDispatcher portletRequestDispatcher =
            getPortletContext().getRequestDispatcher(path);

        if (portletRequestDispatcher == null) {
            _log.error(path + " is not a valid include");
        }
        else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }
     protected String viewJSP;
}


Display Employee JSP Page


<%@page import="java.util.Map"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<h1>Display Employee Derails</h1>
<%
Map<String,String> employeeMap=(Map<String,String>)renderRequest.getAttribute("employeeMap");
if(employeeMap!=null){
%>
Emplyee Name: <%=employeeMap.get("employeeName")%>     <br/>
Emplyee Address: <%=employeeMap.get("employeeAddress")%><b/>
<%}%>


Out Put

Portlet Default View Page


Portlet Add Employee Page


Display Employee Derails Page


The above all is Generic Portlet and which is pure JSR 168&286 standard Portlet and it will be deployed in any portal which follows the JSR portlet standards.

Advantages:

Generic Portlet is JSR 168&286 standard portlet and it will be delayed in any portal which follows the JSR standards. So we no need to worry about deploy into different portals developed by portal vendors.

Limitations:

It is very basic portlet in portlet development and we need to implement many things.
Its basic sun implementation portlet and its have limited feature that will be defined JSR 168&286 specifications.

Related Articles:





Author

0 comments :

Post a Comment

Recent Posts

Recent Posts Widget

Popular Posts