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

Tuesday, September 20, 2016

How to get size of a java collection in xhtml

Basically there are 2 ways to get the size of a collection / list in xhtml.
1. jstl function
#{ fn:length(myList) }
2. call the size() function directly
#{ myList.size() }

Done!!

Monday, February 22, 2016

How to override JSF library in JBoss

In normal scenario, JBoss is bundled with JSF libraries.
But it might be older and stable version of JSF.

 Due to more features enhancement, bug fixes. We might want to use a more latest version of JSF for our application.
1 way is to upgrade the entire JBoss AS, but this is risky to all the existing applications that are running on the same JBoss AS.

to avoid unexpected issues to existing applications. we can proceed to upgrade the JSF libraries on the new JSF applications only.
We just need to bundled the latest JSF libraris in the same application, and add the following context-param into the web.xml.

<context-param>
    <param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name>
    <param-value>true</param-value>
</context-param>


Done!!

Thursday, January 28, 2016

Throw ValidatorException in JSF Validator

When throwing exception from a validator,
remember to throw ValidatorException instead of FacesException,
else the message component might be not able to display the correct validation message.

public void validAbc(FacesContext context, UIComponent component, Object value) {

   // some validation logic
  if(value.equals("abc")) {
    // proceed 
  } else {
    throw  new ValidatorException(new FacesMessage(
        FacesMessage.SEVERITY.ERROR, null, "validation error message"));
  }
}



Done!!

Tuesday, May 5, 2015

Loop every components in a ViewRoot recursively

1. Writing the recursive method.
private void loopComponentsRecursively(List<UIComponent> childrenList) {
  for(UIComponent component : childrenList) {
   if(component.getChildCount() > 0) {
    loopComponentsRecursively(component.getChildren());
   } else {
    // no more children for this component
    System.out.println("child: " + component.getId() + "  " + component.getClientId());
   }
  }
}

2. Invoking the recursive method
// some code
loopComponentsRecursively(viewRoot.getChildren());
//some other code


Done!!

Wednesday, July 30, 2014

How to pass parameters through URL in JSF

To pass parameters through URL in a web application, is to append the parameters into the base URL.

eg, www.google.com?parameter1=value1&parameter2=value2&parameter3=value3.

in JSF, it is nice to pass only 1 parameter through the URL.
When more than 1 parameter pass through the URL, an exception will happen.
Whenever "&" symbol appears in the URL, the exception will happen.

to resolve this problem, what we need to do is to encode the "&" symbol or manually append with the encoded value "&amp;"

eg, www.google.com?parameter1=value1&amp;parameter2=value2&amp;parameter3=value3.


Done!!

Monday, January 27, 2014

Loading Velocity template in JSF

When loading Velocity template with the default setting.
The following exception might be hit
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource

Even I used the Class Resource Loader, still hitting the same exception.

The exception solved when used File Resource Loader together with the system Real Path.
String myTemplatePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/WEB-INF/mytemplatepath");

Properties p = new Properties();
p.setProperty( "file.resource.loader.path", myTemplatePath);
Velocity.init(p);

Template template = Velocity.getTemplate( "mytemplate1.vm" );

p/s: assuming all .vm files are kept under <webapp>/WEB-INF/mytemplatepath folder.

Done!!

Thursday, November 7, 2013

How to get HttpServletRequest and HttpServletResponse from a JSF context

// Servlet request from JSF context
HttpServletRequest request = FacesContext.getCurrentInstance()
.getExternalContext().getRequest();

// Servlet response from JSF context
HttpServletResponse response = FacesContext.getCurrentInstance()
.getExternalContext().getResponse();

Saturday, September 28, 2013

Creating hyperlink with JSF components

normally JSF components accept an outcome from navigation case to generate hyperlink.
eg,
<h:link value="my link" outcome="MY_OUTCOME" />

<h:commandButton value="my button" action="MY_OUTCOME" />

<h:outputLink value="MY_OUTCOME">my link</h:outputLink />

But hyperlink generated with JSF outcome is only within the same application.
That's mean hyperlink generated with JSF components are unable to navigate to other sites. eg, google.com.

This problem could be resolved by <h:outputLink /> where the value attribute also accepts an URL.
eg.
<h:outputLink value="www.google.com">
    <h:outputText value="Google" />
    <f:param name="param1" value="value1" />
    <f:param name="param2" value="value2" />
</h:outputLink>

With the above codes, the <h:outputLink /> component able to generate hyperlink to www.google.com.

<f:param /> is optional, required only when passing parameters
eg.
www.google.com?param1=value1&param2=value2


Done!!

Thursday, September 19, 2013

Currency formatting with <f:convertNumber />

due to internationalization, the system should system the currency based on users' chosen currency or locale.
eg,
12345678.36 in US display as 12,345,678.36
12345678.36 in Danish (Denmark) display as 12.345.678,36
12345678.36 in German (Switzerland) display as 12'345'678.36

this could be easily handled by <f:convertNumber />, otherwise we might need to write a custom converter to handle this.

with <f:convertNumber />, we just need to pass in the system locale for the conversion.
<h:outputText id="balance" value="#{user.balance}">
    <f:convertNumber type="currency" locale="#{facesContext.viewRoot.locale}" />
</h:outputText>
with the above code, system will dynamically format the text value with system provided locale.

Saturday, August 17, 2013

How to display meaningful element name when exception

During form validation in JSF, by default exception(s) thrown will display the element's client id. 

But that is meaningless to the system users, because the client id is not tally with the corresponding element label. 

Thursday, June 6, 2013

Authorization in JSF with Facelets View Handler

According to wikipedia, authorization is the function of specifying access rights to resources.
Authorization is important to protect sensitive against different users.

The simplest way is to provide the access right to the targeted fields/components directly
for readOnly access,
<h:outputText id="authorizedId" value="#{bean.authorizedValue}" readonly="#{bean.authorizedReadonly}" />

for viewable access,
<h:outputText id="authorizedId" value="#{bean.authorizedValue}" disabled="#{bean.authorizedDisabled}" />

but the above solution is NOT feasible if there are many pages and fields/components to be authorized;
NOT flexible, if there are access right changes, re-coding is required.

Another feasible way is through FaceletsViewHandler.
In JSF with Facelets view handling, we can actually place all the authorization controls to the FaceletsViewHandler as the control central.

Wednesday, May 15, 2013

Simple number validation in JSF

There are many ready validator in JSF, eg. <f:validateLongRange />, <f:validateDoubleRange />, <f:validateRegex />, etc.
for more information about JSF validator, please refer here.

to validate number value, we can use the ready made JSF validator, that is <f:validateLongRange /> and <f:validateDoubleRange />

Sample code:
managedBean
private String longValue;
// getter & setter for longValue

private String doubleValue;
// getter & setter for doubleValue;

Thursday, May 9, 2013

How to create custom taglib descriptor in a JSF project

A taglib descriptor in JSF is a taglib.xml.
Name the taglib descriptor always start with a word and follow by "taglib.xml", eg. kian.taglib.xml
taglib descriptor allowed us to define our custom namespace, convertor, validator, composite component, and facelets function.
more details about taglib descriptor could be found here.

Thursday, April 11, 2013

How to create Credit Card Validator with Facelets

This post shows how to build a custom JSF regex validator to validate Credit Card number with Facelets.

There are different types of Credit Cards, the regex used to validate different types of Credit Card are vary with the types of Credit Card.
Visa ^4[0-9]{12}(?:[0-9]{3})?$
Master Card ^5[1-5][0-9]{14}$
American Express ^3[47][0-9]{13}$
Diners Club ^3(?:0[0-5]|[68][0-9])[0-9]{11}$

For more information about Credit Card Regex, please refer here.
so now let's start to build the Credit Card validator.

Tuesday, April 9, 2013

Easy JSF Email validator with Facelets

This post shows how to build a custom JSF regex validator to validate email address with Facelets.
Building email validator with Facelets is very easy if compare to building email validator with JSF component classes.

Steps:
1. create the validateEmail.xhtml in folder <WebContent>/views/validator
    Regex here could be changed to any desired format.

<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
    <f:validateRegex
        pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />

</ui:composition>

Saturday, February 2, 2013

Dynamic Include

Dynamic include is a technique to programmatically include or toggle content into predefined position of a page. It can also uses to create wizard like application by toggle the contents of the wizard.

Benefits of dynamic include
- save bandwidth
- reduce page size
- reduce server memory with smaller component tree
- reduce page loading time

Disadvantages of dynamic include
- increase complexity

Example
- How to create layout with dynamic include
- dynamic include in Richfaces tabPanel
- How to create wizard with dynamic include in JSF2
- Dynamic include with richfaces popupPanel

LinkWithin

Related Posts Plugin for WordPress, Blogger...