JSF difference between action, actionlistener, onClick [duplicate] - jsf

This question already has answers here:
Differences between action and actionListener
(4 answers)
How to invoke a bean action method using a link? The onclick does not work
(3 answers)
Closed 5 years ago.
I am using JSF in my project. I am using a context menu from PrimeFaces. I see in p:menuItem we have action, actionListener, onclick methods. So my question is: When do I have to use action, actionListner, onclick and what is the order of execution?

onclick will be executed first. It is used to call a javascript function.
actionListener is used when you want to have some ajax call to a
method. That method should have the return type void, the method
either take an ActionEvent as argument or no argument; it can
also be used for a non-ajax call but then the page will be refreshed.
action is used to navigate to a different page; the method should
have the return type String.

This question has been asked before.
Action is used when you want to call a method in your backing bean. e.g
action="#{myBean.myMethod}"
the code for bean would be like
#ManagedBean(name = "myBean", eager = true)
#ViewScoped
public class MyBean{
myMethod(){
// your method code here
}
}
How ever action listener does the same except that it is triggered with an event
myMethod(Event e){
// your method code here
}
Note that event can be of any type.
onclick works before sending the ajax request i dont have much knowlegde aboput it... i only used it for the UI purposes for example closing a dialog box on clicking a button
<p:commandButton id="cancel" value="Cancel"
icon="ui-icon ui-icon-arrowreturnthick-1-w"
style="float:right;" onclick="PF("dlg").hide()" type="button">
</p:commandButton>
SEE ALSO
Differences between action and actionListener

Related

JSF outputlabel click event [duplicate]

This question already has an answer here:
How to call JSF backing bean method only when onclick/oncomplete/on... event occurs and not on page load
(1 answer)
Closed 5 years ago.
first of all, I am very new to JSF and web development.
What I want to do is to print a message in the console if the user click an outputlabel.
{businessBean.select()} gets called only on page refresh and not when I click.
<h:outputLabel styleClass="cat" id ="businesstasks" onclick="setColor('businesstasks'); #{businessBean.select()}">
Business and productivity
</h:outputLabel>
My test bean:
#ManagedBean(name="businessBean")
#SessionScoped
public class businessBean {
public void select(){
System.out.print("Test");
}
}
I get "Test" only when I refresh the page but I want to get it on every click.
Thanks for helping!
Is there a reason you 'need' the outputLabel to execute an action? Because onclick will execute it as a javascript, and that interaction can cause issues if you're calling the bean action method. You could use <h:commandLink action="#{businessBean.select}" /> within your output label.

Call same bean method from multiple onclick with different parameters not working [duplicate]

This question already has an answer here:
Multiple action listeners with a single command component in JSF
(1 answer)
Closed 6 years ago.
I'm using Primefaces and jsf in my application. I'm using mutiple commandlink with onclick function. All the onclick function call the same bean method but parameters are different. Pages are working fine & passing parameters also different even though all the pages are showing same metrics.
Based on parameter should display different metrics but not working properly.
XHTML:
<h:commandLink value="Defects"
action="#{loginbean.setCurrPage('metrics','defects.xhtml')}"
onclick="#{reportsBean.MetricPage('defect')}"
rendered="#{sub_selected =='defects'}" />
<h:commandLink value="Test Case"
action="#{loginbean.setCurrPage('metrics','testcase.xhtml')}"
onclick="#{reportsBean.MetricPage('testcase')}"
rendered="#{sub_selected =='testcases'}" />
Bean:
public void MetricPage(String ipageid) {
metricssection = metricsProcess.getMetricsProcess().getUserMetrics(ipageid, SessionMgr.getProj());
metricsfeature = metricsProcess.getMetricsProcess().getMetricFeatures(ipageid, SessionMgr.getPro());
}
How can i resove the problem?
onclick is a client side event. You can only call Javascript functions from onlcick. Not methods from Managedbean.
Since you tagged this question as Primefaces, I assume you are using Primefaces. In that case you can use p:remoteCommand
See this on how to use p:remotecommand

onclick for p:outputLabel works on loading/refreshing page but doesn't work when clicking

I have some problems with calling a bean method when clicking on Label.
When page is loading or refreshing click handler function pokus() is called, but when the label is clicked it isn't.
Part of my web page:
<h:form id="pokus">
<p:outputLabel id="pokus2" value="klikni" onclick="#pozadavkyBean.pokus(5)}"/>
</h:form>
and a method in bean:
public void pokus(int i){
System.out.printf("kliknuto sloupec:%d",i);
}
I've also tried it with:
<p:ajax event="click" listener="....
with the same result - method called on loading/refreshing but not when clicking
also tried others events: mousedown, mouseup, .... with same result
using PrimeFaces 5.0
If you will check official document of Primeface regarding Tag outputLabel.You can easily get attribute onclick used for
Client side callback to execute when component is clicked.
But here you are trying to run Managed bean method directly from onclick attribute while onclick used to call JavaScript functions.
As #Mahendran Ayyarsamy Kandiar mentioned and its simple thing outputLabel is not used to call any bean method. Its Just Simply used to show something in the page.In mean time for your requirement you can use CommandButton,CommandLink or some other component but its all depend upon your requirment etc.

validator for input text using the backing bean method not working [duplicate]

This question already has answers here:
JSF custom validator not invoked when submitted input value is null
(2 answers)
Closed 5 years ago.
I have a form with h:inputText and have the attribute validator with the backing bean method name as value, example:
h:inputText id="poolmanagementinput" validator="#{poolManager.validatePoolManagement}"
Now I have method in backing bean named poolManager in following format:
public void validatePoolManagement(final FacesContext context, final UIComponent component,
final Object value) {
... }
I expected this method to be called in the validation phase in JSF cycle. But to my surprise this method is not being called and validation is not happening. Could anyone point out any missing point or direct me to a soultion.
Note: Just as a side note the input is placed inside a composite:implementation.
Thanks in advance.
Cheers!
Incase if you have forgot add these attributes between body and form like this
<h:body>
<h:form>
<your ui item>
</h:form>
</h:body>
sorround your UI attribute with them. <h:form> has to be parent tag for all JSF UI components that can participate in HTML form submission.
I have encountered same issue and this has resolved issue.
I know it is a old question but answering it for the people who have the same problem.
JSF is not executing the validators if the value is blank.
You need to use required=true for validation blank.
for more reference JSF custom validator not invoked when submitted input value is null

further continuing of double press

In a previous question BalusC gave me good advice on how a button, in place of a commandButton is useful for non ajax navigation. In particular it updates the destination address in the http: position which is useful for the user to bookmark a page.
I tried to use this information to my advantage until I came upon a problem. In a button I tried to use outcome="#{backing.something}" to find out that it gives me a null result. This looks like a timing problem in that action="#{}" is evaluated only when the button is pressed whereas outcome apparently wants a fixed string which gets checked when the page is loaded.
So I went back to commandButton with ajax="false". This has a problem that my navigation address is the page I came from, not the one I am navigating to. This is the wrong bookmark for the user.
I appreciate all the help I have received in stackoverflow on my learning exercise.
Ilan
The <h/p:button outcome> is not intented to invoke a bean action method, but to contain the outcome string directly. Any EL in there is evaluated immediately as a value expression. So the method behind it would immediately be invoked when you just open the page containing the <h/p:button>.
There are in your particular case basically two ways to invoke a bean action method on navigation. If you need to invoke it before the navigation takes place and the action isn't intented to be re-invoked everytime when the enduser reopens/reloads the GET request, then make it a POST-Redirect-GET request. It's a matter of adding faces-redirect=true to the outcome value in query string syntax.
E.g.
<p:commandButton action="#{bean.submit}" ... />
with
public String submit() {
// ...
return "nextpage?faces-redirect=true";
}
This way the browser will be redirected to the target page after POST, hence the enduser will see the target URL being reflected in the address bar.
Or if you need to invoke the action everytime when the enduser reopens/reloads the GET request, do the job in the (post)constructor or preRenderView listener method of the request/view scoped backing bean instead.
E.g.
<p:button outcome="nextpage" ... />
with
#ManagedBean
#RequestScoped
public class NextpageBacking {
public NextpageBacking() {
// In constructor.
}
#PostConstruct
public void onPostConstruct() {
// Or in postconstructor (will be invoked after construction AND injection).
}
public void onPreRenderView() {
// Or before rendering the view (will be invoked after all view params are set).
}
// ...
}
The pre render view listener method needs to be definied as follows in the nextpage
<f:event type="preRenderView" listener="#{nextpageBacking.onPreRenderView}" />
See also:
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
Communication in JSF 2.0 - Processing GET request parameters

Resources