Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an object between @ViewScoped beans without using GET params

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.

like image 324
Chris Avatar asked Sep 05 '14 21:09

Chris


1 Answers

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");
like image 128
BalusC Avatar answered Nov 17 '22 01:11

BalusC