Getting a GET request param into an @ViewScoped bean

烂漫一生 提交于 2019-11-30 23:29:09

The @PostConstruct is invoked directly after bean's construction and all dependency injection (such as @PersistenceContext, @EJB, @ManagedProperty, @Inject, etc..etc..).

The <f:viewParam> sets its value during the update model values phase, which is far after (post)construction of the bean. So inside the @PostConstruct the <f:viewParam> value is simply not yet been set. It'll be still null at that point.

You're close with <f:event type="preRenderView">, but you have to remove the @PostConstruct annotation.

So:

<f:viewParam name="pq" value="#{pqHome.id}">
    <f:convertNumber integerOnly="#{true}" />
</f:viewParam>
<f:event type="preRenderView" listener="#{pqHome.init}" />

with

private Integer id;

public void init() {
    instance = em.find(PQ.class, id);       
}

Unrelated to the concrete problem, I'd suggest to use a Converter for this instead. See also Communication in JSF 2.0 - Converting and validating GET request parameters.

Also the combination @Named @ViewScoped won't work as intended. The JSF-specific @ViewScoped works in combination with JSF-specific @ManagedBean only. Your CDI-specific @Named will behave like @RequestScoped this way. Either use @ManagedBean instead of @Named or use CDI-specific @ConversationScoped instead of @ViewScoped.

Sebastian Denis

There is a better way to get id from url. Just use it in @PostConstruct init() method to get "id" from url:

FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");

You can still use ViewScoped and @PostConstruct.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!