JSF page onload executes button click

2019-09-18 19:22发布

问题:

I have a following JSF page and I check if user is logged in on body onload event.

    <h:body onload="#{adminManagedBean.adminIsLoggedIn()}">
    <div id="top-bar" class="pure-g">
        <div class="pure-u-1-2">
            <img src="images/logo.png" border="0" style="margin-left: 20px;"/>
        </div>
        <div class="pure-u-1-2">
            <div class="pure-menu pure-menu-open pure-menu-horizontal">
                <ul>
                    <li><a href="addProduct.xhtml">Add product</a></li>
                    <li><a href="products.xhtml">Products</a></li>
                    <li><a href="orders.xhtml">Orders</a></li>
                    <li><h:button value="Logout" onclick="#{adminManagedBean.logoutUser()}"></h:button></li>

My question is why is user automaticaly logged out when the page loads? I debuged the app and logoutUser method is called when the page is opened even though the button isn't clicked. The logoutUser method in not called in the adminIsLoggedIn() method. adminIsLoggedIn simply redirects the page if the user is not logged in.

回答1:

You're confusing javascript attribute with server side attribute. eg. onclick is a javascript executed when the component is clicked.

What happens on you case is that onclick="#{adminManagedBean.logoutUser()}" evaluate adminManagedBean.logoutUser() on the server side which make the logout.

It'll be fixed if you use:

<h:commandButton value="Logout" action="#{adminManagedBean.logoutUser()}"/>

You're also misusing onload on you h:body