Tuesday, September 17, 2013

JSF/CDI Tip of the Day: How to create a @Producer for JSF

I was using this code as a utility class to get the current HttpServletRequest object. I added the @Named annotation to expose it via Expression Language (EL). However, it should be noted that the #{request} is an implicit object already. You can see from the output below that they do produce the same output.

package com.bluelotussoftware.bean;

import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

 * A producer class that returns the current {@link HttpServletRequest} object
 * from the {@link FacesContext#getExternalContext()}. This {@link Named}
 * producer can be used directly in Expression Language (EL) as {@literal #{httpServletRequest}}.
 * @author John Yeary
 * @version 1.0
public class ServletRequestProducer {

    public HttpServletRequest getHttpServletRequest() {
        HttpServletRequest httpServletRequest = null;
        Object object = FacesContext.getCurrentInstance().getExternalContext().getRequest();
        if (object instanceof HttpServletRequest) {
            httpServletRequest = (HttpServletRequest) object;
        return httpServletRequest;