0

Can someone tel me how to redirect with data, by the following redirect method:

FacesContext.getCurrentInstance().getExternalContext().redirect("page1.xhtml");

I have some strings "regNo" which I want to send. Also, do let me know how I receive it in page1.xhtml.

user2746713
  • 3
  • 1
  • 6

1 Answers1

2

There are a couple of options. The two most straightforward are mentioned here:

  1. Just pass it as HTTP request parameter.

    String regNo = "somevalue";
    String url = "/page1.xhtml?regNo=" + URLEncoder.encode(regNo, "UTF-8");
    ec.redirect(ec.getRequestContextPath() + url);
    

    (the URLEncoder is mandatory for the case the value contains non-ASCII or URL-special characters, or if it contains digits only, then you could skip the URL-encoding)

    It's available by #{param.regNo} in the target view, which you can set as a bean property via @ManagedProperty or <f:viewParam name="regNo"> the usual way. See also ViewParam vs @ManagedProperty(value = "#{param.id}").


  2. Pass it as flash scoped object.

    String regNo = "somevalue";
    String url = "/page1.xhtml";
    ec.getFlash().put("regNo", regNo);
    ec.redirect(ec.getRequestContextPath() + url);
    

    It's available by #{flash.regNo} in the target view, which you cna set as a bean property via @ManagedProperty.

    @ManagedProperty("#{flash.regNo}")
    private String regNo; // +setter
    

The major functional difference is that the HTTP request parameter approach is idempotent, while the flash scoped object approach is non-idempotent. In other words, only the HTTP request parameter approach is bookmarkable, exactly the same result can be reproduced by merely copypasting/bookmarking/sharing the URL.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555