Tag Archives: jsf

Insert Javascript code in JSF page

jsf_js
Usually you may need to insert a couple of JavaScript in your JSF page markup.
The following advice helps you do it right:

 <ui:composition ...>
    
    <ui:define name="body">
        
        <!-- your code -->
        
        <h:outputScript target="body">
            <![CDATA[
                alert("It works!");
            ]]>
        </h:outputScript>
        
        <!-- your code -->
        
    </ui:define>
    
</ui:composition>

So, as you see in JSF we use h:outputScript tag with CDATA inside to workaround issues like “The content of elements must consist of well-formed character data or markup” for valid XHTML.

Thanx to http://stackoverflow.com/a/4338816

JSF convertDateTime timeZone error fix

To show corrent date JSF with convertDateTime you can use next:

<context-param> 
  <param-name>
    javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE
  </param-name> 
  <param-value>
    true
  </param-value> 
</context-param>

So, in page:

<h:outputText value="#{Bean.date}">
  <f:convertDateTime pattern="HH:mm:ss"/>
</h:outputText>

Thanx to http://stackoverflow.com/a/7491706 !

Using binding in JSF

jsflife
You may heard about binding term in JSF. But it can be used?
Binding can be involved in validation procedure.

1. Add form to JSF page:

<h:form>
    <h:inputText id="email" 
        value="#{SomeBaen.emailValue}" 
        binding="#{SomeBaen.emailComponent}" />
    <h:message for="email" />

    <h:commandButton value="Check" action="#{SomeBaen.doCheck}" />
</h:form>

2. Create bean:

public class SomeBean implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private String emailValue;
    private UIComponent emailComponent;
    
    public String doCheck() {
        if (isValid(emailValue)) {
            return "ok";
        }
        
        // set invalid message
        FacesMessage message = new FacesMessage("Invalid email");
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(emailComponent.getClientId(context), message);
        
        return null;
    }
    
    public void setEmailValue(String emailValue) {
        this.emailValue = emailValue;
    }
    
    public String getEmailValue() {
        return emailValue;
    }
    
    public void setEmailComponent(UIComponent emailComponent) {
        this.emailComponent = emailComponent;
    }
    
    public UIComponent getEmailComponent() {
        return emailComponent;
    }
}

So, if validation failed you’ll see a message near inputText control.
Also example http://stackoverflow.com/a/321722

Primefaces ajax update on rendered attribute

rendered
If you are using rendered attribute on some component and want to update it on ajax request, you be noticed error.
So, that is normal because if rendered=”false” – this component will not be added to DOM tree.
That’s why it cannot be found on update callback.

For more info see
https://weblogs.java.net/blog/mriem/archive/2014/06/03/jsf-tip-62-understanding-renderedfalse.

To fix the problem wrap component into another container and make update on it.
For ex.

<p:outputPanel id="containerToUpdate">
    <p:panel rendered="#{SomeBean.isOk}">
        <!-- your code here -->
    </p:panel>
<p:outputPanel>

<p:commandButton update="containerToUpdate"/>

Thanx to http://stackoverflow.com/a/4525710.

Read version of package from META-INF in Java JSF Bean

vers
Often you need to show the software version in JSF page.
How to make it as follows:

1. Create JSF Bean

public class PropertiesBean implements Serializable {

    private static final long serialVersionUID = 8607941655014578684L;

    private static final String METAINF_LOCATION = "META-INF/MANIFEST.MF";
    private static final String VERSION_PREFIX = "Implementation-Version: ";
    private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+\\.\\d+\\.\\d+)");
    
    public String getVersion() {
        try {
            InputStream is = null;
            Scanner scanner = null;
            try {
                is = this.getClass().getClassLoader().getResourceAsStream(METAINF_LOCATION);
                scanner = new Scanner(is);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith(VERSION_PREFIX)) {
                        Matcher matcher = VERSION_PATTERN.matcher(line);
                        if (matcher.find()) {
                            String group = matcher.group();
                            return group;
                        }
                    }
                }
            } finally {
                if (scanner != null) {
                    scanner.close();
                }
                if (is != null) {
                    is.close();
                }
            }
        } catch (Exception e) {
            // TODO: log error!
        }
        return null;
    }
}

2. Register bean in faces-config.xml

    <managed-bean>
        <managed-bean-name>PropertiesBean</managed-bean-name>
        <managed-bean-class>com.someproject.presentation.PropertiesBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>

3. Use it on JSF page:

<h:outputText value="[v#{PropertiesBean.version}]" rendered="#{PropertiesBean.version != null}" />

Profit!

See also, http://stackoverflow.com/a/4782124

Dealing with f:setPropertyActionListener and actionListener in JSF

setactlist
One important thing about f:setPropertyActionListener tag.
ActionListeners will executes in order they defined!

For ex. see next code.
On page:

 <p:commandLink actionListener="#{SomeBean.onSomeAction}" ajax="true">
    <f:setPropertyActionListener 
        target="#{SomeBean.someProperty}" value="SOME_NEW_VALUE !!!" />
    <h:outputText value="Here is some text..." />
</p:commandLink>

JSF Bean:

public class SomeBean implements Serializable {
    private String someProperty;

    public void onSomeAction(ActionEvent event) {
        System.out.println("SomeBean.onSomeAction() fired!");
    }

	public String getSomeProperty() {
        return someProperty;
    }

    public void setSelectedProperty(String someProperty) {
	    System.out.println("SomeBean.setSomeProperty() fired!");
        this.someProperty = someProperty;
    }
}

So, be aware of situation when your property will set after command action listener fired.

The output:

  SomeBean.onSomeAction() fired!
  SomeBean.setSomeProperty() fired!

To solve the issue, you have to use action instead of actionListener.
That’s all.

Also, see http://stackoverflow.com/a/14160010

Passing values from Page to Bean in JSF

passvalue
There are three ways to pass values from page to JSF ManagedBean:

  1. Passing value with f:param tag – using action attribute
  2. Passing value with f:attribute tag – using actionListener attribute
  3. Passing value with f:setPropertyActionListener tag – no need for additional dealing, value allplies directly to bean property!

 

Here is an example JSF project:

File web.xml:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>bootstrap</param-value>
    </context-param>
</web-app>

File faces-config.xml:

 <?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

    <managed-bean>
        <managed-bean-name>PassParamBean</managed-bean-name>
        <managed-bean-class>passvalue.PassParamBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>

    <navigation-rule>
        <navigation-case>
            <from-outcome>pass_value</from-outcome>
            <to-view-id>/pass_value.xhtml</to-view-id>
            <redirect />
        </navigation-case>
    </navigation-rule>

</faces-config>

File pass_value.xhtml:

 <!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:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>Passing Values</title>
</h:head>
<h:body>

<h1>Case 1 - f:param</h1>
<h:form>
    <p><h:outputText value="#{PassParamBean.someParam}" /></p>
    <p:commandButton value="Pass Param" action="#{PassParamBean.passParam}">
        <f:param name="someParamHolder" value="THIS is VALUE_OF_PARAM !!!" />
    </p:commandButton>

    <p>&nbsp;</p>

    <h1>Case 2 - f:attribute</h1>
    <p><h:outputText id="someAttributeId" value="#{PassParamBean.someAttribute}" /></p>
    <p:commandButton value="Pass Attribute" actionListener="#{PassParamBean.passAttributeListener}"
        ajax="true" update="someAttributeId">
        <f:attribute name="someAttributeHolder" value="THIS is VALUE_OF_ATTRIBUTE !!!" />
    </p:commandButton>

    <p>&nbsp;</p>

    <h1>Case 3 - f:setPropertyActionListener</h1>
    <p><h:outputText id="somePropertyId" value="#{PassParamBean.someProperty}" /></p>
    <p:commandButton value="Pass Property"
       ajax="true" update="somePropertyId">
       <f:setPropertyActionListener target="#{PassParamBean.someProperty}" 
           value="THIS is VALUE_OF_PROPERTY !!!" />
    </p:commandButton>

    <p>&nbsp;</p>

    <p:commandButton value="Reset" action="#{PassParamBean.reset}" />
</h:form>

</h:body>
</html>

File PassParamBean.java:

 package passvalue;

import java.io.Serializable;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

public class PassParamBean implements Serializable {

    private static final long serialVersionUID = 7980827794690701951L;

    private static final String DEFAULT_OUTCOME = "pass_value";

    private String someParam;
    private String someAttribute;
    private String someProperty;

    public String reset() {
        someParam = null;
        someAttribute = null;
        someProperty = null;

        return DEFAULT_OUTCOME;
    }

    public String passParam() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        Map<String, String> params = externalContext.getRequestParameterMap();
        someParam = params.get("someParamHolder");

        return DEFAULT_OUTCOME;
    }

    public void passAttributeListener(ActionEvent event) {
        UIComponent component = event.getComponent();
        Map<String, Object> attrs = component.getAttributes();
        someAttribute = (String) attrs.get("someAttributeHolder");
    }

    public String getSomeParam() {
        return someParam;
    }

    public void setSomeParam(String someParam) {
        this.someParam = someParam;
    }

    public String getSomeAttribute() {
        return someAttribute;
    }

    public void setSomeAttribute(String someAttribute) {
        this.someAttribute = someAttribute;
    }

    public String getSomeProperty() {
        return someProperty;
    }

    public void setSomeProperty(String someProperty) {
        this.someProperty = someProperty;
    }
}

Also, you can download whole project here: passValues.