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.
1
2
3
4
<div>
    #{request.getSession(false).id}
    #{httpServletRequest.getSession(false).id}
</div>

ServletRequestProducer.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 {
 
    @Produces
    @Named
    public HttpServletRequest getHttpServletRequest() {
        HttpServletRequest httpServletRequest = null;
        Object object = FacesContext.getCurrentInstance().getExternalContext().getRequest();
        if (object instanceof HttpServletRequest) {
            httpServletRequest = (HttpServletRequest) object;
        }
        return httpServletRequest;
    }
}

0 comments :

Popular Posts