Archive for May, 2012

The JSF Mail Application

Posted: May 8, 2012 in OpenSource

http://www.lawrence.edu/fast/greggj/CMSC250/JSF/JSFMail.html

renferent

Posted: May 8, 2012 in Validate in jsf

http://byteco.de/2009/06/16/jsf-validations/

Introduction

Validators in JSF are nice. They, however, have its shortcomings. They will by default validate only one field at once. There is no standard way to attach one validator to multiple fields. Although there are some situations where you want this kind of functionality. For example validating the password confirmation field, validating the range of two numeric or date values (e.g. the one have to be lesser than the other), validating correctness of the three separate day, month and year fields, etcetera.

The cleanest solution would be to create a custom component which renders two or more components and use a specific validator for that, but that would involve more work. The easiest solution in this particular case is to attach the validator to the first component of the group (components are rendered, validated, converted and updated in the same order as you define them in the JSF view) and pass the other component(s) as unique f:attribute facet(s) along the first component. Then in the validator you can get the desired component(s) using UIComponent#getAttributes().

Back to top

Basic example

This example demonstrates a basic registration form with one username field and two password fields. The value of the second password field should equal to the value of the first password field before the action method may be invoked. The stuff is tested in a Java EE 5.0 environment with Tomcat 6.0 with Servlet 2.5, JSP 2.1 and JSF 1.2_07 (currently called Mojarra by the way!).

Here is the relevant JSF code. Note the binding=”#{confirm}” of the second password field. It binds the component to the view and makes it available elsewhere by #{confirm}. This is an instance of the UIInput class which has a getSubmittedValue() method to get the submitted value. Note the f:attribute of the first password field, its value should point to the component of the second password field #{confirm}. Also note that the second password field doesn’t have any value bound to the backing bean as this is unnecessary in this specific case.

<h:form id="register">
    <h:panelGrid columns="3">
        <h:outputLabel for="username" value="Username" />
        <h:inputText id="username" value="#{myBean.username}" required="true" />
        <h:message for="username" style="color: red;" />

        <h:outputLabel for="password" value="Password" />
        <h:inputSecret id="password" value="#{myBean.password}" required="true">
            <f:validator validatorId="passwordValidator" />
            <f:attribute name="confirm" value="#{confirm}" />
        </h:inputSecret>
        <h:message for="password" style="color: red;" />

        <h:outputLabel for="confirm" value="Confirm password" />
        <h:inputSecret id="confirm" binding="#{confirm}" required="true" />
        <h:message for="confirm" style="color: red;" />

        <h:panelGroup />
        <h:commandButton value="Register" action="#{myBean.register}" />
        <h:message for="register" style="color: green;" />
    </h:panelGrid>
</h:form>

And now the validator code:

package mypackage;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class PasswordValidator implements Validator {

    // Actions ------------------------------------------------------------------------------------

    public void validate(FacesContext context, UIComponent component, Object value)
        throws ValidatorException
    {
        // Cast the value of the entered password to String.
        String password = (String) value;

        // Obtain the component and submitted value of the confirm password component.
        UIInput confirmComponent = (UIInput) component.getAttributes().get("confirm");
        String confirm = confirmComponent.getSubmittedValue();

        // Check if they both are filled in.
        if (password == null || password.isEmpty() || confirm == null || confirm.isEmpty()) {
            return; // Let required="true" do its job.
        }

        // Compare the password with the confirm password.
        if (!password.equals(confirm)) {
            confirmComponent.setValid(false); // So that it's marked invalid.
            throw new ValidatorException(new FacesMessage("Passwords are not equal."));
        }

        // You can even validate the minimum password length here and throw accordingly.
        // Or, if you're smart, calculate the password strength and throw accordingly ;)
    }

}

The appropriate test backing bean look like:

package mypackage;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class MyBean {

    // Init ---------------------------------------------------------------------------------------

    private String username;
    private String password;

    // Actions ------------------------------------------------------------------------------------

    public void register() {

        // Just for debug. Don't do this in real! Hash the password, save to DB and forget it ;)
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);

        // Show succes message.
        FacesContext.getCurrentInstance().addMessage("register", new FacesMessage("Succes!"));
    }

    // Getters ------------------------------------------------------------------------------------

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    // Setters ------------------------------------------------------------------------------------

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

Finally the relevant part of the faces-config.xml:

    <validator>
        <validator-id>passwordValidator</validator-id>
        <validator-class>mypackage.PasswordValidator</validator-class>
    </validator>

    <managed-bean>
        <managed-bean-name>myBean</managed-bean-name>
        <managed-bean-class>mypackage.MyBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>

From : www.http://balusc.blogspot.com

Communication in jsf

Posted: May 8, 2012 in JSEE

This can be done in several ways, with f:setPropertyActionListener, f:attribute and f:param.

f:setPropertyActionListener: with the h:commandLink and h:commandButton tags you can trigger a method of the backing bean using the action or the actionListener attribute. As you cannot directly pass some method parameters from the JSF to the backing bean, the f:setPropertyActionListener tag might be very useful to dynamically set the bean properties which can be used as parameters. This works in JSF 1.2 or newer only. Here is an example:

 

<h:form>
    <h:commandLink value="Click here" action="#{myBean.action}">
        <f:setPropertyActionListener target="#{myBean.propertyName1}" value="propertyValue1" />
        <f:setPropertyActionListener target="#{myBean.propertyName2}" value="propertyValue2" />
    </h:commandLink>

    <h:commandButton value="Press here" action="#{myBean.action}">
        <f:setPropertyActionListener target="#{myBean.propertyName1}" value="propertyValue1" />
        <f:setPropertyActionListener target="#{myBean.propertyName2}" value="propertyValue2" />
    </h:commandButton>
</h:form>

This require at least a setter for propertyName1 and propertyName2 in the backing bean:

package mypackage;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String propertyName1;
    private String propertyName2;

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        System.out.println("propertyName1: " + propertyName1);
        System.out.println("propertyName2: " + propertyName2);
    }

    // Setters -----------------------------------------------------------------------------------

    public void setPropertyName1(String propertyName1) {
        this.propertyName1 = propertyName1;
    }

    public void setPropertyName2(String propertyName2) {
        this.propertyName2 = propertyName2;
    }

}

Now the properties propertyName1 and propertyName2 should contain the values propertyValue1 and propertyValue2 respectively.

f:attribute: with the h:commandLink and h:commandButton tags you can also trigger a method of the backing bean using the actionListener attribute. With this you can also use the f:attribute tag to dynamically pass the parameters. Here is an example:

<h:form>
    <h:commandLink value="Click here" actionListener="#{myBean.action}">
        <f:attribute name="attributeName1" value="attributeValue1" />
        <f:attribute name="attributeName2" value="attributeValue2" />
    </h:commandLink>

    <h:commandButton value="Press here" actionListener="#{myBean.action}">
        <f:attribute name="attributeName1" value="attributeValue1" />
        <f:attribute name="attributeName2" value="attributeValue2" />
    </h:commandButton>
</h:form>

Those attributes can be retrieved using getAttributes() of the parent UI component, which on its turn can be retrieved by the ActionEvent passed by the actionListener.

package mypackage;

import javax.faces.event.ActionEvent;

import net.balusc.util.FacesUtil;

public class MyBean {

    // Actions -----------------------------------------------------------------------------------

    public void action(ActionEvent event) {
        String attributeName1 = FacesUtil.getActionAttribute(event, "attributeName1");
        String attributeName2 = FacesUtil.getActionAttribute(event, "attributeName2");

        System.out.println("attributeName1: " + attributeName1);
        System.out.println("attributeName1: " + attributeName1);
    }

}
package net.balusc.util;

import javax.faces.event.ActionEvent;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static String getActionAttribute(ActionEvent event, String name) {
        return (String) event.getComponent().getAttributes().get(name);
    }

}

The variables attributeName1 and attributeName2 now should contain the values attributeValue1 and attributeValue2 respectively.

Take care that each attribute name should be unique and should not overwrite any default component attributes, like “id”, “name”, “value”, “binding”, “rendered”, etc.

f:param: another way to pass parameters to the backing bean is using the f:param tag. This works on h:commandLink and h:outputLink only. The h:outputLink example is described in the next chapter. Here is the h:commandLink:

 

<h:form>
    <h:commandLink value="Click here" action="#{myBean.action}">
        <f:param name="parameterName1" value="parameterValue1" />
        <f:param name="parameterName2" value="parameterValue2" />
    </h:commandLink>
</h:form>

Those parameters can be retrieved using getRequestParameterMap() of the FacesContext. With the following utility method you can use the f:param name to request the f:param value of any f:param parameter specified in the command block:

package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String parameterName1 = FacesUtil.getRequestParameter("parameterName1");
        String parameterName2 = FacesUtil.getRequestParameter("parameterName2");

        System.out.println("parameterName1: " + parameterName1);
        System.out.println("parameterName2: " + parameterName2);
    }

}
package net.balusc.util;

import javax.faces.context.FacesContext;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static String getRequestParameter(String name) {
        return (String) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get(name);
    }

}

The variables parameterName1 and parameterName2 now should contain the values parameterValue1 and parameterValue2 respectively.

Back to top

Passing GET parameters from JSF to backing beans

This can be done easily using the h:outputLink tag with f:param:

 

<h:outputLink value="mypage.jsf">
    <f:param name="parameterName1" value="parameterValue1" />
    <f:param name="parameterName2" value="parameterValue2" />
    <h:outputText value="Click here" />
</h:outputLink>

Define those parameters in the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>mypackage.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>parameterName1</property-name>
        <value>#{param.parameterName1}</value>
    </managed-property>
    <managed-property>
        <property-name>parameterName2</property-name>
        <value>#{param.parameterName2}</value>
    </managed-property>
</managed-bean>

And add those properties to the backing bean MyBean.java:

package mypackage;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String parameterName1;
    private String parameterName2;

    // Getters -----------------------------------------------------------------------------------

    public String getParameterName1() {
        return parameterName1;
    }

    public String getParameterName2() {
        return parameterName2;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setParameterName1(String parameterName1) {
        this.parameterName1 = parameterName1;
    }

    public void setParameterName2(String parameterName2) {
        this.parameterName2 = parameterName2;
    }

}

The #{param} is a predefinied variable referring to the request parameter map which also can be retrieved by FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(). Invoking a GET request using the following URL will set the parameter values automatically in the managed bean instance, thanks to the managed-property configuration in the faces-config.xml:
http://example.com/mypage.jsf?parameterName1=parameterValue1&parameterName2=parameterValue2

If you want to execute some action directly after setting of the managed properties, then add a method which you annotate using the @PostConstruct annotation.

    @PostConstruct
    public void doSomeAction() {
        // Do your thing here with parameterName1 and parameterName2!
    }

Which is only available as per JSF 1.2 however. If you’re still using JSF 1.1 or older, then consider adding ‘lazy executing’ to the setter (check if the current property is null and then execute some logic before assigning). This is the opposite of ‘lazy loading’ which can happen in the getter (check if the current property is null and then assign it before returning).

    public void setParameterName1(String parameterName1) {
        if (this.parameterName1 == null) {
            // This will only be executed if the property was null before.
            doSomeAction(parameterName1);
        }
        this.parameterName1 = parameterName1;
    }

    // Or, without passing the parameter (and let the action access the instance variable):

    public void setParameterName2(String parameterName2) {
        boolean wasNull = this.parameterName2 == null;
        this.parameterName2 = parameterName2;
        if (wasNull) {
            // This will only be executed if the property was null before.
            doSomeAction();
        }
    }
Back to top

Passing component attributes from JSF to backing beans

The f:attribute tag can also be used in conjunction with every UI component which is bound to the backing bean using the binding attribute of the UI component. All of those attributes can be retrieved using getAttributes() of the parent UI component. As you cannot directly pass some method parameters from the JSF to the getters and setters of the bound UI component in the backing bean, the f:attribute tag might be very useful to dynamically pass the parameters. Here is a basic JSF example with the h:outputText component bound to the backing bean:

<h:outputText binding="#{myBean.text}" value="#{myBean.textValue}">
    <f:attribute name="attributename" value="attributevalue" />
</h:outputText>

Take care that each attribute name should be unique and should not overwrite any default component attributes, like “id”, “name”, “value”, “binding”, “rendered”, etc.

Here is the dummy example of the backing bean code:

package mypackage;

import javax.faces.component.html.HtmlOutputText;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private HtmlOutputText text;

    // Getters -----------------------------------------------------------------------------------

    public HtmlOutputText getText() {
        return text;
    }

    public String getTextValue() {
        return (String) text.getAttributes().get("attributename");
    }

    // Setters -----------------------------------------------------------------------------------

    public void setText(HtmlOutputText text) {
        this.text = text;
    }

}

The value of the h:outputText now should contain the value set in the f:attribute tag.

Back to top

Passing objects from request to request

If you have a request scoped managed bean and you want to reuse a property, parameter and/or object for the next request, without reinitializing it again and again, then just use the h:inputhidden tag to save the object in it. Here is a basic JSF example:

<h:form>
    ...
    <h:inputHidden value="#{myBean.value}" />
    ...
</h:form>

One requirement is that the value should be a String, or Number, or Boolean (where JSF has built-in converters for which automatically converts between them and String) or a primitive, otherwise you have to write a custom converter for it.

You can also use the SessionMap to store the values which should be saved during one user session:

package net.balusc.util;

import javax.faces.context.FacesContext;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static Object getSessionMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key);
    }

    // Setters -----------------------------------------------------------------------------------

    public static void setSessionMapValue(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
    }

}

This all is not needed for a session scoped managed bean as the managed bean instance won’t be garbaged and re-instantiated on every request. If you want to remove the value from the SessionMap, then set it to null or just invoke sessionMap.remove(key).

If you want to store static-like variables which are equal and accessible for all sessions, then you can use the ApplicationMap:

package net.balusc.util;

import javax.faces.context.FacesContext;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static Object getApplicationMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(key);
    }

    // Setters -----------------------------------------------------------------------------------

    public static void setApplicationMapValue(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().put(key, value);
    }

}

Of course this one is also not needed for an application scoped managed bean.

An alternative to the above is the Tomahawk’s t:saveState tag. It is similar the h:inputHidden, with the biggest difference that you can pass non-standard object types (such as managed beans, collections, custom objects, etc) along it while the h:inputHidden only accepts standard object types (String, Number, Boolean) as long as you don’t supply a Converter.

Back to top

Passing new hidden values to backing beans

If you want to pass new hidden input values to the backing beans, then there are two general ways. One way where you use a plain vanilla HTML hidden input field with the hardcoded value and another way where you use the JSF h:inputHidden whose value is manipulated with Javascript.

Here is the hardcoded example, you can use a plain vanilla HTML hidden input field with a form-unique name. Its value will be available in the getRequestParameterMap(). You can obtain it directly in the action method or even define a managed property for it in the backing bean. The example below makes use of the managed-property entry.

<h:form>
    <h:commandButton value="submit" action="#{myBean.action}" />
    <input type="hidden" name="hiddenInput" value="foo" />
</h:form>

The relevant part of the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>mypackage.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>hiddenInput</property-name>
        <value>#{param.hiddenInput}</value>
    </managed-property>
</managed-bean>

The backing bean (the getter is indeed not required):

package mypackage;

import javax.faces.context.FacesContext;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String hiddenInput;

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        System.out.println("hiddenInput: " + hiddenInput);

        // It is also available as follows:
        System.out.println(FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get("hiddenInput"));
        // In this case the property as well as managed-property are redundant.
    }

    // Setters -----------------------------------------------------------------------------------

    public void setHiddenInput(String hiddenInput) {
        this.hiddenInput = hiddenInput;
    }

}

Here is the Javascript way, you can just use the h:inputHidden component and manipulate its value using Javascript. All what you need to know in the Javascript side is the client ID of the h:inputHidden component. Check the generated HTML source if you’re unsure.

<h:form id="form">
    <h:commandButton value="submit" action="#{myBean.action}"
        onclick="document.getElementById('form:hiddenInput').value = 'foo';" />
    <h:inputHidden id="hiddenInput" value="#{myBean.hiddenInput}" />
</h:form>

The relevant part of the faces-config.xml, there is no managed property needed:

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>mypackage.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

The backing bean:

package mypackage;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String hiddenInput;

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        System.out.println("hiddenInput: " + hiddenInput);
    }

    // Getters -----------------------------------------------------------------------------------

    public String getHiddenInput() {
        return hiddenInput;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setHiddenInput(String hiddenInput) {
        this.hiddenInput = hiddenInput;
    }

}
Back to top

Communication between managed beans

You can have more than one managed bean in a scope. If required by design, then you can use getSessionMap() of the FacesContext to communicate between the managed beans during one browser session. This can be very useful for user-sessions by example.

An example of two managed beans in the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

The managed beans myBean1 and myBean2 are instances of the backing beans MyBean1.java and MyBean2.java, which can be accessed by JSF pages. It don’t matter whether the managed-bean-scope is set to request or session. With the managed-bean-scope set to session, the same instance of the backing bean will be used during the whole session. When the scope is set to request, then each request (form action) will create a new instance of the backing bean everytime.

You can use the getSessionMapValue() and setSessionMapValue() of the FacesUtil which is mentioned in the former paragraph to get and set values in the SessionMap. Here is an use example:

package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean1 {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String value = "value1";
        FacesUtil.setSessionMapValue("MyBean1.value", value);
    }

}
package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean2 {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String value = (String) FacesUtil.getSessionMapValue("MyBean1.value");
    }

}

The variable value now should contain the value value1. Of course only if already set by another managed bean.

Back to top

Injecting managed beans in each other

You can also inject the one managed bean in the other managed bean as a property. This may be useful if you have an application scoped bean for e.g. configurations and you want to use it in a session or request scoped bean. This is also useful if you want to keep the large data of datatables in session scope and the form actions in request scope.

Here is an example of an application scoped and request scoped managed bean in the faces-config.xml where the application scoped bean is injected in the request scoped bean:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>myBean1</property-name>
        <value>#{myBean1}</value>
    </managed-property>
</managed-bean>

Where the MyBean2 look like:

package mypackage;

public class MyBean2 {

    // Init --------------------------------------------------------------------------------------

    private MyBean1 myBean1;

    // Getters -----------------------------------------------------------------------------------

    public MyBean1 getMyBean1() {
        return myBean1;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setMyBean1(MyBean1 myBean1) {
        this.myBean1 = myBean1;
    }

}
Back to top

Accessing another managed bean

If you have more than one managed bean in a scope and you want to get the current instance of the another managed bean and get access to its properties, then there are eight ways to get the instance using the FacesContext. You can use getRequestMap, getSessionMap, getApplicationMap, getVariableResolver, createValueBinding, getELResolver (since JSF 1.2), createValueExpression (since JSF 1.2) or evaluateExpressionGet (since JSF 1.2). The first three ways will not implicitly create the bean if it is not already created by JSF or yourself. The last five ways will do.

An example of two managed beans in the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

The managed beans myBean1 and myBean2 are instances of the backing beans MyBean1.java and MyBean2.java, which can be accessed by JSF pages. It don’t matter whether the managed-bean-scope is set to request or session. Only take care that you can use the getRequestMap method only when the scope of the another managed bean is set to request, and you can use the getSessionMap only when the scope of the another managed bean is set to session.

The JSF use example:

<h:form>
    <h:commandButton action="#{myBean1.action1}" value="action1" />
    <h:commandButton action="#{myBean1.action2}" value="action2" />
    <h:commandButton action="#{myBean1.action3}" value="action3" />
    <h:commandButton action="#{myBean1.action4}" value="action4" />
    <h:commandButton action="#{myBean1.action5}" value="action5" />
    <h:commandButton action="#{myBean1.action6}" value="action6" />
    <h:commandButton action="#{myBean1.action7}" value="action7" />
    <h:commandButton action="#{myBean1.action8}" value="action8" />
    <h:outputText binding="#{myBean2.text}" />
</h:form>

Here is the first bean, MyBean1.java. Note that you should access the another managed bean by the managed-bean-name as definied in the faces-config.xml.

package mypackage;

import javax.faces.context.FacesContext;

public class MyBean1 {

    // Actions -----------------------------------------------------------------------------------

    // Using RequestMap. NOTE: myBean2 should be request scoped and already created!
    public void action1() {
        MyBean2 myBean2 = (MyBean2) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestMap().get("myBean2");

        // This only works if myBean2 is request scoped and already created.
        if (myBean2 != null) {
            myBean2.getText().setValue("action1");
        }
    }

    // Using SessionMap. NOTE: myBean2 should be session scoped and already created!
    public void action2() {
        MyBean2 myBean2 = (MyBean2) FacesContext.getCurrentInstance().getExternalContext()
            .getSessionMap().get("myBean2");

        // This only works if myBean2 is session scoped and already created.
        if (myBean2 != null) {
            myBean2.getText().setValue("action2");
        }
    }

    // Using ApplicationMap. NOTE: myBean2 should be application scoped and already created!
    public void action3() {
        MyBean2 myBean2 = (MyBean2) FacesContext.getCurrentInstance().getExternalContext()
            .getApplicationMap().get("myBean2");

        // This only works if myBean2 is application scoped and already created.
        if (myBean2 != null) {
            myBean2.getText().setValue("action3");
        }
    }

    // Using VariableResolver. NOTE: this is deprecated since JSF 1.2!
    public void action4() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication()
            .getVariableResolver().resolveVariable(context, "myBean2");

        myBean2.getText().setValue("action4");
    }

    // Using ValueBinding. NOTE: this is deprecated since JSF 1.2!
    public void action5() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication()
            .createValueBinding("#{myBean2}").getValue(context);

        myBean2.getText().setValue("action5");
    }

    // Using ELResolver. NOTE: this is implemented since JSF 1.2!
    public void action6() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getELContext()
            .getELResolver().getValue(context.getELContext(), null, "myBean2");

        myBean2.getText().setValue("action6");
    }

    // Using ValueExpression. NOTE: this is implemented since JSF 1.2!
    public void action7() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication().getExpressionFactory()
            .createValueExpression(context.getELContext(), "#{myBean2}", MyBean2.class)
                .getValue(context.getELContext());

        myBean2.getText().setValue("action7");
    }

    // Using evaluateExpressionGet. NOTE: this is implemented since JSF 1.2!
    public void action8() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication()
            .evaluateExpressionGet(context, "#{myBean2}", MyBean2.class);

        myBean2.getText().setValue("action8");
    }

}

The second bean, MyBean2.java:

package mypackage;

import javax.faces.component.html.HtmlOutputText;

public class MyBean2 {

    // Init --------------------------------------------------------------------------------------

    private HtmlOutputText text;

    // Getters -----------------------------------------------------------------------------------

    public HtmlOutputText getText() {
        return text;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setText(HtmlOutputText text) {
        this.text = text;
    }

}

You’ll probably question: Which is the best way then?? Use the evaluateExpressionGet approach (which is by the way just a shorthand for the ValueExpression approach). For ones who are still sitting with the ancient JSF 1.1 or older, then go ahead with ValueBinding approach.

Back to top

Returning current managed bean instance of self

You can also let the backing bean return the current managed bean instance of self using a static method. Here is an example with a request scoped managed bean:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Where the MyBean1 look like:

package mypackage;

import javax.faces.context.FacesContext;

public class MyBean1 {

    // Init --------------------------------------------------------------------------------------

    private static final String MANAGED_BEAN_NAME = "myBean1";

    // Actions -----------------------------------------------------------------------------------

    public static MyBean1 getCurrentInstance() {
        return (MyBean1) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestMap().get(MANAGED_BEAN_NAME);
    }

}

So you can get the current instance of MyBean1 in the another bean as follows:

package mypackage;

public class MyBean2 {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        MyBean1 myBean1 = MyBean1.getCurrentInstance();
    }

}

You can find an use example in the FriendlyUrlAction bean in the Friendly URL’s in JSF article.

Back to top

Lookup the managed bean name inside the backing bean

You can have more than one managed bean instance of the same backing bean. This might be useful if you want to implement different ways to use the backing bean. When you need to know the assigned managed bean name inside the current instance of the backing bean, then you need to lookup the values of the requestmap, sessionmap or applicationmap and compare them with the current instance of the backing bean. If it is equal, then the associated key is the same as the managed bean name.

package net.balusc.util;

import java.util.Map;

import javax.faces.context.ExternalContext;

public class FacesUtil {

    // Helpers -----------------------------------------------------------------------------------

    public static String lookupManagedBeanName(Object bean) {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

        // Get requestmap.
        Map<String, Object> requestMap = externalContext.getRequestMap();

        // Lookup the current bean instance in the request scope.
        for (String key : requestMap.keySet()) {
            if (bean.equals(requestMap.get(key))) {
                // The key is the managed bean name.
                return key;
            }
        }

        // Bean is not in the request scope. Get the sessionmap then.
        Map<String, Object> sessionMap = externalContext.getSessionMap();

        // Lookup the current bean instance in the session scope.
        for (String key : sessionMap.keySet()) {
            if (bean.equals(sessionMap.get(key))) {
                // The key is the managed bean name.
                return key;
            }
        }

        // Bean is also not in the session scope. Get the applicationmap then.
        Map<String, Object> applicationMap = externalContext.getApplicationMap();

        // Lookup the current bean instance in the application scope.
        for (String key : applicationMap.keySet()) {
            if (bean.equals(applicationMap.get(key))) {
                // The key is the managed bean name.
                return key;
            }
        }

        // Bean is also not in the application scope.
        // Is the bean's instance actually a managed bean instance then? =)
        return null;
    }

}

You can call it as follows:

package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String managedBeanName = FacesUtil.lookupManagedBeanName(this);
    }

}

Although remember that this is not always a good practice. If you can, rather subclass (extend) the backing bean into another backing bean and if necessary override or add some more code. Then assign another managed bean name to the subclassed backing bean.

Back to top

Accessing the FacesContext inside HttpServlet or Filter

Other Servlets than the FacesServlet and all Filters cannot directly access the FacesContext in the same web container, because they are sitting in the ServletContext outside the FacesContext. When you want to request the FacesContext instance outside the FacesContext, you’ll get FacesContext.getCurrentInstance() == null. In this case you need to precreate the FacesContext yourself.

package mypackage;

import java.io.IOException;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.balusc.util.FacesUtil;

public class MyServlet extends HttpServlet {

    // Actions -----------------------------------------------------------------------------------

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        doSomething(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        doSomething(request, response);
    }

    private void doSomething(HttpServletRequest request, HttpServletResponse response) {

        // Get the FacesContext inside HttpServlet.
        FacesContext facesContext = FacesUtil.getFacesContext(request, response);

        // Now you can do your thing with the facesContext.
    }

}

And here is how you can precreate the FacesContext:

package net.balusc.util;

import javax.faces.FactoryFinder;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static FacesContext getFacesContext(
        HttpServletRequest request, HttpServletResponse response)
    {
        // Get current FacesContext.
        FacesContext facesContext = FacesContext.getCurrentInstance();

        // Check current FacesContext.
        if (facesContext == null) {

            // Create new Lifecycle.
            LifecycleFactory lifecycleFactory = (LifecycleFactory)
                FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); 
            Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

            // Create new FacesContext.
            FacesContextFactory contextFactory  = (FacesContextFactory)
                FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
            facesContext = contextFactory.getFacesContext(
                request.getSession().getServletContext(), request, response, lifecycle);

            // Create new View.
            UIViewRoot view = facesContext.getApplication().getViewHandler().createView(
                facesContext, "");
            facesContext.setViewRoot(view);                

            // Set current FacesContext.
            FacesContextWrapper.setCurrentInstance(facesContext);
        }

        return facesContext;
    }

    // Helpers -----------------------------------------------------------------------------------

    // Wrap the protected FacesContext.setCurrentInstance() in a inner class.
    private static abstract class FacesContextWrapper extends FacesContext {
        protected static void setCurrentInstance(FacesContext facesContext) {
            FacesContext.setCurrentInstance(facesContext);
        }
    }     

}

Think twice about this practice and don’t misuse it. If you’re using a Filter and you want to access the FacesContext, then rather use a PhaseListener instead and listen on the first phase (the PhaseId.RESTORE_VIEW). If you just want to pass objects (attributes) from the ServletContext to the FacesContext using a HttpServlet, then rather use the getAttribute() and setAttribute() methods of the HttpServletRequest (which reflects to the RequestMap), or the HttpSession (which reflects to the SessionMap), or the ServletContext (which reflects to the ApplicationMap).

The HttpSession is accessible in the HttpServlet using HttpServletRequest#getSession() and the ServletContext is accessible in the HttpServlet using the inherited method getServletContext().

Login and Registration is one of the most required module of any project. This tutorial explains how to implement login and registration functionality in your JSF project. The example application in this tutorial is named “RichLRApplication” which uses RichFaces as JSF implementation and library of rich featured components. We have selected RichFaces for the application because it provides a large number of useful components which are enough to start with. RichFaces components are AJAX enabled which increases the responsiveness of the application.

In this application, Login page appears first in front of the user. User fills the login and password information and enters into the application for further actions. After successful user login, user can edit and save its profile information, change password and logout itself. If user is not able to login to the application i.e. forget the password, it can get password by clicking the link “Forgot Password?” in the login page itself. User is asked for the email id, which if valid and registered then password is sent to the email id. User can now login to the application by checking the mail and getting the password from there. If any new user wants to register itself in the application, there is a link “Register Here” for it. This link takes the user to the registration page where user can fill the required information and submit the information. User can change its password after successful login to the application by entering the old password and new password.

This Login & Registration example application provides:

  1. User Login
  2. User Registration
  3. Retrieve password to the registered email id
  4. Edit User Profile Information
  5. Change User Password
  6. User Logout

Application Development Steps:

To understand the application easily, we have divided the process in the following steps. These steps will let you understand the development of directory structure for the application, creating database structure, developing presentation layer through JSP, creating managed beans and running the application.

  1. Developing directory structure for the application
  2. Developing database for the application
  3. Creating configuration files
  4. Developing JSP files
  5. Creating managed beans
  6. Creating a properties file
  7. Registering managed bean and defining navigation rules
  8. Running the application

You can also download full source code for this application in zipped format. Unzip the source code and deployed it to the Tomcat server.
Download full Source Code

You can also download the database script to create the database required for the application. Execute the script and database will be created automatically.
Download Script for database

  Our example application uses:

  1. JSP pages for presentation purpose
  2. JavaBean to handle model data and
  3. Configuration files for defining managed bean, navigation rules, controller servlet.

http://www.roseindia.net

JSF 2.0 Tutorial

Posted: May 7, 2012 in JSF + Hibernate

JavaServer Faces (JSF) 2.0, is a MVC web framework which focus on simplifies building user interfaces (comes with 100+ ready UI tags) for Java web application and make reusable UI component easy to implement. Unlike JSF 1.x, almost everything are declared in faces-config.xml, with JSF 2.0, you are allowed to use annotation to declared navigation, managed bean or CDI bean, which make your development more easier and faster.

In this tutorials, it provides many step by step examples and explanations on using JavaServer Faces (JSF) 2.0 framework.

Happy learning JSF 2.0 🙂

Quick Start

Some quick start examples for JSF 2.0

  • JSF 2.0 hello world example
    A JavaServer Faces (JSF) 2.0 hello world example, shows the JSF 2.0 dependencies, basic annotations and configurations. Let you have a quick idea about how JSF 2.0 look like, and also how it different from JSF 1.x.
  • JSF 2.0 + Ajax hello world example
    In JSF 2.0, coding Ajax is just like coding a normal HTML tag, it’s extremely easy. In this tutorial, you will restructure the last JSF 2.0 hello world example, so that, when the button is clicked, it will make an Ajax request instead of submitting the whole form.
  • How to make Eclipse IDE supports JSF 2.0
    Here’s a quick guide to show how to enable the JSF 2.0 features in Eclipse project.
  • Resources (library) in JSF 2.0
    In JSF 2.0, all your resources files like css, images or JavaScript, should put into a “resources” folder in the root of your web application. In JSF 2.0 terminology, all the sub-folder name of the “resources” folder is consider as a “library” in JSF 2.0 web application. Later, you can reference this “library” with JSF tag’s library attribute.

Managed Bean

About managed bean configuration and injection in JSF 2.0

  • Configure Managed Beans in JSF 2.0
    In JSF 2.0, Java bean that can be accessed from JSF page is called Managed Bean. The managed bean can be a normal Java bean, which contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value).
  • Injecting Managed beans in JSF 2.0
    In JSF 2.0, a new @ManagedProperty annotation is used to dependency injection (DI) a managed bean into the property of another managed bean.

Navigation

How navigation works in JSF 2.0

  • Implicit Navigation in JSF 2.0
    Now, JSF 2 come out a new “auto view page resolver” mechanism named “implicit navigation“, where you don’t need to declare the above navigation rule, instead, just put the “view name” in the action attribute and JSF will find the correct “view page” automatically.
  • Conditional Navigation Rule in JSF 2.0
    JSF 2 comes with a very flexible conditional navigation rule to solve the complex page navigation flow.
  • JSF “form-action” navigation rule example
    In JSF navigation rule, you may encounter a situation where two separate actions return a same “outcome” in a page. In this case, you can use “form-action” element to differentiate the two navigation cases.
  • JSF : Page Forward vs Page Redirect
    By default, JSF is perform a server page forward while navigating to another page. See following example to differentiate between the page forward and page redirect.

Resource Bundles

JSF’s message manipulation and internationalization.

  • JSF 2.0 and Resource Bundles example
    In this tutorial, we show you the use of resource bundle to display the messages in the JSF 2.0. For maintainability concern, it’s recommended to put all the messages in properties file, instead of hard-code the message in the page directly.
  • JSF 2 internationalization example
    JSF 2.0 internationalization or multiple languages example.

JSF Tag Library

Standard JSF 2 form’s tag component.

Table Manipulation

Add, update, delete and sorting data in via JSF’s dataTable.

Facelets Tags

Doing layout template with JSF 2.0 facelets tags.

Converters & Validation

Standard Convertors and validator tags in JSF 2.0

Composite Components

Reusable components in JSF 2.0

Event Handler

JSF 2 comes with many event handler to hijack the JSF’s life cycle.

Integrate with Other Frameworks

How to integrate JSF with external services.

FAQ

Some Frequent ask questions in JSF 2.0

Common Errors

Some common error messages in JSF 2.0

Reference

Some useful reference site for further study on JSF 2.0

  1. JSF official Website
  2. The JSF application lifecycle
  3. Converter and Validation
  4. Communication in JSF

http://www.mkyong.com

Reset password in SVN

Posted: May 3, 2012 in JSEE

The Problem

When you open a project from Subversion repository AnkhSVN will prompt you to authenticate (If you have turned on security in your subversion repository). Once you enter your username and password and check the save password it will not prompt again.

Now what if you change your password? I googled about this for two days but didn’t find any solution. Luckily today my boss found this.
The Solution

The authentication data is saved to the following directories

%APPDATA%\Subversion\auth\svn.ssl.server
%APPDATA%\Subversion\auth\svn.simple

Deleting all the files inside these folders will solve the problem. After deleting these files AnkhSVN will prompt you for username and password once again.

I am currently writing a small Visual Studio Add-in that will help you clear these information from within Visual Studio.