Pass an object between @ViewScoped beans without using GET params

纵然是瞬间 提交于 2019-12-27 10:30:28

问题


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.

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.

Is there any way to achieve this? I'm using Mojarra 2.2.8 with PrimeFaces 5 and OmniFaces 1.8.1.


回答1:


Depends on whether you're sending a redirect or merely navigating.

If you're sending a redirect, then put it in the flash scope:

Faces.setFlashAttribute("car", car);

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);

This is available in the @PostConstruct of the next bean as:

Car car = Faces.getRequestAttribute("car");

See also:

  • Injecting one view scoped bean in another view scoped bean causes it to be recreated
  • How to pass objects from one page to another page in JSF without writing a converter

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).


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");


来源:https://stackoverflow.com/questions/25694423/pass-an-object-between-viewscoped-beans-without-using-get-params

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