@Named bean中未设置带有请求参数的@ManagedProperty [英] @ManagedProperty with request parameter not set in a @Named bean

查看:115
本文介绍了@Named bean中未设置带有请求参数的@ManagedProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CDI托管bean,其中我想将请求参数设置为托管属性:

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

URL为domain/activate.jsf?key=98664defdb2a4f46a527043c451c3fcd&id=5,但是永远不会设置属性并将其保留为null.

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?

我知道我可以手动从ExternalContext抓取它们,如下所示:

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.

推荐答案

特定于JSF的 @Named 注释.

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没有提供开箱即用的注解以专门注入HTTP请求参数. JSF实用程序库 OmniFaces 提供了 @Param批注,用于将HTTP请求参数注入CDI托管bean中的目的.

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;

或者,使用 <f:viewParam> 标签.

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>

另请参见

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆