Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the standard href="#" attribute of h:commandLink?

Tags:

jsf-2

mojarra

I am maintaining a JSF2 Ajax application and we are heavily using h:commandLinks and f:ajax tags for all actions - always only rerendering what is needed.

This does of course break the expected behaviour for the user when performing a right click on the links and choosing "Open Link in New Tab" etc.

I understand that f:ajax forces the href atribute of the resulting a element to be # and does all the magic post request trickery in the onclick function - I now want to provide fallback support for the "Open Link..." action by putting some meaningful link in the href attribute of the resulting <a> tag.

This would not break the "normal" onclick behaviour as the generated javascript always finishes with return false; but would allow me to send my users to some page using a normal GET request in case they want to open the link in a new window.

Is there a build in way to do this? Or could somebody point me in the right direction on where in the JSF lifecycle I would have to jump in to do this maybe using a phase listener?

like image 752
bxr Avatar asked Nov 04 '22 15:11

bxr


1 Answers

Simplest would be to extend com.sun.faces.renderkit.html_basic.CommandLinkRenderer and override the renderAsActive() method accordingly. Mojarra is open source, just copy the method and edit the line where it says writer.write("href", "#", "href"). Replace the "#" string accordingly to your insight.

public class MyCommandLinkRenderer extends CommandLinkRenderer {

    @Override
    protected void renderAsActive(FacesContext context, UIComponent command) throws IOException {
        // ...
    }

}

To get it to run, register it as follows in faces-config.xml:

<render-kit>
    <renderer>
        <component-family>javax.faces.Command</component-family>
        <renderer-type>javax.faces.Link</renderer-type>
        <renderer-class>com.example.MyCommandLinkRenderer</renderer-class>
    </renderer>
</render-kit>

Note that this tight couples your renderer to Mojarra. To be JSF implementation independent, you'd need to create a whole new renderer instead of extending a Mojarra specific renderer class.


Unrelated to the concrete problem, consider reading When should I use h:outputLink instead of h:commandLink?

like image 92
BalusC Avatar answered Nov 15 '22 13:11

BalusC