7

I've a CDI managed bean wherein I'd like to set request parameters as managed properties:

import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@Named
@RequestScoped
public class ActivationBean implements Serializable {

    @ManagedProperty(value="#{param.key}")
    private String key;

    @ManagedProperty(value="#{param.id}")
    private Long id;

    // Getters+setters

The URL is domain/activate.jsf?key=98664defdb2a4f46a527043c451c3fcd&id=5, however the properties are never set and remain null.

How is this caused and how can I solve it?

I am aware that I can manually grab them from ExternalContext as below:

Long id = Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"), 10);
String key = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("key");

However, I'd rather use injection.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Milkmaid
  • 1,659
  • 4
  • 26
  • 39
  • have you tried to change RequestScoped on ViewScoped? – user3127896 Feb 28 '15 at 09:36
  • 1
    CDI doesn't provide out-of-the-box request parameter injection (and you can't use what you have because JSF won't inject into a CDI context, although the reverse is possible). Look at [this answer](http://stackoverflow.com/questions/13239975/depedency-inject-request-parameter-with-cdi-and-jsf2) – kolossus Feb 28 '15 at 15:48

1 Answers1

9

The JSF-specific @ManagedProperty annotation works only in JSF managed beans, not in CDI managed beans. In other words, it works only in classes annotated with JSF-specific @ManagedBean annotation, not in classes annotated with CDI-specific @Named annotation.

CDI does not offer an annotation out the box to inject specifically a HTTP request parameter. JSF utility library OmniFaces offers a @Param annotation for the very purpose of injecting a HTTP request parameter in a CDI managed bean.

@Inject @Param
private String key;

@Inject @Param
private Long id;

Alternatively, use the <f:viewParam> tag in the view.

<f:metadata>
    <f:viewParam name="key" value="#{bean.key}" />
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

See also

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555