问题描述
我有一个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的 @ManagedProperty
注释仅在JSF托管Bean中起作用,而在CDI托管Bean中不起作用.换句话说,它仅在使用特定于JSF的 @ManagedBean
注释,而不是在特定于CDI的 @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>
另请参见
- ViewParam与@ManagedProperty(值=#{param.id}"")
- 如何在页面加载时在后备bean中处理GET查询字符串URL参数?
- ViewParam vs @ManagedProperty(value = "#{param.id}")
- How do I process GET query string URL parameters in backing bean on page load?
See also
这篇关于@Named bean中未设置带有请求参数的@ManagedProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!