JSF 2.0 查询字符串传播
我有一个页面通过查询字符串接收 ID 号并显示相关文章。
我将
与 preRenderView 事件一起使用,并在 @PostConstruct 方法中从数据库加载数据:
@Named
@RequestScoped
public class Bean {
private Long id;
@PostCostruct
public void init() {
if (this.id != null) {
// load data from db
}
}
public String modify() {
// update data
}
}
当我调用页面时,数据已正确加载,但当我单击修改按钮时,
<h:commandButton value="Modify" action="#{bean.modify}" />
我收到错误因为没有查询字符串参数发送到 bean,因此不会加载任何数据。
如何传播查询字符串参数?
I've a page that receives an id number via querystring and shows the relative article.
I use <f:viewParams>
with preRenderView event and the data are loaded from db in @PostConstruct method:
@Named
@RequestScoped
public class Bean {
private Long id;
@PostCostruct
public void init() {
if (this.id != null) {
// load data from db
}
}
public String modify() {
// update data
}
}
When I call the page the data are correctly loaded but when I click modify button
<h:commandButton value="Modify" action="#{bean.modify}" />
I obtain an error because no query string parameter is sent to the bean and, thereby, no data are loaded.
How can I propagate query string parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,修改方法应该返回一个以“?includeViewParams=true”结尾的操作字符串。只有这样,视图参数才会被传播(理论上,它也应该与 faces-include-view-params 一起使用,与 faces-redirect 配对时,它对眼睛的伤害较小)。
附录:如果您需要(如评论中所述)在 init 方法中使用参数,那么从 JSF 的角度来看,它们不是真正的输入。你不会得到验证、转换等。但如果你只想获取原始值,请使用:
Id 将在调用 init 之前注入。请注意,这基本上是绕过 viewparams 的一种方法。您可以使用 String 以外的其他类型,但任何转换错误都会以异常结束,因此最好将其保留为字符串并手动执行任何转换。
但你的问题的根源似乎是滥用@PostConstruct;可能你想填充你的预渲染阶段,大致如下:
afaik, modify method should return an action string that ends with "?includeViewParams=true". Only then view params are propagated (it should, in theory, also work with faces-include-view-params, which hurts eyes less when paired with faces-redirect).
ADDENDUM: if you need (as stated in the comment) to use the parameter in your init method, then they are not - from JSF perspective - a real input. You do not get the validation, conversion etc. But if you just want to grab the raw value, use:
Id will be injected before calling init. Note that this is basically a way to go around viewparams. You could use some other type than String, but any conversion error would end in an exception, so it's really better to leave it as a string and do any conversion manually.
But the root of your problem seems a misuse of @PostConstruct; probably you want to fill your been in the prerender phase, roughly like so: