get GET parameters in JSF's managed bean - jsf

Can someone tell me how to catch parameters passed from URI in JSF's managed bean?
I have a navigation menu all nodes of which link to some navigation case. And i have two similar items there: Acquiring products and Issuing products. They have the same page but one different parameter: productType. I try to set it just by adding it to URL in "to-view-id" element like this:
<navigation-case>
<from-outcome>acquiring|products</from-outcome>
<to-view-id>/pages/products/list_products.jspx?productType=acquiring</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>issuing|products</from-outcome>
<to-view-id>/pages/products/list_products.jspx?productType=issuing</to-view-id>
</navigation-case>
But i can't get this "productType" from my managed bean. I tried to get it through FacesContext like this:
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("productType")
And like this:
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
request.getParameter("productType");
And i tried to include it as a parameter of managed bean in faces-config.xml and then getting it through ordinary setter:
<managed-bean>
<managed-bean-name>MbProducts</managed-bean-name>
<managed-bean-class>my.package.product.MbProducts</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>productType</property-name>
<value>#{param.productType}</value>
</managed-property>
</managed-bean>
...
public class MbProducts {
...
public void setProductType(String productType) {
this.productType = productType;
}
...
}
But neither of these ways have helped me. All of them returned null. How can i get this productType? Or how can i pass it some other way?

The navigation rule by default does a forward. I.e. it reuses the initial request. Whatever way you try to access the request parameters in the forwarded resource, it will always try to grab them from the initial and already-processed request.
To fix this, you need to fire a redirect instead of forward. It creates a brand new request (you also see this reflecting back in the browser address bar).
In JSF, adding
<redirect/>
to the navigation case should do.

Related

JSF: navigation-rule stopped working after adding parameter to action method

I'm modernizing a JSF web application I took over from someone who retired and is not available for questions.
Current job is to simplify a h:dataTable. Each record has a commandLink to go to the corresponding details page.
Old version: action method openDetail(), determined the selected record by binding of the dataTable and looping trough the records to get the row.
New version: action method is now openDetail(Long id) and of course I added the parameter to the command link as well.
My action method is called with the correct parameter, I verified this by adding some log output. But the navigation-rule is not effective anymore. Although the action method returns the correct outcome, it stays on the page with the table.
The navigation-rule in faces-config.xml looks like this:
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-action>#{myBean.openDetail}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/mysks/detail.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
Do I need to adapt the navigation-rule ? Does JSF make a difference for overloaded action methods ?
The <from-action> has to exactly match the literal string as defined in action attribute.
So if it currently looks like this:
<h:commandButton ... action="#{myBean.openDetail(detail.id)}">`
Then the <from-action> must be exactly that literal string:
<from-action>#{myBean.openDetail(detail.id)}</from-action>
However, the whole navigation rule system has not proven to be really useful in JSF and has become de-facto deprecated since release of JSF 2.0 in 2009 which introduced the new support for immediately returning the <to-view-id> as return value, called "implicit navigation". Essentially, XML-based navigation rules are really a "leftover" of the jurassic JSF 1.x and you'd best just get rid of them.
So if you simply adjust the openDetail() method from
public String openDetail(Long id) {
// ...
return "success";
}
to
public String openDetail(Long id) {
// ...
return "/mysks/detail.xhtml?faces-redirect=true";
}
then you can get rid of the entire <navigation-rule> bloat from the faces-config.xml.
See also:
JSF implicit vs. explicit navigation

Omnifaces Faces.redirect loses conversation scope

I have problem with org.omnifaces.util.Faces#redirect and conversation scoped bean:
there is a button
<p:commandButton action="#{navigationHandler.gotoCreateCar}"
actionListener="#{createHandler.init(searchHandler.search())}
value="#{msg.search}" update=":articleSearchForm">
<f:param name="cid" value="#{javax.enterprise.context.conversation.id}"/>
</p:commandButton>
which must do a navigation to createCar page within the same conversation scope after init of my conversation scoped bean: createHandler.
In the NavigationHandler#gotoCreateCar is just a call of Faces.redirect(createCarPage).
If I do like this the parameter cid is not transfered and I lose my conversation.
If I define a navigation rule in faces-config.xml:
<navigation-case>
<from-outcome>createCar</from-outcome>
<to-view-id>/portal/createCar.xhtml</to-view-id>
<redirect />
</navigation-case>
and in the NavigationHandler#gotoCreateCar just return the needed outcome - then it works fine.
Maybe I do not understand every detail in the difference between this two navigation approaches. I would be appreciated if somebody could help me to understand the problem.
Thanks!
The conversation propagation is handled by the navigation handler. The Faces#redirect() delegates to ExternalContext#redirect() which does not use the navigation handler. You'd better use Faces#navigate() instead which delegates to NavigationHandler#handleNavigation().
public void gotoCreateCar() {
// ...
Faces.navigate("/portal/createCar.xhtml?faces-redirect=true");
}
(note: no <navigation-case> is needed in this case)
Alternatively, just return exactly that string from the action method.
public String gotoCreateCar() {
// ...
return "/portal/createCar.xhtml?faces-redirect=true";
}
The Faces#navigate() is only useful when you're inside a (listener) method which doesn't support returning a navigation case outcome, such as #PostConstruct or preRenderView.

ManagedBean is constructed but shouldn't?

I'working on a enterprise application that uses JSF 2.0, with Netbeans 7.0 and Glassfish 3.1
I have a managed bean that is ViewScoped. this is the declaration of the class:
#ManagedBean(name = "myBean")
#ViewScoped
public class MyMBean implements Serializable {
Inside its #PostConstruct, it has the following:
String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
if (id == null) {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("home.xhtml");
FacesContext.getCurrentInstance().responseComplete();
} catch (Exception e) { }
return;
}
if I go to the page that uses this managed bean, and the id is null, everything works fine, and I get redirected to home page.
The problem is that when I navigate to a different page that does NOT use this managed bean (lets say for example "otherpage.xhtml") the PostConstruct method is executed, and it shouldn't! And it gets worse: since the url of this other page doesn't have the "id" parameter, the bean tries to redirect to home page; and I get a IllegalStateException.
Any idea of why a viewscoped managed bean is constructed when navigating to a page that does not use it?
Edit:
If in order to navigate to "otherpage.xhtml" I use the commandlink in "home.xhtml", 6 extra beans are created.
But, if instead of using the link, I type the url in the browser; it works fine. No extra bean is created. Maybe there's something wrong in how I implemented the link. This is the code:
<h:form>
<h:commandLink value="Go to other page" action="otherPage" />
</h:form>
And this is the navigation rule in faces-config:
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>otherPage</from-outcome>
<to-view-id>/views/otherPage.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
Is there anything wrong there?
Thanks!
Damian
You surely have a #{myBean} somewhere in the view or one of its templates/include/tag/composite files, or as a #ManagedProperty of the beans referenced by the view. Putting a breakpoint in the (post)constructor and investigating the stacktrace should give enough insights who/what has triggered the bean's construction.
Unrelated to the concrete problem, the ExternalContext#redirect() already implicitly calls FacesContext#responseComplete(), you don't need to call it yourself. See also the method's javadoc.
Update: a <h:commandLink> submits its parent POST <form> to the current page (and thus creates all its related beans!) and then depending on the navigation outcome, it will forward/redirect to the result page. You shouldn't be using commandlinks/commandbuttons for plain page-to-page navigation. Use <h:link> instead.
<h:link value="Go to other page" outcome="views/otherPage" />
You can eventually also get rid of that <navigation-case>. If you really insist in keeping that navigation case, then use outcome="otherPage" instead.
See also:
When should I use h:outputLink instead of h:commandLink?
Communication in JSF 2.0 - Implicit navigation

Using Navigation in JSF

Framework: JSF 2.0.
My problem: I have a page, called login.xhtml. Whenever someone view that page, it invoked a filter, called Authentication filter. The filter will check, if user already loged in, it will be redirected to default based on user's role (for example: Admin will go to "admin/admin.xhtml", student will be redirected to "user/user.xhtml").
My solution: Using the JSF Navigation
My config:
faces-config.xml
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>AD</from-outcome>
<to-view-id>/admin/admin.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>US</from-outcome>
<to-view-id>/user/user.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
The redirection using navigation:
public static void redirectUsingNavigation(String from, String outCome) {
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, from, outCome);
}
My question:
When i run the redirectUsingNavigation("*","AD") or redirectUsingNavigation(null,"AD"), it does not redirect me to admin.xhtml (i'm still on login.xhtml). How to fix this?
Any framework support me on this problem?
That code is not redirecting at all. It's just forwarding the request. It's just using the same request object for a different target page). A real redirect instructs the browser to send a new request on the given Location header. You see this change being reflected back in browser address bar.
You need to either add faces-redirect=true parameter to the outcome to trigger the redirect (this is particularly useful if you're using implicit navigation instead of verbose navigation cases):
navigationHandler.handleNavigation(facesContext, from, outCome + "?faces-redirect=true")
Or add <redirect/> to the navigation cases if you want them to always take place:
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>AD</from-outcome>
<to-view-id>/admin/admin.xhtml</to-view-id>
<redirect/>
</navigation-case>
<navigation-case>
<from-outcome>US</from-outcome>
<to-view-id>/user/user.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
Last but not least, you need to ensure that handleNavigation() is called before the response is committed, otherwise it won't work at all and your server logs would be littered with IllegalStateException: response already committed errors. You can make use of <f:event type="preRenderView"> to invoke a bean action before the response is committed.
See also:
jsf navigation question
Hit a bean method and redirect on a GET request

JSF 1: execute bean method and set parameters for next page

I'm new to JSF.
What i want is to click on something and when i do i want to run a bean method AND send the request with GET so i can set Parameters that will show on the URL of the next page.
I tried with this navigation-rule, the method will execute and return "success_selectedUserToCard", it will forward me to-view-id but the parameters are removed:
<navigation-rule>
<navigation-case>
<from-outcome>success_selectedUserToCard</from-outcome>-->
<to-view-id>/jspx/user_to_card.faces?tab=usertocard&selectedLink=usertocardManagementLink</to-view-id>
</navigation-case>
</navigation-rule>
So my URL on the following page will be only: /jspx/user_to_card.faces
P.S. I am using JSF 1. Cannot move to JSF 2
Use ExternalContext#redirect() instead.
public void submit() {
// Do your job here.
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.redirect("/jspx/user_to_card.faces?tab=usertocard&selectedLink=usertocardManagementLink");
}
Nasty, but since you aren't using JSF 2.0 which supports includeViewParams, there's no other way.

Resources