Monday Apr 21

Key Concepts

Java Server Faces 2.0

AddThis Social Bookmark Button

JSF2

JavaServer Faces (JSF Faces) is a standardized specification for building User Interfaces (UI) for server-side applications. Before JavaServer Faces, developers who built web applications often relied on building HTML user interface components with servlets or JavaServer Pages (JSP pages).

JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client.

JSF provides ease-of-use in the following ways:

  • Makes it easy to construct a UI from a set of reusable UI components 
  • Simplifies migration of application data to and from the UI 
  • Helps manage UI state across server requests 
  • Provides a simple model for wiring client-generated events to server-side application code 
  • Allows custom UI components to be easily built and re-used

Foundational new features in JSF 2.0

These features were developed by the expert group specifically to enable other features in JSF 2.0

  • System Events provides a very fined-grained level of detail to observe and act upon the JSF runtime as it processes requests. It is described in detail in Chapter 9.
  • Resources feature allows the JSF runtime to serve up static resources, such as style sheets, scripts, and images, in addition to the previously available capability to serve up JSF pages. 
  • Facelets began as an open-source JSF extension that provided first-class templating and easy integration between markup and the JSF API. This made the experience of writing JSF pages easier and more maintainable. Facelets is now fully included in the core JSF specification in version 2.0 

New Features in JSF 2

  • Ajax JSF 2 provides now a native support for Ajax. Ajax is an essential element of most production-quality Web applications currently in production. Ajax enables JSF views to communicate with the server directly from the browser without requiring a full-page refresh of the browser window.
  • Composite Components JSF 2 provides a simple way to implement custom components with composites. JSF 2 lets you implement user interfaces that are easy to modify and extend with two powerful features: templating and composite components

Last Updated on Tuesday, 17 May 2011 17:17
PDFPrintE-mail
Wednesday, 11 May 2011 06:48
AddThis Social Bookmark Button

Unified Expression Language 2.2 

EL-2.2 is part of JSR-245 MR2 (JSP-2.2) and therefore not included in Tomcat6 nor Jetty6. EL-2.2 is part of Tomcat7 and Jetty7, but with a few manual steps, you can use EL-2.2 even in current containers.

Add Unified expression language in your Java server faces project using Maven

Include the following snippet in the dependencies section of your project's pom.xml-file to get EL2 :

javax.el dependencies maven

<dependency>
    <groupId>javax.el</groupId>
    <artifactId>el-api</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <version>2.2</version>
</dependency>

Include the java.net repository project's pom.xml-file or in your settings.xml :

Unified expression language repository download location

<repository>
   <id>java-net</id>
   <url>http://download.java.net/maven/2/ </url>
</repository>  

Apache's EL 2.2 implementation

The above code uses Sun's EL 2.2 implementation from Glassfish. If you want to use Apache's implementation, you have to use the following dependencies from the Apache SNAPSHOT repository.

Include the following snippet in the <dependencies> section of your project's pom.xml-file:

Apache EL 2.2 Maven configuration

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-el-api</artifactId>
    <version>7.0.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jasper-el</artifactId>
    <version>7.0.0-SNAPSHOT</version>
</dependency>

web.xml settings

Include the following snippet in the <build><plugins> section of your project's pom.xml-file:

<context-param>
    <param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
    <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>

Tomcat 6 Configuration for EL 2.2

Tomcat6 has to be prepared, otherwise it will crash with a Exception on container startup:

1 ) Go to the tomcat home directory 

2) Remove tomcats el-api.jar from the classpath:

Tomcat6 el-api el-impl Expression Language

> mv ./lib/el-api.jar ./lib/el-api.jar.bak

3) Copy the EL-2.2 jars into ./lib (el-api-2.2.jar, el-impl-2.2.jar) 

4) Make sure that your WARs don't contain those 2 el jars!

 
Last Updated on Wednesday, 01 June 2011 18:32
PDFPrintE-mail
Thursday, 26 May 2011 10:04
AddThis Social Bookmark Button

Java Server Faces 2.0 Error Page
JSF 2 Error Page 

If no <error-page> elements are declared in the web application deployment descriptor, the runtime must provide a
default error page that contains the following information.

  • The stack trace of the Exception
  • The UIComponent tree at the time the ExceptionEvent was handled.
  • All scoped variables in request, view, session and application scope.
  • If the error happens during the execution of the view declaration language page (VDL)
  • The physical file being traversed at the time the Exception was thrown, such as /user.xhtml
  • The line number within that physical file at the time the Exception was thrown
  • Any available error message(s) from the VDL page, such as: "The prefix "ubiteck" for element "ubiteck:inputBox" is not bound."
  • The viewId at the time the ExceptionEvent was handled

Source : JSF specs 2.0

Last Updated on Tuesday, 29 May 2012 15:26
PDFPrintE-mail
Tuesday, 17 May 2011 17:32
AddThis Social Bookmark Button

Create a composite tag library 

The design of JSF 2.0 is influenced by the philosophy of convention over configuration, popularized by Ruby on Rails. To realize composite components, this philosophy is combined with the resource loading feature, described in Ryan Lubke’s blog JSF 2.0 New Feature Preview Series (Part 2.1): Resources.

The namespace short-name that prefixes a composite component tag, ubiteck:, has an entry in the element, that is, xmlns:ubiteck="http://java.sun.com/jsf/composite/ubiteck". The content after http://java.sun.com/jsf/composite/ in this case, ubiteck, is the library-name. The library-name and resource-name are used to create a Resource instance.

JSF 2.0 has a method that creates a UIComponent from a Resource. Due to these conventions, any .xhtml file in a resource library can be accessed as a composite component.

There are several ways to create a resource library. Here is one way to do it.

In your webapp directory, you should have a directory named resources. In this directory is a sub-directory named ubiteck. The name of the subdirectory (in this case, ubiteck) must correspond to the end part of the composite xmlns for the namespace short-name that prefixes the composite component tag. 

ConventionValue
Namespace for composite A Composite namespace should start with
http://java.sun.com/jsf/composite/<Name of your library>
Property access  

A property defined in the interface section should be accessed using 
#{cc.attrs.<name of your property>}

Structure content under
these resources directories

localePrefix/][libraryName/][libraryVersion/]resourceName[/resourceVersion]
items in [] are optional

associate a resource with a particular locale identifiter

If a developer wishes to 
leverage this feature, they must add a key/value pair like: 

  • javax.faces.resource.localePrefix=<localePrefix>

The default implementation will look for resources in two locations and in the following order:

  1. /resources this location represents resources in the webapp itself and if present, must be in the root of the web application 
  2. /META-INF/resources this location represents resources on the classpath

HTML Spacer composite component example

Let's imagine we want to create a spacer component. We will create a file called spacer.xhtml in the folder ../webapp/resources/ubiteck/

The spacer take support a width parameter to define  the length of the spacer. The default value if omiited is 10 pixels.  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:composite="http://java.sun.com/jsf/composite"
    xmlns:h="http://java.sun.com/jsf/html">

<head>
    <title>Spacer Ubiteck component</title>
</head>
    <!--
    *****************************
      Usage  :  
        <md:spacer width="50"/>
    *****************************
     -->
    <body>
        <composite:interface>
            <composite:attribute name="width" defaut="10" />
        </composite:interface>
        
        <composite:implementation>
            <h:graphicImage
                value="#{facesContext.externalContext.requestContextPath}/../images/common/spacer.gif"
                width="#{cc.attrs.width}" height="1" />
        </composite:implementation>
    </body>
</html> 

The graphic image is tag is more described at Tag Graphic Image  (JSF 2.0)

The component will be reachable defining the namespace for ubiteck and calling <ubiteck:spacer width="100"/> and passing the width parameter

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ubiteck="http://java.sun.com/jsf/composite/ubiteck">
<h:head>
    <title>Spacer Composite Components Test</title>
</h:head>
<h:body>
    Before spacer <ubiteck:spacer width="100"/> After Spacer        
</h:body>
</html>
<meta charset="utf-8" />

Migrate tag library from 1.x to 2.x

Find below a small table with correponding tags or expressions between JSF 1.x and JSF 2.x

TagsJSF 1.xJSF 2.x
A property attribute  myParam cc.attrs.myParam

Any child components or template text within the composite component
tag in the using page will be reparented into the composite component

<ui:insert/>

<composite:insertChildren/>

method param N/A
<composite:attribute 
name="<param name>"
method-signature="java.lang.String action()"/>
Bean + method 
JSTL Choose

<c:choose>

<c:when test="<condition>">

....

</c:choose> 

 ...rendered="<condition>"
JSTL If conditional

<c:if test="<condition>">

<f:verbatim rendered="<condition>">
...
</f:verbatim>

Last Updated on Tuesday, 28 June 2011 15:27
PDFPrintE-mail
Thursday, 26 May 2011 07:52
AddThis Social Bookmark Button

Expression Language release 2.2

Literal-expression

A literal-expression does not use the ${expr} or #{expr} constructs, and simply evaluates to the text of the expression, of type String. Upon evaluation, an expected type of something other than String can be provided. Sample literalexpressions are shown in the table below.

ExpressionExpected TypeResult
Hello World !  String Hello World ! 
true Boolean Boolean.TRUE

To generate literal values that include the character sequence "${" or “#{“, the developer can choose to use a composite expression as shown here:
  • ${'${'}exprA}
  • #{'#{'}exprB}The resulting values would then be the strings ${exprA} and #{exprB}.
Alternatively, the escape characters \$ and \# can be used to escape what would otherwise be treated as an eval-expression. Given the literal-expressions:
  • \${exprA}
  • \#{exprB}

The resulting values would again be the strings ${exprA} and #{exprB}. A literal-expression can be used anywhere a value expression can be used. A literalexpression can also be used as a method expression that returns a non-void return value. The standard EL coercion rules (see Section 1.18, “Type Conversion”) then apply if the return type of the method expression is not java.lang.String.

Composite expressions

The EL also supports composite expressions, where multiple EL expressions are grouped together. With composite expressions, eval-expressions are evaluated from left to right, coerced to Strings (according to the EL type conversion rules), and concatenated with any intervening literal-expressions.

For example, the composite expression “${firstName} ${lastName}” is composed of three EL expressions: eval-expression “${firstName}”, literalexpression “ “, and eval-expression “${lastName}”.

Once evaluated, the resulting String is then coerced to the expected type, according to the EL type conversion rules. A sample composite expression is shown below

ExpressionExpected TypeResult
Welcome
${customer.name} to
our site
 
String
Welcome John Doe to our
site.

${customer.name} evaluates to a String which is then concatenated with the
literal-expressions. No conversion necessary.
 

Expression language warning composite expression  It is illegal to mix ${} and #{} constructs in a composite expression.

Literals

There are literals for boolean, integer, floating point, string, and null in an evalexpression.

TypeDescription

String

With single and double quotes - " is escaped as \", ' is escaped as \', and \ is escaped as \\. Quotes only need to be escaped in a string value enclosed
in the same type of quote

Boolean

 

true and false

Integer

As defined by the IntegerLiteral construct :

IntegerLiteral ::= [‘0’-’9’]+

Float

As defined by the FloatingPointLiteral construct :

FloatingPointLiteral::= ([‘0’-’9’])+ ‘.’ ([‘0’-’9’])* Exponent?
| ‘.’ ([‘0’-’9’])+ Exponent?
| ([‘0’-’9’])+ Exponent?

Null null

Enums

The Unified EL supports Java SE 5 enumerated types. Coercion rules for dealing with enumerated types are included in the following section. Also, when referring to values that are instances of an enumerated type from within an EL expression, use the literal string value to cause coercion to happen via the below rules.

For example, Let’s say we have an enum called Suit that has members Heart, Diamond, Club, and Spade. Furthermore, let’s say we have a reference in the EL, mySuit, that is a Spade.

If you want to test for equality with the Spade enum, you would say ${mySuit == ’Spade’}. The type of the mySuit will trigger the invocation of Enum.valueOf(Suit.class, ’Spade’).

Last Updated on Monday, 04 March 2013 15:16
PDFPrintE-mail
Tuesday, 29 January 2013 16:10
AddThis Social Bookmark Button

JSF 2 redirection with Java Server Faces

External Site redirection with JSF

To redirect to an external site you need to get an external context using FaceContext then call the redirect method with the external website url

Java Server Faces external site redirection

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.redirect("htp://www.java-tutorial.ch");

Get the asbolute context path from your backing bean

To return your absolute context path in your backing you can use the following snippet. This method take into account the fact that you are using a "non standard" port by adding the port only if you are using a port different from the usual 80.

Return the absolute context path from your Backing bean

public String getAbsoluteContextPath(){
        HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        StringBuffer buffer = new StringBuffer();
        buffer.append(request.getScheme());  //http,https,...
        buffer.append("://");
        buffer.append(request.getServerName()); //localhost
        if (request.getServerPort() != 80){
            buffer.append(":"); //localhost
            buffer.append(request.getServerPort()); //8080
        }
        if (request.getContextPath() !=""){
            buffer.append("/");
            buffer.append(request.getContextPath());
        }
        else 
            buffer.append("/");
        return buffer.toString();
    }

If you have any remark or questions feel free to put a comment.If you enjoyed this tutorial and want to promote it don't hesitate to click on

Java Tutorial on Facebook