Showing posts with label JSF2. Show all posts
Showing posts with label JSF2. Show all posts

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, December 29, 2015

How to parameterized label from resource bundle

Assuming we have a of labels to be displayed by type.
label.type.a = This is label A label.type.b = This is label B label.type.c = This is label C label.type.d = This is label D

To display the label by type in xhtml, the simplest way it to use a rendered attribute
<h:outputLabel value="#{lbl['label.type.a']}" rendered="#{myType == 'A'}" /> <h:outputLabel value="#{lbl['label.type.b']}" rendered="#{myType == 'B'}" /> <h:outputLabel value="#{lbl['label.type.c']}" rendered="#{myType == 'C'}" /> <h:outputLabel value="#{lbl['label.type.d']}" rendered="#{myType == 'D'}" />

Instead of using the above sample, I would prefer to use two lines to achieve the same effect.
especially when the list of type are long. 
<ui:param name="typeLabel" value="label.type.#{myType}" /> <h:outputLabel value="#{lbl['typeLabel']}" />


Done!!

Monday, June 29, 2015

How to set common styleClass when component is required, readonly or disabled

This is to show how to highlight input components globally when it is either required, readonly, or disabled.

1. Create a class that is extending the javax.faces.application.ViewHandlerWrapper.
public class MyViewHandlerWrapper extends ViewHandlerWrapper {

}

2. Overrider the renderView method.
@Override
public void renderView(FacesContext fc, UIViewRoot view) throws IOException, FacesException {

  super.renderView(fc, view);

}

3. create a private method to find input components recursively and highlight them based on the required, readonly and disabled attribute.

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!!

Tuesday, February 10, 2015

How to update JSF library in JBoss

1. Download the expected version of JSF library.
jsf-api
https://repository.jboss.org/nexus/content/groups/public/org/jboss/spec/javax/faces/jboss-jsf-api_2.1_spec/

jsf-impl
https://repository.jboss.org/nexus/content/groups/public-jboss/com/sun/faces/jsf-impl/

2. Copy the newly downloaded JSF jar into the following folder
jsf-api
<JBoss_AS>/modules/javax/faces/api/main
<JBoss_EAP>/modules/system/layers/base/javax/faces/api/main

jsf-impl
<JBoss_AS>/modules/com/sun/jsf-impl/main
<JBoss_EAP>/modules/system/layers/base/com/sun/jsf-impl/main

3. Modify module.xml with the new jar file name.
jsf-api
    <resources>
        <resource-root path="jboss-jsf-api_2.1_spec-2.1.19.1.Final-redhat-1.jar"/>
    </resources>
jsf-impl
    <resources>
        <resource-root path="jsf-impl-2.1.19-redhat-2.jar"/>
    </resources>

4. Restart JBoss


Done!!


Monday, August 4, 2014

javax.faces.project_stage

There is a new feature introduced in JSF2.x,
Which is the javax.faces.PROJECT_STAGE in the web.xml.

When creating a new JSF2.x project, the default value is “Development”.
When going into Production environment, the value should be changed to “Production”
To reduce logs, and avoid re-download of static resources (js, css, images, etc), and all the static resources will be cached in the client machine.

Besides, if this parameter remove from web.xml, the default value is "Production"

reference,
https://blogs.oracle.com/rlubke/entry/jsf_2_0_new_feature2
https://weblogs.java.net/blog/driscoll/archive/2009/09/28/jsf-20-reminder-project-stage


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!!

Saturday, May 17, 2014

How to integrate SlidesJS into JSF2

SlidesJS is an image slider that is nice and easy to implement.
To implement SlidesJS into JSF2.x application, just need to download the required files and follow the steps below.

1. copy all the required files into resources folder.

Sunday, March 23, 2014

JSTL namespace in JSF2.x

Remember to use "http://java.sun.com/jsp/jstl/core" instead of "http://java.sun.com/jstl/core" in JSF2.x

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:c="http://java.sun.com/jsp/jstl/core">    

    ................................

</ui:composition>


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!!

Friday, January 10, 2014

Getting Liferay Signed in user in XHTML

Check the session is signed in in XHTML
#{facesContext.externalContext.requestMap['THEME_DISPLAY'].signedIn}

Get the signed in user in XHTML
#{facesContext.externalContext.requestMap['THEME_DISPLAY'].user}

Get the signed in user's properties in XHTML
#{facesContext.externalContext.requestMap['THEME_DISPLAY'].fullName}

#{facesContext.externalContext.requestMap['THEME_DISPLAY'].lastLoginDate}

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, November 2, 2013

How to invoke action before a view is rendered

There is a new component since JSF2.0 & JSF2.1 that can invoke a listener at the defined type of JSF event.
If is <f:event />

To invoke action/listener before a view is rendered,
The type event to be used is preRenderView
and this event type is available since JSF2.1

eg,
<f:event type="preRenderView" listener="#{myBean.preRenderViewListener}" />

with the above sample code, #{myBean.preRenderViewListener} will be invoked before the view is rendered.

Monday, October 21, 2013

Accessing bean's property dynamically like a map

Assuming we have the following class
@ManagedBean(name="myBean")
public class MyBean {
    private String property1;
    private String property2;

    // getter and setting for property1, property2, ...
}

Normally we are accessing the properties in a bean from xhtml like syntax below.
#{myBean.property1}

But, recently found that we can actually accessing the properties of a bean like accessing a map.
#{myBean['property1']}

#{myBean['property2']}

in normally circumstances, it is nothing special from the traditional way.
But it is relatively useful if we want to dynamically access the properties in a bean.


Done!!

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!!

Wednesday, September 25, 2013

How to retrieve logged in user model in JSF2 Portlet

Retrieving logged in user is essential in every system, especially for logging purpose or authentication and authorization.

Steps to retrieve Liferay Logged in user in JSF portlet:
1. get the PortletRequest from JSF context
    PortletRequest portletRequest = (PortletRequest) FacesContext                                                                 .getCurrentInstance()
                                .getExternalContext().getRequest();

2. get the logged in user id
    String userId = portletRequest .getRemoteUser();

3. get the user model with Liferay API
    User user = UserServiceUtil.getUserById(Long.valueOf(userId));


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. 

LinkWithin

Related Posts Plugin for WordPress, Blogger...