Wednesday, May 11, 2011

Global Filter Bean in JSF

I come to idea to save user search criteria in a bean. The bean will be in Session scope, because each user will have different search criteria to use. When user, redirected to another page, the search value still exist while in session scope. If the session expired or invalidated, then the value is gone.

I'm using JSF 2.0, Mojarra 2.0.4. With ajax features built-in. So in the bean I will save the search criteria per view. Each view will have it's own map (HashMap)

FilterBean

package com.mycompany;

import java.io.Serializable;
import java.util.HashMap;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mycompany.DTO;

@Component("filterBean")
@Scope("session")
public class FilterBean implements Serializable {

    HashMap<String, DTO> map = new HashMap<String, DTO>();

    public DTO getData() {
        String currentViewId = getFacesContext().getViewRoot().getViewId();
        if (!map.containsKey(currentViewId)) {
            // create a new key
            map.put(currentViewId, new DTO());
        }
        return this.map.get(currentViewId);
    }

}
DTO is Data Transfer Object which there is HashMap<String, Object> inside

public class DTO implements Serializable {
         private HashMap<String, Object> map;

         //setter or getter
}

No comments: