Saturday Aug 23

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

JSF and SEO

Last Updated on Thursday, 26 May 2011 15:50 Thursday, 26 May 2011 15:43
Attention: open in a new window. PDFPrintE-mail
AddThis Social Bookmark Button

Introduction

Url rewriting is not reserved to PHP solutions. JSF has now a library able to provide SEO features like :  

  • URL Rewriting — Replace ugly URLs: “/faces/page.jsf” with pretty, SEO-friendly, human URLS: “/optimized/page/”; The client browser never sees your original URLs, even in the source-HTML 
  • Dynamic view IDs — Now with dynamic view ID mapping for URLs (through El method expressions,) you can show different views based on run-time conditions, effectively de-coupling the URL from the JSF view. 
  • Page-load actions — Call one or more action-methods, at one or more phases, before rendering a view. 
  • Managed parameter parsing — HTTP parameters parsed from URLs are stored in managed beans, simply get a reference to your parameter bean for easy access from other Java classes. 
  • Navigation by ID — Define your page IDs in one place, reference them easily in action-methods and components, using standard JSF navigation techniques. 
  • Integrated validation — For URL and query-parameters, able to re-use existing JSF validator objects. 
  • Easy to configure — Requires absolutely minimal configuration; may be enabled using XML or annotations.

Prettyfaces is that library.

PrettyFaces

PrettyFaces is an OpenSource extension for Servlet, Java EE, and JSF, which enables creation of bookmarkable, REST-ful, "pretty" URLs. PrettyFaces solves several problems elegantly, such as: custom URL-rewriting, page-load actions, seamless integration with JSF navigation and links, dynamic view-id assignment, managed parameter parsing, and configuration-free compatibility with other JSF frameworks.

Maven dependencies configuration 

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

Maven plugin configuration

<!-- For Servlet/Java EE and JSF 2.0 -->
<dependency>
    <groupId>com.ocpsoft</groupId>
    <artifactId>prettyfaces-jsf2</artifactId>
    <version>3.2.0</version>
</dependency>

 
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 Monday, 26 September 2011 09:43
PDFPrintE-mail
Monday, 26 September 2011 08:55
AddThis Social Bookmark Button

JSF 2 Bean Validation (JSR 303)

Bean Validation with JSR 303 

A common issue when receiving data either electronically or from user input is verifying the integrity of the data. This work is repetitive and becomes even more complicated when different sets of validation rules need to be applied to the same set of data based on locale. Error messages may also vary by locale. The JSR 303 addresses some of these issues to speed development and maintenance of validation rules.

V

alidating data is a common task that occurs throughout an application, from the presentation layer to the persistence layer. Often the same validation logic is implemented in each layer, proving to be time consuming and errorprone. To avoid duplication of these validations in each layer, developers often bundle validation logic directly into the domain model, cluttering domain classes with validation code that is, in fact, metadata about the class itself.

The JSR 303 defines a metadata model and API for JavaBean validation. The default metadata source is annotations, with the ability to override and extend the meta-data through the use of XML validation descriptors.

The validation API developed by this JSR is not intended for use in any one tier or programming model. It is specifically not tied to either the web tier or the persistence tier, and is available for both server-side application programming, as well as rich client Swing application developers. This API is seen as a general extension to the JavaBeans object model, and as such is expected to be used as a core component in other specifications. Ease of use and flexibility have influenced the design of this specification.

Source :  jsr 303 specifications

You can download the specifications on the JCP site 

JSR 303 implementations

Provider Name Version Download
Hibernate  hibernate-validator (API)

4.0.2.GA

Donwload binary 

Code Google GWT-Vadliation

1.1.0-R88

Download binary
Code Google Wicket-jsr303-Validators

Download binary

What is not 

  • JSR 303 is not designed for Cross validation

JSF 2 Expression Language Tips and Tricks

Last Updated on Tuesday, 05 February 2013 10:48 Thursday, 24 January 2013 17:58
Attention: open in a new window. PDFPrintE-mail
AddThis Social Bookmark Button

Java Server Faces 2.0 Expression Language Tips and Tricks

Java Server Faces 2 Expression Language Tips and Tricks

Put the View id in the title only in development

JSF 2.0 has introduced a new feature called project stage. The project stage define the role of the current deployment. You can define this parameter in your Web.xml configuration file. Sometimes during the development you need to know which source file is behind the current page but you want to display this debugging information only in the development stage. To achieve this target you can use the following snippet:

Display page view id in development stage using JSF 2.0

        <title>Java tutorial
            <ui:fragment rendered="#{initParam['javax.faces.PROJECT_STAGE'] eq 'Development'}">
                 <h:outputText value="[#{view.viewId}]"/>
             </ui:fragment>
        </title>

Display the current page View Id or URI 

The viewId is a context-relative path starting with a slash character indicating the location of the source file

jsf_source

<h:outputText value="#{view.viewId}"/>

The result should display something like : 

/protected/myPage.xhtml

To display the URI of your page, you can use the following snippet

jsf_source

<h:outputText value="#{request.requestURI}"/>

The result should display something like : 

/protected/myPage.jsf

Resource Handler

If you want to get access to your resource handler your can use the following snippet

<h:outputText value="#{resource}"/>

It can be used to display debugging information. You can ask if a library exists :

<h:outputText value="Is my YAML css add-ons existings"/>
<h:outputText value="#{resource.libraryExists('css/yaml/add-ons/microformats')}"/>

If this examples i'm checking if the YAML Microformats add-ons is present.

If you have a custom resource handler.It has been defined in your faces-config.xml file with the following xml definition :

<faces-config>
   ...
   <application>
      <resource-handler>com.ubiteck.MyResourceHandlerWrapperImpl</resource-handler>
   </application>
</faces-config>

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

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’).

Java Tutorial on Facebook