在不使用 GET 参数的情况下在 @ViewScoped bean 之间传递对象 [英] Pass an object between @ViewScoped beans without using GET params
问题描述
我有一个 browse.xhtml
,我在其中浏览了 cars
列表,我想在 details.xhtml
中查看汽车的详细信息> 按下查看更多"按钮时.它们的支持 bean 是 @ViewScoped
,分别称为 BrowseBean
和 DetailsBean
.
I have a browse.xhtml
where I browse a list of cars
and I want to view the details of the car in details.xhtml
when a "View more" button is pressed. Their backing beans are @ViewScoped
and are called BrowseBean
and DetailsBean
, respectively.
现在,我不希望用户/客户端在 URL 中看到汽车 ID,所以我想避免使用 GET 参数,如此处 和 此处.
Now, I wouldn't like the user/client to see the car ID in the URL, so I would like to avoid using GET params, as presented here and here.
有什么办法可以做到这一点吗?我将 Mojarra 2.2.8 与 PrimeFaces 5 和 OmniFaces 1.8.1 一起使用.
Is there any way to achieve this? I'm using Mojarra 2.2.8 with PrimeFaces 5 and OmniFaces 1.8.1.
推荐答案
取决于您是发送重定向还是仅仅导航.
Depends on whether you're sending a redirect or merely navigating.
如果您要发送重定向,请将其放入 flash 范围:
If you're sending a redirect, then put it in the flash scope:
Faces.setFlashAttribute("car", car);
这在下一个 bean 的 @PostConstruct
中可用:
This is available in the @PostConstruct
of the next bean as:
Car car = Faces.getFlashAttribute("car");
或者,如果您只是导航,则将其放入请求范围:
Or, if you're merely navigating, then put it in the request scope:
Faces.setRequestAttribute("car", car);
这在下一个 bean 的 @PostConstruct
中可用:
This is available in the @PostConstruct
of the next bean as:
Car car = Faces.getRequestAttribute("car");
另见:
- 将一个视图范围的 bean 注入另一个视图范围的 bean 会导致它被重新创建
- 如何在不编写转换器的情况下在 JSF 中将对象从一个页面传递到另一个页面
请注意,我假设您非常清楚具有两个完全独立的视图的设计选择,如果没有另一个视图,它们就不能存在(幂等),而不是具有例如具有条件渲染内容的单个视图.并且您已经知道当实际以幂等方式(即通过书签、共享链接、搜索机器人等)请求视图时,视图应该如何表现.如果没有,那么我强烈建议您仔细阅读这个问题的答案:如何在 JSF 中导航?如何使 URL 反映当前页面(而不是前一个页面).
Note that I assume that you're very well aware about the design choice of having two entirely separate views which cannot exist (be idempotent) without the other view, instead of having e.g. a single view with conditionally rendered content. And that you already know how exactly the view should behave when it's actually being requested idempotently (i.e. via a bookmark, shared link, by a searchbot, etc). If not, then I strongly recommend to carefully read the answer on this question: How to navigate in JSF? How to make URL reflect current page (and not previous one).
更新:如果您不使用 OmniFaces,请分别使用以下内容:
Update: in case you're not using OmniFaces, use respectively the following:
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("car", car);
Car car = (Car) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("car");
FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("car", car);
Car car = (Car) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("car");
这篇关于在不使用 GET 参数的情况下在 @ViewScoped bean 之间传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!