使用<p:commandButton>时deck_id参数为空(Mojarra 2.3)求助
问题排查与解决方案
核心原因
页面头部能正常使用deck_id是因为渲染阶段直接从请求参数获取,但<p:commandButton>触发的是POST回发请求,默认不会自动携带原请求参数;若CardListController中deck_id定义为int类型(而非Integer),未赋值时会默认输出0,这就是你看到的现象。
解决方案
方案1:显式传递请求参数
在<p:commandButton>中通过<f:param>携带deck_id,确保POST回发时参数不丢失:
<p:commandButton value="new card" action="#{cardListController.print}"> <f:param name="deck_id" value="#{deck_id}" /> </p:commandButton>
然后在CardListController中获取参数:
public void print() { String deckIdStr = FacesContext.getCurrentInstance() .getExternalContext() .getRequestParameterMap() .get("deck_id"); Integer deckId = deckIdStr != null ? Integer.valueOf(deckIdStr) : null; System.out.println(deckId); }
方案2:使用视图作用域Bean存储参数
将deck_id存入视图作用域的Bean中,避免依赖请求参数传递:
- 创建视图作用域的Deck详情Bean:
import javax.faces.view.ViewScoped; import javax.inject.Named; import java.io.Serializable; import javax.faces.context.FacesContext; @Named @ViewScoped public class DeckDetailBean implements Serializable { private Integer deckId; @PostConstruct public void init() { String deckIdStr = FacesContext.getCurrentInstance() .getExternalContext() .getRequestParameterMap() .get("deck_id"); if (deckIdStr != null) { deckId = Integer.valueOf(deckIdStr); } } // Getter public Integer getDeckId() { return deckId; } }
- 修改页面,替换
<ui:param>为视图Bean的属性:
<!-- 移除原<ui:param>,直接使用视图Bean --> <h1>#{deckListController.getDeckByDeckId(deckDetailBean.deckId).name}</h1> <p:commandButton value="new card" action="#{cardListController.print(deckDetailBean.deckId)}" />
- 修改
CardListController的方法接收参数:
public void print(Integer deckId) { System.out.println(deckId); }
方案3:使用<f:attribute>传递参数(适用于actionListener)
若坚持使用actionListener,通过<f:attribute>绑定参数:
<p:commandButton value="new card" actionListener="#{cardListController.print}"> <f:attribute name="deck_id" value="#{deck_id}" /> </p:commandButton>
然后在Controller中从组件属性获取:
import javax.faces.event.ActionEvent; public void print(ActionEvent event) { Integer deckId = (Integer) event.getComponent().getAttributes().get("deck_id"); System.out.println(deckId); }
额外注意事项
- 检查
CardListController中deck_id的类型:若定义为int,未赋值时默认是0,建议改为Integer,未赋值时会显示null,更便于排查问题。 - 确保视图作用域Bean的
@ViewScoped注解正确(Mojarra 2.3中需使用javax.faces.view.ViewScoped,而非旧版的javax.faces.bean.ViewScoped)。
内容的提问来源于stack exchange,提问作者JakoBolt
相关产品推荐
相关产品推荐

