Showing posts with label JSF Portlets Apllication. Show all posts
Showing posts with label JSF Portlets Apllication. Show all posts

How to pass request parameters in URL between JSF Pages

Passing request parameters with URL from one page to another and binding them in target pages is possible but using them with UIInput components is not. Because the param map is read-only. So update model phase in lifecycle fails if you are using as a value for UIInput components. To avoid this,
In the backing bean of the target page, define a variable and getter/setter for it. In the getter method; if the variable is null, initialize it with expressionResolver method. The expression parameter should be in #{foo} format.
    

private String myParam;

public String getMyParam() {
if (myParam == null) {
myParam = (String) expressionResolver("#{param.foo}");
}
return myParam;
}

public void setMyParam(String myParam) {
this.myParam = myParam;
}

public Object expressionResolver(String expression) {
Object value = null;

if ((expression.indexOf("#{") != -1) && (expression.indexOf("#{") < expression.indexOf('}'))) {
value = getFacesContext().getApplication().createValueBinding(expression).getValue(getFacesContext());
} else {
value = expression;
}
return value;
}
To use the value in the target page, bind myParam to a h:inputHidden component.
<h:inputHidden id="hiddenParam" value="#{yourBackingBean.myParam}"/>


For example you can use the value in javascript like,

var myParam = document.getElementById('form1:hiddenParam').value;
Click here to View more...

JSF Portlet Tag Library

There is a tag library that contains tags for JavaServer Faces components used in Portal enviornment. These components are *not* part of the standard JavaServer Faces Specification. All JSF tags in a portlet should be embedded with this tag if multiple instances of the same portlet can exist within a portal page.

Usage:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/portlet/components" prefix="p" %>

<%-- Embed JSF tags with in portletPage tag if you expect multiple instances of this portlet to exist within a portal page --%>
<f:view>
<p:portletPage>
.....................
.....................
</p:portletPage>
</f:view>


Click here to View more...

Auto Focus on particular element on page load in JSF

Inside <f:view> place the following scriplet..

<%
javax.faces.context.FacesContext.getCurrentInstance()
.getViewRoot().setLocale(request.getLocale());
%>

-------------------------------------------------------------
Above </h:form> plce the following code...
The target filed (XXXX) indicates which field should have focus on page load

<hx:inputHelperSetFocus id="setFocus1" target="XXXX"
rendered="true"></hx:inputHelperSetFocus>


Click here to View more...

Problems related with ValueChangeListeners in JSF

Ok now I never quite figured this one out. The idea behind value change listeners should be simple. However EVERYONE gets confused because they don’t execute when expected.


Ok what you might of missed! Value change listeners are fired before the Setter methods are called.

So what?

Well this means any changes you make to variables from your value change method will be overwritten when the setters are called.


So I commonly hear just call FacesContext.getCurrentInstace.renderResponse()

so this should skip the phases meaning the setters are not called and go directly to the render response phase.

At first glance yes perfect it works.

What it doesn't do is update the VIEW ?
The getters are never called on your managed bean properties which means that the view is never updated with the values you change from you valueChangeListener.

How annoying :) so how to get around this.


1) You can force JSF to recreate the view.

Make a navigation rule to navigate back to the same page and call it in your value change method.

FacesContext.getCurrentInstance().getApplication().getNavigationHandler().
handleNavigation(FacesContext.getCurrentInstance(),null,"test");

< navigation-rule >
< from-view-id > /myPage.jsp< /from-view-id >
< navigation-case >
< from-outcome > test< /from-outcome >
< to-view-id > / myPage.jsp< /to-view-id >
< /navigation-case >
< /navigation-rule >

2) Move the value change event to the update model phase.

This way your setters are called before your value change event something like

public void changeMethod(ValueChangeEvent event)
{
PhaseId phaseId = event.getPhaseId();
String oldValue = (String) event.getOldValue();
String newValue = (String) event.getNewValue();
if (phaseId.equals(PhaseId.ANY_PHASE))
{
event.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
event.queue();
}
else if (phaseId.equals(PhaseId.UPDATE_MODEL_VALUES))
{
// do you method here
}
}

3) Create your UICcomponents in your bean (use binding) and from your value change method call the .setMethod() on the UIComponents, then call the FacesContext.getCurrentInstance().renderResponse();
It appears the getters are called if you update the UI components directly.




I know these seems like hacks but for now I have not found any better solutions to what really seems like a flaw in the design

Click here to View more...

jsp:include page - Error - javax.servlet.jsp.JspException: Assertion Failed

Here are rules when including JSF pages that need to be followed.


i) The "top level" JSF page must have an tag surrounding all JSF tags being used. Since you seem to be mixing and matching simple JSPs and JSF pages I'm not clear if that will always be the case in what you describe

ii) The content of the included JSF (faces) page fragments need to be surrounded with tags. These f:subview tags can either be in the included page or surround the include statement in the including page. Either is fine.

iii) All non JSF tags and content in the included JSF (faces) page fragments need to be surrounded by f:verbatim tags.

If you're using JSF with a JSP renderer, make sure you're following all of these rules.

If you're building a system with lots of includes and you're using JSF, I'd probably suggest that you consider Facelets. It eliminates requirement (iii) and has expanded support for templating and dynamic inclusion. It does however introduce a few other requirements, most notably that your pages be strict XML.
Click here to View more...

Inter Portlet Communications IPC JSR168

This article demonstrates the steps performed to implement JSR 168 compliant cooperative portlets using IBM Rational Application Developer V6.0 and WebSphere Portal Server V5.1. The article illustrates passing multiple values from source portlet to target portlet without defining complex data type inside WSDL file.

The term cooperative portlets refers to the capability of portlets on a page to interact with each other by sharing information. One or more cooperative portlets on a portal page can automatically react to changes from a source portlet triggered by an action or event in the source portlet. Portlets that are targets of the event can react so that users are not required to make repetitive changes or actions in other portlets on the page. Cooperation between source and target portlets is facilitated by a WebSphere Portal runtime entity called the property broker. Portlets on a page can cooperate in this way even if they were developed independently, without the programmer's awareness of the existence of the other cooperative portlets.

JSR 168 is a specification from the Java Community Process for portlet development. IBM WebSphere Portal V5.1 provides support for the JSR 168 API. With an IBM extension, WebSphere Portal V5.1 supports cooperative portlets for JSR 168 portlets, in which one JSR 168 portlet can communicate with another JSR 168 portlet.

To develop and deploy the sample application, we used the following IBM products:

  1. Rational Application Developer for Rational Software Development Platform V6.0
  2. WebSphere Portal V5.1.x
Introducing the DemoPortlets scenario
In the DemoPortlets scenario we are going to create two JSR 168 portlets. The DemoPortlet1 will pass the multiple values to the DemoPortlet2 without defining complex data type inside WSDL file.

DEMOPORTLET1:
Gets the input from the user in three fields and then passed these input values to the target portlet. This portlet is our source portlet. (See Figure 1.)

DEMOPORTLET2:
Act as a target portlet and retrieve those three entered values from DemoPortlet1 and display them on the page. (See Figure 2.)

Create Portlet Project (JsR 168)
Start the IBM Rational Application Developer (IRAD).

  1. With the IRAD workbench started, switch to the Web perspective by clicking Window > Open Perspective >Web.
  2. Click New > Other
  3. Select Portlet Project (JSR 168) from the list. This launches the New Portlet Project (JSR 168) wizard (See Figures 3 and 4.)
  4. Enter DemoPortlets as the Name.
  5. Clear the Create a portlet checkbox. You will create your portlets separately in order to have better control over portlet naming conventions.
  6. Click the Show Advanced button.
  7. Select WebSphere Portal v5.1 Unit Test Environment in the Target Server list.
  8. Accept defaults for the other fields.
  9. Click Finish
Create DemoPortlet1 (JSR 168)
  1. Select the DemoPortlets project in the Project Navigator view.
  2. Right-click to bring up the context menu, and click New > Portlet. This launches the New Portlet wizard
  3. Enter DemoPortlet1 as the Default Name prefix, click Next (See Figure 5.)
  4. Accept default values and click Finish.
Create Portlet2 (JSR 168)
As a same way create DemoPortlet2 portlet.

Enabling the DemoPortlet1 as a source
JSR 168 portlets can cooperate with each other by exchanging properties via the property broker. A WSDL file describes publish (or send) to the property broker.

DESCRIBING THE SOURCE WITH WSDL
To enable our DemoPortlet1 portlet as a property source, simply right-click the portlet in the Project Explorer view to display the Enable Source (See Figure 6.)

Once the Enable Cooperative Source wizard launches enter the illustrated values: (See Figure 7.)

  • A name for the Data type
  • The Namespace for the new data type
  • What you want your parameter Bound to

The term parameter refers to how the value will be transferred from the source portlet to the target portlet. The choices are:

  1. None: This setting implies that you will not specify the way the value will be passed, so the default behavior for portlet
  2. Render Parameter: Supports only strings. The string value will be bound to the RenderRequest object. The render phase and retrieved during the render phase of the portlet lifecycle. It cannot be retrieved during the action phase.
  3. Request Parameter: Supports only strings. The string value will be bound to the ActionRequest object, and can stage of the portlet lifecycle. The parameter value will be meaningless at the conclusion of request processing (that invocation).
  4. Request Attribute: Supports any JavaBean type. The bean will be bound to the ActionRequest object. Lifecycle Request Parameter.
  5. Session: Supports any JavaBean type. The bean will be bound to the session object and will persist for the duration and the portal server.
The Enable Cooperative Source wizard generates a WSDL file that describes the portlet to the property broker tagged with a distinctive icon to indicate that it is a property source. The WSDL file contains the following sections:
  • Types: This section describes data types (using XML schema) that can be emitted by the source portlet.
  • Messages: This section describes messages that can be produced or consumed by the portlet.
  • Port Type: This section describes the abstract interface of the portlet as seen by the property broker.
  • Binding: This section describes how the abstract interface (port type) is implemented.
To define the second attribute, right-click the portlet again and select Cooperative->Enable Source Define the following values: (See Figure 8.)

For the third attribute, perform the same step, as mentioned above, and provide following values: (See Figure 9.)

Source WSDL
Once we done with the wizard, the WSDL file should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="DemoPortlet1portlet_Service"
targetNamespace="http://demoportlets"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:portlet="http://www.ibm.com/wps/c2a"
xmlns:tns="http://demoportlets"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<types>
<xsd:schema targetNamespace="http://demoportlets">
<xsd:simpleType name="IDDatatype">
<xsd:restriction base="xsd:string"></xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="NameDatatype">
<xsd:restriction base="xsd:string"></xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="StateDatatype">
<xsd:restriction base="xsd:string"></xsd:restriction>
</xsd:simpleType>
</xsd:schema>
</types>
<message name="IDDatatype_Response">
<part name="IDDatatype_Output" type="tns:IDDatatype" />
<part name="NameDatatype_Output" type="tns:NameDatatype" />
<part name="StateDatatype_Output" type="tns:StateDatatype" />
</message>
<portType name="DemoPortlet1portlet_Service">
<operation name="DemoPortlet1portlet">
<output message="tns:IDDatatype_Response" />
</operation>
</portType>
<binding name="DemoPortlet1portlet_Binding"
type="tns:DemoPortlet1portlet_Service">
<portlet:binding />
<operation name="DemoPortlet1portlet">
<portlet:action name="MyAction" actionNameParameter="ACTION_NAME" type="standard"
caption="output.data" description="Output.Data" />
<output>
<portlet:param name="FormID" partname="IDDatatype_Output" boundTo="request-attribute"
caption="output.ID" />
<portlet:param name="FormName" partname="NameDatatype_Output"
boundTo="request-attribute" caption="output.NAME" />
<portlet:param name="FormState" partname="StateDatatype_Output"
boundTo="request-attribute" caption="output.STATE" />
</output>
</operation>
</binding>
</definitions>

Note: Make sure the captions and description are defined for and attributes. However, these fields are optional but very useful while creating wires.


Enabling DemoPortlet2 as Target
GENERATING THE WSDL
You will use the Enable Cooperative Target wizard to generate the WSDL. To launch the wizard, simply select the portlet and click Cooperative > Enable Target (this step is nearly identical to enabling cooperative source).(See Figure 10.)

Once the Enable Cooperative Target wizard launches enter the illustrated values:(See Figure 11.)

  • Data type: Use the exact same name that you used when you enabled the source portlet.
  • Namespace: Again, the namespace that you enter here should be the same one you used for the source.
  • Action: Use the exact same name that you used when you enabled the source portlet.
  • Parameter: Use the exact same name that you used when you enabled the source portlet.
  • Bound to: Choose None from the list.
  • Label and Description: These fields are optional, but should be filled in; as they will help you create the wires
In order to define the remaining two attributes for the same target portlet, DO NOT use the wizard. We have to define them inside the WSDL file directly. Open the DemoPortlet2portlet.wsdl file and make the modifications according to the WSDL Source.

WSDL CODE

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="DemoPortlet2portlet_Service"
targetNamespace="http://demoportlets"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:portlet="http://www.ibm.com/wps/c2a"
xmlns:tns="http://demoportlets"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<types>
<xsd:schema targetNamespace="http://demoportlets">
<xsd:simpleType name="IDDatatype">
<xsd:restriction base="xsd:string"></xsd:restriction>
</xsd:simpleType>
</xsd:schema>
<xsd:schema targetNamespace="http://demoportlets">
<xsd:simpleType name="NameDatatype">
<xsd:restriction base="xsd:string"></xsd:restriction>
</xsd:simpleType>
</xsd:schema>
<xsd:schema targetNamespace="http://
demoportlets">
<xsd:simpleType name="StateDatatype">
<xsd:restriction
base="xsd:string"></xsd:restriction>
</xsd:simpleType>
</xsd:schema>
</types>
<message name="IDDatatype_Request">
<part name="IDDatatype_Input" type="tns:IDDatatype" />
<part name="NameDatatype_Input" type="tns:NameDatatype" />
<part name="StateDatatype_Input" type="tns:StateDatatype" />
</message>
<portType name="DemoPortlet2portlet_Service">
<operation name="DemoPortlet2portlet">
<input message="tns:IDDatatype_Request" />
</operation>
</portType>
<binding name="DemoPortlet2portlet_Binding" type="tns:DemoPortlet2portlet_Service">
<portlet:binding />
<operation name="DemoPortlet2portlet">
<portlet:action name="MyAction" actionNameParameter="ACTION_NAME" type="standard"
caption="input.Data" description="Input Data from Source Portlet" />
<input>
<portlet:param name="FormID" partname="IDDatatype_Input" caption="input.ID" />
<portlet:param name="FormName" partname="NameDatatype_Input" caption="input.NAME" />
<portlet:param name="FormState" partname="StateDatatype_Input" caption="input.STATE" />
</input>
</operation>
</binding>
</definitions>

Note: Make sure the captions and description are defined for and attributes. However, these fields are optional but very useful while creating wires.The IRAD generates the DemoPortlet1portlet.wsdl and DemoPortlet2portlet.wsdl file. (See Figure 12.)


Java Class Modifications:
After defining the attributes and the portlet action in the WSDL file, the following code need to be written:

1. Open DemoPortlet1Portlet.java file.

2. Declare the following attributes:

public static final String FORM_ID = "FormID";
public static final String FORM_NAME = "FormName";
public static final String FORM_STATE = "FormState";
public static final String ACTION_TEXT = "MyAction";

Note: Make sure the values of FORM_ID, FORM_NAME and FORM_STATE must be same to the name defined for in the WSDL file.

3. Modify processAction() method

public void processAction(ActionRequest request, ActionResponse response) throws
PortletException, java.io.IOException {

String id = request.getParameter(FORM_ID);
String name = request.getParameter(FORM_NAME);
String state = request.getParameter(FORM_STATE);

request.setAttribute(FORM_ID, id);
request.setAttribute(FORM_NAME, name);
request.setAttribute(FORM_STATE, state);
}

3. Save the changes

4. Open DemoPortlet2PortletSessionBean.java and define following attributes

private String id = "";
private String name = "";
private String state = "";

5. Generate getter and setter methods for the above attributes and save the changes.

6. Open DemoPortlet2Portlet.java file.

7. Declare the following attributes:

public static final String FORM_ID = "FormID";
public static final String FORM_NAME = "FormName";
public static final String FORM_STATE = "FormState";
public static final String ACTION_TEXT = "MyAction";

Note: Make sure the values of FORM_ID, FORM_NAME and FORM_STATE must be same to the name defined for in the WSDL file.

8. Modify processAction() method

public void processAction(ActionRequest request, ActionResponse response) throws
PortletException, java.io.IOException {
DemoPortlet2PortletSessionBean sessionBean = getSessionBean(request);
String id = request.getParameter(FORM_ID);
String name = request.getParameter(FORM_NAME);
String state = request.getParameter(FORM_STATE);
sessionBean.setId(id);
sessionBean.setName(name);
sessionBean.setState(state);
}

9. Save the changes

JSP Modifications:
1. Open DemoPortlet1PortletView.jsp

2. Modify the JSP code as follows:

<%@ page session="false" contentType="text/html"
import="java.util.*,javax.portlet.*,demoportlet1.*" %>
<%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>


<%
PortletURL actionUrl = renderResponse.createActionURL();
actionUrl.setParameter("ACTION_NAME", DemoPortlet1Portlet.ACTION_TEXT);
%>

">
Enter ID: "
type="text"/>

Enter Name: "
type="text"/>

Enter State: "
type="text"/>

" type="submit"
value="Submit"/>




3. Save the changes

4. Open DemoPortlet2PortletView.jsp

5. Modify the JSP code as follows:

<%@ page session="false" contentType="text/html"
import="java.util.*,javax.portlet.*,demoportlet2.*" %>
<%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>


<%
DemoPortlet2PortletSessionBean sessionBean =
(DemoPortlet2PortletSessionBean)renderRequest.getPortletSession()
.getAttribute(DemoPortlet2Portlet.SESSION_BEAN);
%>

Entered Id is = <%= sessionBean.getId()%>

Entered Name is = <%= sessionBean.getName()%>

Entered State is = <%= sessionBean.getState()%>

6. Save the changes

Deploy the DemoPortlets.war portlet

  1. Export the DemoPortlets Project as a WAR file.(See Figure 13.)
  2. Install the DemoPortlets.war file in WebSphere Portal Server (See Figure 14.)
  3. Once the installation of the portlet is completed. Create the page
  4. Place both the portlets on the same page
  5. Create the wires between both portlets by selecting the Wire link on top of the page
  6. Define a wire for each attribute defined and click Add wire, as shown in the figure (See Figure 15.)
  7. Once all the wires created press Done.
  8. Go to the page where both portlets are placed.
  9. Test the portlets by entering dummy data and press Submit. You should see the values on the second portlet.
Conclusion
The WebSphere Portal Server Property Broker allows passing complex data between portlets without defining complex data type inside the WSDL files. Click here to View more...

JSF Portlet Session Maintenance

To Maintain the Sessions between the two portlets which are deployed on the same portlet page we have to follow the below steps.

Each Portlet Instance does not preserve its independent session, all the instance of the portlet share the same managed beans. This happens because the PortletSession object by default maintains the attributes in APPLICATION SCOPE (this can be used whenever you need all your portlet instances to share the same attribute) But if you need your portlets to have their independent attribute values then we need to set the scope as PORTLET SCOPE. To say this point clear the below sample is explained.

The scenario which I faced for this is: I had a created a Jsf Portlet in eclipse 3.4 Ganymede, The name of the project is FinalJSFTest3 in that faces jsp name which is FinalJSFTestView.jsp, success’s.jsp and the bean which i used for this is FinalJSFBean.java. The FinalJSFBean.java contains both setters and getters and the action which u want to perform when u click on the jsp button is also in this bean.

When u deployed this application in WPS v6.1, The flow of this application is as follows:

1) The portal server load the web.xml first and from the web.xml it will redirect to portlet.xml

2) From the portlet.xml file depending upon the class mentioned it loads the Faces context class and loads the FinalJSFTestVeiw.jsp page.

3) The FinalJSFTestVeiw.jsp page contains two input textboxes and with a submit button.

4) When u fill the data in the text boxes as soon as, when u click on the submit button a request has been sent to the faces-config.xml file. And depending upon the action which u write for the bean it goes to the bean and executes the appropriate action and returns the value form the action.

5) Depending upon the action it redirects to the appropriate page.

Here the problem which i faced is If i add the same portlet twice in the same page and If I submit values in the first portlet and I click on the submit button

It navigates to the next page (success.jsp) with the values which I have given in the first page, there I have a back button in the success.jsp page if I click on the back button it will goes to the previous page. Here the values which I send in the first page can be viewed in the second page upto now the scenario is fine. The problem here is the values which I send in the second portlet page is navigates to success page with values by the same time it is updating the values in the first portlet page which is a wrong session maintenance. For this I followed the below scenario:

In the bean when we are setting the attributes in general we set in a request.setAttribute. but in the JSF Bean we don’t have Render request, Render response so i set these values in a sessionAttribute which is a portletSession and I maintained these values in the PortletScope.

See the example code here.

In the above code on buttonAction () it is executing some code. In this code first i get the currentInstance of the FacesContext object and i stored that currentInstance in a facesContext and i set the portletSession to null. And i setting the portletSession to true using the request.getPortletSession(true), thereafter iam setting the attribute values using portletSession.setAttribute (String arg0, Object arg1, int arg2) here the above code is reflected as follows String “username”, Object username, int portletSession.PORTLET_SCOPE. It is a JSF Bean so iam returning the successfrombean. It is mapped with faces-config.xml file. i.e. we have an add rule concept in JSF that depending upon the output returned from the action we can navigate to another page which we mapped to that output action. In the same way depending upon this successfrombean it is going to navigate to success.jsp page.

In the success.jsp page we want to show the values which we passed in the FinalJSFTestView.jsp page. For that i done with the below code.

Using the above code I retrieved the values from the FinalJSFTestView.jsp page and I stored those values in a portletSession.PORTLET_SCOPE.

With the above methodology we can maintain a individual session for each portlet in jsf portlets. With this the session will won’t conflict each other the data can’t clash any where through out that portlet scope. We can also call it is Inter-portlet communication with in the application.

For PortletSession Maintenance you can see the following references.

http://www.jroller.com/HazemBlog/entry/migration_of_jsf_application_to

Note: The above PortletSessionMaintenance problem is explained for JSFPortlet project. Here we don’t have a doView(), doProcessaction ()
Click here to View more...

Where JSF and Portlets went wrong.

JSF and Portlets promised to integrate the web, but in reality they just brought more confusion and lock-in. One of the main goals is to provide a lightweight alternative for web integration.

JSF promise was to be able to reuse web components among different frameworks that correspond to one standard. However the standard, as always, have left more things open than specified, and in reality we didn't even come near to actually reusing components between frameworks (try using ICEFaces components with ADFFaces). What's worse, JSF have imposed on us a highly complex and clumsy API, that one needs to follow to achieve even a little reusability and broke the familiar way of capturing logic in custom JSP tags.

While third-party options (like Facelets) do make programming with JSF easier, one still has to jump through hoops just to get simple reusable components. And since the components are not really Java objects, there is almost no good way to enforce a normal contract for their communication.

The trouble is that we already have a great tool for building and integrating disparate components—it is called the Java programming language. Object-oriented design have been proven to be a viable solution for already two decades, and it is just sad to see that the designers of JSF have ignored it to pursue type unsafe and hard to debug design that looks more than a bit like Struts, revisited.

Which brings us to our second offender—Portlets. Although Portlets were the first to achieve actual remote integration among different web applications, they also did that with a model that is limiting in every way possible. There is almost no communication between portlets, there is no way to embed portlets in other portlets, and some of the worst aspects of servlets (like static configuration and global contexts) have been carbon copied to the portlet spec. However instead we get modes, window states, persistent store and user profiles, which don't have much to do with the integration itself and should really have been provided on top of that and not all in one spec.

In my mind these specifications share the same trouble as the infamous EJBs:

  • They are designed by a committee
  • They are not standardizing something existing, but creating a new solution on paper
  • They are designed largely by and for tool makers, instead of developers

Now, selling tools is a great goal for those of us who make them. But tool-oriented specifications have insofar turned out to be less than successful. The EJB world is rapidly moving towards lightweight solutions like Spring and Hibernate, which instead of providing shiny tool support have a simple and clean design and just do their job well. The developers became so bitter from the tools, mappings and bytecode postprocessing, that Plain Old Java Objects became a buzzword that sells considerably better than MDA.

Now the situation is rapidly improving in the application server ecosystem, and with EJB 3.0 being a mix of Spring and Hibernate with a healthy dose of annotations, we are definitely looking to a brighter future (though the point of the rubber stamping perfectly good open source frameworks as a standard is still unclear to me).

However the situation in the web framework ecosystem is yet to achieve the same level of enlightenment. Currently we are looking at a large number of incompatible web frameworks that kill any hope of integration and reuse even before it appears. Many of these frameworks are really innovative (Wicket, Tapestry, RIFE come to mind and Seaside deserves an honorable mention), but there is no way to use their strength without also accepting their weaknesses.

It is our belief that different approaches are needed for different types of web applications. For example blog engines do well with a REST semantics, while complex enterprize applications do better with a component semantics and in some other cases one needs differently proportioned mix of the two or something altogether different. Aranea goal is to capture different types of these semantics in a simple and clean component model:

  • Services capture REST semantics
  • Widgets capture stateful component semantics

However to become actually useful you also need to connect the two, so we have Components that are a supertype of both and capture component lifecycle, communication and hierarchy. As a result we get a lightweight implementation of the Hierarchical Model-View-Controller pattern that allows to actually use both approaches at the same time.

What's more, since service and widgets capture the essence of their semantics they should allow to host similar constructions from different web frameworks providing an interoperability layer with a simple and clean API (widget interface has 4 meaningful methods not counting the 4 more lifecycle ones and does not need any configuration). It is indeed our intention that the minimalistic Aranea core would be usable to integrate together different web frameworks, allowing to seamlessly use them together in one application combining (to some extent) different approaches when needed.

Next to that goal it becomes relatively simple to just reuse components between applications a la JSF or combine several subapplications into one a la Portlets. Remote integration is trickier, but it shouldn't be too hard to host portlets or provide a WSRP adaptor.

Although we still have to talk in future tense about integrating the open source web frameworks (and possibly JSF), we have already achieved a lot of reusability and integration in terms inside and between applications, as well as with an internal legacy web framework. We hope that it will go just as smoothly with the other frameworks and we will be able to deliver on the JSF and Portlet promise.

Click here to View more...

JSF Portlets


Why JSF and Portlets?

Why should I combine JavaServer Faces (JSF) and Portlets? Why did you build up such a website?


If you have questions like these, be assured:

JSF and Portlets are a great team in order to
create modern und powerful websites.



Portlets have been available for some time now. There
are plenty of websites based on the portlet technology.
But programming portlets is sometimes a bit exhausting,
because you have to use "old" JSP- and Servlet programming
technologies.



On the other hand you have quite powerful webframeworks like
JavaServer Faces. With JSF you have a fantastic base for
creating user interfaces for web applications.



In December 2006 a new JSR was born: JSR-301. The main goal
of this JSR was the combination of JSF and Portlets.
So for the future it will be possible you have both powerful
technologies without feeling any pain during integration.



The main target of this website is to provide tutorials and
knowhow, how you can use this great combination.


JSR-168 and JSR-286


All started with JSR-168 some years ago. This was the first specification for
a portlet standard. Though the JSR-168 was not catching all aspects of portlet programming,
it was still a great success to have a common standard in the industry.
Nowadays, nearly all developers build their portlet application based on this standard.



Because of the lack of some very important features in the specification, a second
version (or an enhancement of JSR-168) was started: JSR-286. This specification is
going to standardize features like eventing, public render parameters or portlet filters.



Now, with the enhanced specification of the portlet development it will be possible
to create powerfull AND standard-based portlet applications.

In my opinition, this is a big step towards the acceptance of Portals and Portlets in
the industry.



JSR-127, JSR-252 and JSR-314


With JSR-127, a new user-interface framework was standardized. The process began in 2001.
The expert group defined the first standard for a framework targeting the user interface
in web applications.



JavaServer Faces, the name of the framework, was very successful from the beginning. A lot
of companies used this standard for building their web user interface.
With JSR-252 a next step of the specification (and reference implementation) was done. The
main new thing was, that JSF 1.2 belongs to Java EE 5. That means, every Java EE 5 compatible
Application Server runs with JSF.



JSR-314 is the next version of JSF. JSF 2.0 is developed at the moment within this
JSR. Hopefully at the end of 2008 we will see the result of the expert group.





JSR-301


Portlets and JavaServer Faces are both great frameworks. Both are based on standards
and both technologies are acknowledged in the industry.



But the combination of JSF and Portlets was not easy in the past. It was hard to create
a mapping of the lifecycles of each framework and also to use all aspects of JSF within
the portlet container.



With JSR-301 (Portlet Bridge Specification for JavaServer Faces), a new JSR started with
the goal to standardize a bridge for using both technologies.









Combining JSF with Portlets - Step 1


In the following pages a simple portlet based on JavaServer Faces
is created. It is shown, how you can integrate JSF and Portlets using
the JSR-301 Portlet Bridge.


This tutorial is the first approach to demonstrate the usage of the
JSR-301 bridge. As the bridge is still "work in progress", changes could
occur in the future :-)



Within the following pages we will build a very simple portlet with some
JSF-pages and components. The example is based on Apache Pluto 1.1.4,
Apache Tomcat 6.0.14, JSF 1.2_05 (Reference Implementation) and JSTL 1.2.

Click here to View more...

JSF & JSF Portlets Apllication

Table Of Contents

1. Introduction. 3

2. Files In JSF Application. 3

3. Directory Structure. 4

4. XML files. 4

5. JAR files. 4

6. How does JSF work?. 5

7. JSF Lifecycle. 7

8. A simple JSF Application. 10

9. A simple JSF Portlet Application. 10

10. References 11


INTRODUCTION

JavaServer Faces (JSF) is a technology that helps you build user interfaces for dynamic Web applications that run on the server. The JavaServer Faces

framework manages UI states across server requests and offers a simple model for the development of server-side events that are activated by the client. JSF is

consistent and easy to use.

A JSF application looks like any other servlet/JSP application. It has a deployment descriptor, JSP pages, custom tag libraries, static resources, and so on. The user interface of a JSF application is one or many JSP pages that host JSF components such as forms, input boxes, and buttons. These components are represented by JSF custom tags and can hold data. A component can be nested inside another component, and it is possible to draw a tree of components. In fact, a JSP page in a JSF application is represented by a component tree. Just as in normal servlet/JSP applications, you use JavaBeans to store the data the user entered.

Files in a JSF Application

(1) JSP pages

(2) Java class filesPublish Post

(3) XML files

(4) JAR files

(5) Resource bundle (if any)

The important xml files are:

  1. web.xml
  2. faces-config.xml

The jar files required are: (specific to JSF applications)

  1. commons-beanutils.jar
  2. commons-collections.jar
  3. commons-digester.jar
  4. commons-logging.jar
  5. jsf-api.jar
  6. jsf-impl.jar
  7. jstl.jar
  8. standard.jar

Directory Structure:

Project

/ JavaSource

Properties file (Resource Bundle)

.java files

/ WebContent

/ WEB-INF

/ classes

/ lib

JAR files

faces-config.xml

web.xml

/ pages

XML files:

web.xml

This file inside the WEB-INF folder is the Web Application Deployment Descriptor for your application. This is an XML file describing the servlets and other components that make up the application.

faces-config.xml

This file inside the WEB-INF folder is the Java Server Faces configuration file. This file lists bean resources and navigation rules.

JAR files:

  • commons-beanutils.jar: Utilities for defining and accessing JavaBeans component properties
  • commons-collections.jar: Extensions of the J2SE Collections Framework
  • commons-digester.jar: For processing XML documents
  • commons-logging.jar: A general purpose, flexible logging facility to allow developers to instrument their code with logging statements
  • jsf-api.jar: Contains the javax.faces.* API classes
  • jsf-impl.jar: Contains the implementation classes of the JSF Reference Implementation

Note that the JSF framework uses the Java Server Pages Standard Tag Library (JSTL), and therefore it is assumed that the web container you use provides the necessary JAR files for JSTL.

How Does JSF Work?

A JSF application works by processing events triggered by the JSF components on the pages. These events are caused by user actions. For example, when the user clicks a button, the button triggers an event. You, the JSF programmer, decide what the JSF application will do when a particular event is fired. You do this by writing event listeners. In other words, a JSF application is event-driven. Figure 1 illustrates the processing of a JSF application.

When an event occurs (say, when the user clicks a button), the event notification is sent via HTTP to the server. On the server is a special servlet called the FacesServlet. Each JSF application in the Web container has its own FacesServlet.

In the background, three things happen for each JSF request, as illustrated in Figure 2.

For JSF requests to be processed, they must be directed to a servlet called FacesServlet. The redirection is accomplished by using the following servlet and servlet-mapping tags in the deployment descriptor:



<servlet>
<servlet-name>Faces Servletservlet-name>
<servlet-class>javax.faces.webapp.FacesServletservlet-class>
<load-on-startup>1load-on-startup>
servlet>

<servlet-mapping>
<servlet-name>Faces Servletservlet-name>
<url-pattern>/faces

This means that the URL of every request must contain the /faces/ pattern, as specified in the url-pattern element under the servlet-mapping element.

JSF Applications

Figure 1 JSF applications are event-driven


NOTE You can specify a context parameter saveStateInClient with a value of true to force JSF to save state in the client as opposed to saving it in the server. If you choose to do so, you must add the following context-param element before the servlet element in your deployment descriptor.


<context-param>
<param-name>saveStateInClientparam-name>
<param-value>falseparam-value>
context-param>

FacesServlet creates an object called FacesContext, which contains information necessary for request processing. To be more precise, FacesContext contains the ServletContext, ServletRequest, and ServletResponse objects that are passed to the service method of FacesServlet by the Web container. During processing, FacesContext is the object that is modified.

JSF

Figure 2 How JSF works in a nutshell

Next is the processing. The processor is an object called Lifecycle. The FacesServlet servlet hands over control to the Lifecycle object. The Lifecycle object processes the FacesContext object in six phases, which we will look at next.

NOTE The series of actions necessary for JSF request processing by the Lifecycle object is referred to as the request processing lifecycle. You will encounter this term throughout this book.

JSF also allows you to configure a JSF application via an application configuration file. After discussing the Lifecycle object phases, we will discuss how to use this configuration file to register JavaBeans.

JSF Lifecycle

Figure 3 The JSF lifecycle

Phase 1: Restore view

In the first phase of the JSF lifecycle -- restore view -- a request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page.

The JSF framework controller uses the view ID to look up the components for the current view. If the view doesn't already exist, the JSF controller creates it. If the view already exists, the JSF controller uses it. The view contains all the GUI components.

This phase of the lifecycle presents three view instances: new view, initial view, and postback, with each one being handled differently. In the case of a new view, JSF builds the view of the Faces page and wires the event handlers and validators to the components. The view is saved in a FacesContext object.

The FacesContext object contains all the state information JSF needs to manage the GUI component's state for the current request in the current session. The FacesContext stores the view in its viewRoot property; viewRoot contains all the JSF components for the current view ID.

In the case of an initial view (the first time a page is loaded), JSF creates an empty view. The empty view will be populated as the user causes events to occur. From an initial view, JSF advances directly to the render response phase.

In the case of a postback (the user returns to a page she has previously accessed), the view corresponding to the page already exists, so it needs only to be restored. In this case, JSF uses the existing view's state information to reconstruct its state. The next phase after a postback is apply request values.

Phase 2: Apply request values

The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values. Component values are typically retrieved from the request parameters, although they can also be retrieved from cookies or headers.

If a component's immediate event handling property is not set to true, the values are just converted. So if the field is bound to an Integer property, the value is converted to an Integer. If the value conversion fails, an error message is generated and queued in the FacesContext, where it will be displayed during the render response phase, along with any validation errors.

If a component's immediate event handling property is set to true, the values are converted to the proper type and validated. The converted value is then stored in the component. If the value conversion or value validation fails, an error message is generated and queued in the FacesContext, where it will be displayed during the render response phase, along with any other validation errors.

Phase 3: Process validation

The first event handling of the lifecycle takes place after the apply request values phase. At this stage, each component will have its values validated against the application's validation rules. The validation rules can be pre-defined (shipped with JSF) or defined by the developer. Values entered by the user are compared to the validation rules. If an entered value is invalid, an error message is added to FacesContext, and the component is marked invalid. If a component is marked invalid, JSF advances to the render response phase, which will display the current view with the validation error messages. If there are no validation errors, JSF advances to the update model values phase.

Phase 4: Update model values

The fourth phase of the JSF application lifecycle -- update model values -- updates the actual values of the server-side model -- namely, by updating the properties of your backing beans (also known as managed beans). Only bean properties that are bound to a component's value will be updated. Notice that this phase happens after validation, so you can be sure that the values copied to your bean's properties are valid (at least at the form-field level; they may still be invalid at the business-rule level).

Phase 5: Invoke application

At the fifth phase of the lifecycle -- invoke application -- the JSF controller invokes the application to handle Form submissions. The component values will have been converted, validated, and applied to the model objects, so you can now use them to execute the application's business logic.

At this phase, you also get to specify the next logical view for a given sequence or number of possible sequences. You do this by defining a specific outcome for a successful form submission and returning that outcome. For example: on successful outcome, move the user to the next page. For this navigation to work, you will have to create a mapping to the successful outcome as a navigation rule in the faces-config.xml file. Once the navigation occurs, you move to the final phase of the lifecycle.

Phase 6: Render response

In the sixth phase of the lifecycle -- render response -- you display the view with all of its components in their current state.

Figure 2 is an object state diagram of the six phases of the JSF lifecycle, including validation and event handling.


Figure 4 The six-phase progression of the JSF lifecycle
Object state diagram of JSF lifecycle

A simple JSF application

A JSF application is just like any other Java Web application. It runs in a servlet

container, and it typically contains:

    • JSP pages
    • Event listeners
    • Java Beans that hold data and application-specific functionality
    • Server-side classes, such as database access beans

In addition to these common items, a JSF application also has:

  • A custom tag library for rendering UI components on a page. This is called the component tag library, and it is provided by the JSF implementation. The component tag library eliminates the need to hardcode UI components in any specific markup language, such as HTML. This results in completely reusable UI components.
  • A custom tag library for representing event handlers, validators and other actions. This is called the core tag library, and it is provided by the JSF implementation. The core tag library makes it easy to register events, validators and actions on the components.
  • UI components represented as stateful objects on the server.
  • Backing beans, which define properties and functions for UI components.
  • Validators, converters, event listeners and event handlers.
  • An application configuration resource file for configuring application resources.

Example: Product Display Application

A simple product display application that accesses a list of plants from a supplier backend. When selecting a plant from the list, you will be directed to one of three pages:

  • An error page if a product is not carried at all
  • A backordered product page that might display information on dealing with that issue or
  • A product detail page for items in stock and ready for ordering

The following link gives the steps to be followed in creating the example.

http://www.ibm.com/developerworks/rational/library/04/r-3219/

A simple JSF Portlet Application

The JSF portlet runtime is the component that makes possible to run JSF

applications as portlets in WebSphere Portal. The JSF portlet runtime is found in

a different jar file for each portlet API:

  • For the JSR 168 API, the jar file is jsf-portlet.jar.
  • For the IBM Portlet API, the jar file is jsf-wp.jar.

Besides this, the application makes use of portlet.xml, in addition to faces-config.xml and web.xml

Example: The calculator application

The first application to be created is a simple calculator. A JavaBean named

CalculatorBean is included to provide the basic mathematical operations on two

integer (long) numbers.

This bean has five properties:

_ Operand 1

_ Operand 2

_ Operation

_ Result

_ Error message

The bean also has associated getter and setter methods for all of its properties.

In addition, the calculate() method calculates the result of one of the following

operations:

_ Add

_ Subtract

_ Multiply

_ Divide

The result is stored in the first number (operand 1) for subsequent operations. If

a division does not result in an integer, an exception is thrown. Finally, a

toString() method displays the numbers and the operation.

The following is the link:

http://www.redbooks.ibm.com/Redbooks.nsf/RedbookAbstracts/sg246449.html

Here you need to download the PDF file.

Chapter 17 gives the steps to be followed in creating the application

References

http://www.devshed.com/c/a/Java/Introduction-to-JavaServer-Faces-1/

http://www.ibm.com/developerworks/library/j-jsf2/

Click here to View more...