Retrieve the fragment (hash) from a URL and inject the values into the bean

后端 未结 5 800
不思量自难忘°
不思量自难忘° 2020-12-14 20:03

I am looking for a way to inject values from the fragment (#) of a URL into bean(JSF), in the same way query-parameter values are injected. I am using Ben Alman\'s Bookmarka

5条回答
  •  时光说笑
    2020-12-14 20:43

    You can do this with help of window.onhashchange which fills an input field of a hidden form which submits itself asynchronously when the input field has changed.

    Here's a kickoff example of the Facelets page:

    
    
        
            SO question 3475076
            
            
        
        
            
                
                    
                
            
            

    Change the fragment in the URL. Either manually or by those links: foo, bar, baz

    Fragment is currently:

    Here's how the appropriate bean look like:

    package com.stackoverflow.q3475076;
    
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
    import javax.faces.event.AjaxBehaviorEvent;
    
    @ManagedBean
    @RequestScoped
    public class Bean {
    
        private String fragment;
    
        public void processFragment(AjaxBehaviorEvent event) {
            // Do your thing here. This example is just printing to stdout.
            System.out.println("Process fragment: " + fragment);
        }
    
        public String getFragment() {
            return fragment;
        }
    
        public void setFragment(String fragment) {
            this.fragment = fragment;
        }
    
    }
    

    That's all.

    Note that the onhashchange event is relatively new and not supported by the older browsers. In absence of the browser support (undefinied and so on), you'd like to check window.location.hash at intervals using setInterval() instead. The above code example should at least give a good kickoff. It works at at least FF3.6 and IE8.

提交回复
热议问题