Passing information between JSF pages - java

I am developing an application where I have to show data from the database based on User Input (let's say field empid for employee id and I show some information from database based on this input). I am using JSF, PrimeFace and Hibernate.
Now I have the index.xhtml page where I am taking input the empid. After that, I have to redirect to another page page2.xhtml.
Here is a snippet from index.xhtml:
<h:form>
<p>Employee ID:
<p:inputText value="#{userBean.newuser.empid}" required="true"/></p>
</h:form>
<br />
<h:form>
<p:commandButton action="page2?faces-redirect=true" value="Enter" />
</h:form>
But after re-directing to page2.xhtml, the empid input from index.xhtml page is lost. I tried to read a few posts on this but was not able to understand. Please help. I am sorry if it is a repeated question.

I assume that viewscopes of managed bean in which you are insterested in are #RequestScope ? You could specify more wide view scope for a managed bean, so it won't be destroyed after each request. However #RequestScope is really good when want to minimize session scope bloat. To stay with this session scope you could use flash object which was introduced with JSF 2.0. Thanks to this object you can transfer data between requests. You could put following code snippet :
ExternalContext.getFlash().put("empid", newuser.getEmpid);
in your userBean. After redirect you could retrieve that value on jsf page in the following way :
#{flash.empid}
Or in your managed bean :
ExternalContext.getFlash().get("empid");
More about flash with example can be found in this post or in JSF 2 Flash documentation

Related

Alternative to scriptlet for setting session variable?

I'm creating some pages for a web application, I currently have some pages with a brief description of a company and a link to allow them to log in to access more information. When the user logs in, they should be redirected to the more detailed version of the page.
In order to do this, when the user clicks on the log in link, I save the company name (as it is used in the url) to the session and access it when the user is logging in to figure out where to redirect them to.
This works fine but the only problem is these pages are using simple file name controllers and I don't want to implement controllers for them just so I can set this attribute. I've found a fix by using scriptlets in my jsp:
<a href="<c:url value='/login.jsp' />"
onclick="<% session.setAttribute( "partner", "companyName" ); %>"
>
Click here to log in
</a>
Now after some reading on SO and other resources I know that use of these scriptlets is highly discouraged, but I'm at a loss as to how to fix this problem without having to implement a controller to handle this simple problem. Any suggestions would be greatly appreciated.
use jstl
<c:set var="partner" value="companyName" scope="session" />

JSF: How to invoke a method from object? [duplicate]

Sometimes, when using <h:commandLink>, <h:commandButton> or <f:ajax>, the action, actionListener or listener method associated with the tag are simply not being invoked. Or, the bean properties are not updated with submitted UIInput values.
What are the possible causes and solutions for this?
Introduction
Whenever an UICommand component (<h:commandXxx>, <p:commandXxx>, etc) fails to invoke the associated action method, or an UIInput component (<h:inputXxx>, <p:inputXxxx>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml,
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.
Possible causes
UICommand and UIInput components must be placed inside an UIForm component, e.g. <h:form> (and thus not plain HTML <form>), otherwise nothing can be sent to the server. UICommand components must also not have type="button" attribute, otherwise it will be a dead button which is only useful for JavaScript onclick. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.
You cannot nest multiple UIForm components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.
No UIInput value validation/conversion error should have occurred. You can use <h:messages> to show any messages which are not shown by any input-specific <h:message> components. Don't forget to include the id of <h:messages> in the <f:ajax render>, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.
If UICommand or UIInput components are placed inside an iterating component like <h:dataTable>, <ui:repeat>, etc, then you need to ensure that exactly the same value of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.
If UICommand or UIInput components are included by a dynamic source such as <ui:include src="#{bean.include}">, then you need to ensure that exactly the same #{bean.include} value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
The rendered attribute of the component and all of its parents and the test attribute of any parent <c:if>/<c:when> should not evaluate to false during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a #ViewScoped bean or making sure that you're properly preinitializing the condition in #PostConstruct of a #RequestScoped bean should fix it. The same applies to the disabled and readonly attributes of the component, which should not evaluate to true during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway
The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm component should not return false or cause a JavaScript error. There should in case of <h:commandLink> or <f:ajax> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.
If you're using Ajax via JSF 2.x <f:ajax> or e.g. PrimeFaces <p:commandXxx>, make sure that you have a <h:head> in the master template instead of the <head>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.
If you're using Ajax, and the submitted values end up being null, then make sure that the UIInput and UICommand components of interest are covered by the <f:ajax execute> or e.g. <p:commandXxx process>, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
If the submitted values still end up being null, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to #Dependent which effectively recreates the bean on every single evaluation of the EL expression. See also #SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?
If a parent of the <h:form> with the UICommand button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form> in the render of the <f:ajax>. See also h:commandButton/h:commandLink does not work on first click, works only on second click.
If the <h:form> has enctype="multipart/form-data" set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>, check this answer and for PrimeFaces <p:fileUpload>, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.
Make sure that the ActionEvent argument of actionListener is an javax.faces.event.ActionEvent and thus not java.awt.event.ActionEvent, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}". If you don't want an argument in your method, use actionListener="#{bean.method()}". Or perhaps you actually want to use action instead of actionListener. See also Differences between action and actionListener.
Make sure that no PhaseListener or any EventListener in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse() or FacesContext#responseComplete().
Make sure that no Filter or Servlet in the same request-response chain has blocked the request fo the FacesServlet somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.
If you are using a PrimeFaces <p:dialog> or a <p:overlayPanel>, then make sure that they have their own <h:form>. Because, these components are by default by JavaScript relocated to end of HTML <body>. So, if they were originally sitting inside a <form>, then they would now not anymore sit in a <form>. See also p:commandbutton action doesn't work inside p:dialog
Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar UI element with a defaultLabel attribute (or, in some cases, a rich:placeholder sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.
Debugging hints
In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax> enabled button while not having <h:head> declared (as described in point 7 above).
Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText> and a single <h:commandButton> with <f:ajax execute="#form" render="#form">.
(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)
In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand component, that would be UICommand#queueEvent() and in case of UIInput component, that would be UIInput#validate(). Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.
If your h:commandLink is inside a h:dataTable there is another reason why the h:commandLink might not work:
The underlying data-source which is bound to the h:dataTable must also be available in the second JSF-Lifecycle that is triggered when the link is clicked.
So if the underlying data-source is request scoped, the h:commandLink does not work!
While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:
If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="#this" to your command components.
As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both #form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="#this" and render="#none" respectively.
Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)
I would mention one more thing that concerns Primefaces's p:commandButton!
When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.
For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".
Hope this will help someone!
Got stuck with this issue myself and found one more cause for this problem.
If you don't have setter methods in your backing bean for the properties used in your *.xhtml , then the action is simply not invoked.
I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.
I had a command button on a row of a datatable (the extended version, so <hx:datatable>) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).
I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope. The data backing the table itself was in a sort of ViewScope (in reality, temporarily in SessionScope).
If the row display was increased via the control which value was also bound to the datatable's rows attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.
Placing this attribute in the same scope as the table data itself fixed the problem.
I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.
I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">.
In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.
Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.
Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).
Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.
What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.
I had lots of fun debugging an issue where a <h:commandLink>'s action in richfaces datatable refused to fire. The table used to work at some point but stopped for no apparent reason. I left no stone unturned, only to find out that my rich:datatable was using the wrong rowKeyConverter which returned nulls that richfaces happily used as row keys. This prevented my <h:commandLink> action from getting called.
One more possibility: if the symptom is that the first invocation works, but subsequent ones do not, you may be using PrimeFaces 3.x with JSF 2.2, as detailed here: No ViewState is sent.
I fixed my problem with placing the:
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
In:
<h:form>
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
</h:form>
This is the solution, which is worked for me.
<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
actionListener="#{userGroupSetupController.saveData()}"
update="growl userGroupList userGroupSetupForm" />
Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from #ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!--Working-->
</p:dialog>
</h:form>
<h:form id="form2">
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Not Working-->
</p:dialog>
</h:form>
</ui:composition>
To solve;
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!-- Working -->
</p:dialog>
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Working -->
</p:dialog>
</h:form>
<h:form id="form2">
<!-- .......... -->
</h:form>
</ui:composition>

Is there a way I can invoke something per request in a view scoped bean in JSF?

I have a basic CRUD view-scoped bean. Within the setter methods I am performing some data-specific validation, which build a detailed error message for each setter if an error occurs in any of them.
This works fine, but I would like to empty this error message on each request and I have no idea how I would do that.
preRenderView won't cut it, because this error message needs to be rendered as well. Something like a postRenderView would be ideal.
You shouldn't perform validation in setter methods and you shouldn't store validation messages in the backing bean. Your whole problem is just caused by bad design and not utilizing JSF provided validation facilities.
Just utilize JSF provided validation facilities instead of working completely around it and all your problems as described so far will disappear. You can use several of the JSF builtin validators such as required="true", validator="javax.faces.XxxValidator, <f:validateXxx> tags, etc on input components. You can create a custom validator by implementing Validator interface and giving it an unique validator ID which you use in validator="myValidator" or <f:validator validatorId="myValidator">.
When using JSF standard validation, any validation error will be thrown as a ValidatorException with a FacesMessage in the request scope which would be shown in a <h:message> associated with the component. This way the messages will "automagically" disappear in the subsequent requests.
Here's a very basic kickoff example:
<h:form>
<h:inputText id="foo" required="true" requiredMessage="Enter this!" />
<h:message for="foo" />
<h:commandButton value="Submit" />
</h:form>
See also:
Is there how to validate into rich:calendar if the date selected is before a specific date?
How to create JSF form with AJAX data validation
How to show multi error message in jsf while validation is in EJB?
How validate two password fields by ajax?
etc...

Elegant handling of attributes without a session bean

I'm working on an application using JSF 2.0 and Richfaces 4, that consists of many tables that display elements and of course, the usual View/Edit/Delete options. After some SO browsing and Google search I've decided to post a question because the answers I found did not solve my problem.
Right now, and going straight to the point, my application is having issues when handling certain attributes that are stored in request beans and, on certain points, are lost due to successive requests.
For example, when I want to edit an object, the object is sent (f:propertyActionListener) to a request bean that displays the data on a form, then it is discarded as that request ends. When saving, a new object is created and the attributes on the form are setted to it and the item gets saved instead of updated, since it has no id (JPA + Hibernate).
I've investigated many options and this is what I've did so far and the results:
f:param + h:link or h:commandLink: With #ManagedProperty the param is null, and I can't find it on the Context to look it up through JNDI.
f:setPropertyActionListener + h:commandLink + Request Bean: Works... but I'm losing some data. The form that displays the data has some conditionally rendered fields and I can't hold that info, so the form is messed if the validation phase finds invalid data.
f:viewParam + h:commandLink + View Scoped Bean: Weird stuff here. This one doesn't directly work because the bean seems to get discarded before rendering the form, because the form is rendered with no information since the bean is clean.
Using a session bean: Works like a charm, but I don't want to make a session bean for every form just because I'm still learning things about the JSF lifecycle, I want to do it the proper way.
If I want to keep the Request session approach, is there a way to store a parameter (either an object or a plain string) and obtain later on a request bean?.
Dunno if this helps but I'm using a master page through ui:insert and ui:define.
Use a view scoped bean. It should work. The problems which you describe there suggests that you're binding it to JSTL tags or id or binding attributes. You should not do that on a view scoped bean. See also #ViewScoped fails in tag handlers. Another possible cause is that you're using CDI's #Named to manage the bean instead of JSF's #ManagedBean. That would also explain why #ManagedProperty doesn't work in one of your attempts as it also requires the bean to be managed by JSF's #ManagedBean.
As to the master-detail page approach, use a <h:link> with <f:param> in the table page to create view/edit links in the master page.
E.g. user/list.xhtml
<h:dataTable value="#{userList.users}" var="user">
<h:column>#{user.id}</h:column>
<h:column>#{user.name}</h:column>
<h:column>
<h:link value="Edit" outcome="edit">
<f:param name="id" value="#{user.id}" />
</h:link>
</h:column>
</h:dataTable>
The bean can be just request scoped.
Then, in the defail page, which is in this case an edit page, use <f:viewParam> to convert, validate and set the id as User.
E.g. user/edit.xhtml
<f:metadata>
<f:viewParam name="id" value="#{userEdit.user}"
converter="#{userConverter}" converterMessage="Bad request. Unknown user."
required="true" requiredMessage="Bad request. Please use a link from within the system." />
</f:metadata>
<h:messages />
<h:link value="Back to all users" outcome="users" />
<h:form id="user" rendered="#{not empty userEdit.user}">
<h:inputText value="#{userEdit.user.name}" required="true" />
...
<h:commandButton value="Save" action="#{userEdit.save}">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
</h:form>
Use a #ViewScoped bean to hold the data, service and action methods:
#ManagedBean
#ViewScoped
public class UserEdit {
private User user;
#EJB
private UserService service;
public String save() {
service.save(user);
return "users";
}
// Getter+setter.
}

Pass Value From JSP To JSF Page Backing Bean

Is it possible to pass parameter from a JSP page to a JSF page's backing bean?
JSP page is popup window open when I invoke a button in JSF page and my selected value in JSP page, I should be able to pass to JSF's backing bean.
P.S. When I add comment and I put #anyname when someone replies, #namyname part is getting truncated.
Update 1
To get the selected value from JSP to bean I did a crude approach.
I added the the following in JSP
String str = request.getParameter("selectname");
and assigned string str to a hidden field
<input type="hidden" name="hid" value="<%=str%>" />
and in my bean I am getting the value like the following
logger.info("jsp value "+FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("hid"));
This almost works except I always gets the value which I previously selects.
E.g. First time when I selects 1 and value returned in bean is null, second time when I selects 2, value returned is 1.
How could I get the currently selected value in my bean?
First, if your JSF view technology is JSP, then you can use the <h:> tags in the jsp and it becomes straightforward 0 just add a <h:commandButton action="#{yourBean.yourMethod}" />
Otherwise, you still can perhaps, but I'd suggest that you make your popup also a JSF page. JSF and JSP don't coexist well. If you really must retain the situation, then you can try to emulate a JSF POST request to the target jsf URL.
f:viewParam lets you associate bean
properties with request parameters
–
-This introduces several new capabilities
New tags that navigate via GET instead of POST and tags that
navigate via GET instead of POST, and send parameters along with the
address
Sending data from non-JSF forms to JSF pages
Make results pages results pages bookmarkable
This is a new feature in JSF 2.0
example:
<f:viewParam name="fg" value="#{colorPreferences.foreground}" />
If the “fg” parameter is non-null, it is passed to
setForeground before the page is rendered
<f:metadata>
<f:viewParam name="param1" value="#{bean.prop1}"/>
<f:viewParam name="param2" value="#{bean.prop2}"/>
</f:metadata>
<h:head>…</h:head>
<h:body>
Blah Blah blah #{bean prop1} , blah, #{bean.prop1}
</h:body>
If the page is called with page.jsp?param1=foo&param2=bar, then “foo” and “bar” are passed to “setProp1” and “setProp2” before the page is rendered. If any of the parameters are null (i.e., no such request parameter exists), then the associated setter is not called at all, and the bean has its normal value for that property
You can find the answer from the JSF tutorial http://www.coreservlets.com/JSF-Tutorial/jsf2/

Categories