a href / h:link outcome / h:button outcome methods automatically called during page load without any clicks

后端 未结 1 761
遇见更好的自我
遇见更好的自我 2020-12-12 02:41

I have 3 pages with 3 links that I tried implementing with h:link or simply an tag. But in both cases the methods connected to these link

相关标签:
1条回答
  • 2020-12-12 02:51
    <a href="#{bean.gotoMySrchie()}">           
    
    <h:link ... outcome="#{bean.gotoMySearches()}">
    

    They are called as value expressions because their return value needs to be printed in there during generating the HTML output during the JSF render response phase. Their return value is used as href in the resulting HTML output. Rightclick the page in webbrowser, do View Source and look at the value of the href attribute. If those methods returned String, you'll see exactly that string being printed there.

    They are, on the contrary to what you expected, not called as method expressions during JSF invoke application phase as result of a postback. This is just a fundamental misunderstanding. To invoke actions during a postback, you need <h:commandXxx action> instead.

    <h:form>
        <h:commandLink ... action="#{bean.gotoMySearches()}" />
    </h:form>
    

    This however fires a POST request, not a GET request, which may thus have many other consequences.

    Clicking a plain link by default sends a GET request not a POST request. If you want to keep using GET, which is a good thing in this specific case, then you should be doing the database job in the @PostConstruct method of the backing bean associated with target page instead of during loading the page containing those links as you did there.

    <h:link ... outcome="/searches">
        <h:graphicImage ... />
    </h:link>
    
    @Named
    @RequestScoped // Or @ViewScoped
    public class SearchesBean {
    
        @PostConstruct
        public void init() {
            // Here.
        }
    
        // ...
    }
    

    See also:

    • Invoke JSF managed bean action on page load
    • When should I use h:outputLink instead of h:commandLink?
    • Differences between action and actionListener
    • How to navigate in JSF? How to make URL reflect current page (and not previous one)
    0 讨论(0)
提交回复
热议问题