I'm curious about the possibility to alter href
attributes of all generated links.
Let's assume I have a web page which looks something like this:
<div>
<h:link outcome="/foo.xhtml" value="a link" />
...
<h:link outcome="/bar.xhtml" value="another link" />
</div>
The resulting output would be something like this:
<div>
<a href="/foo.jsf">a link</a&开发者_StackOverflow社区gt;
...
<a href="/bar.jsf">another link</a>
</div>
I'm now trying to alter the URL generated as href
attribute within the generated content and let's say add a directory to all the generated links (depending on their content), so that I get the output
<div>
<a href="/a-new-location/foo.jsf">a link</a>
...
<a href="/another-new-location/bar.jsf">another link</a>
</div>
Is there a quick and easy way to achieve this or do I have to implement the component and the renderer completely on my own and copy the logics used by the standard implementation?
I think there is no a direct solution without using some renderer modification.
I propose a solution that works when the href is a valid JSF page and you want the transformation of the outcome be made before is evaluated by the navigation handler.
First, a bean for outcome transformation:
@ManagedBean
@ApplicationScoped
public class OutcomeTransformer {
public String getNewOutcome(String outcome){
if(outcome.equals("/page.xhtml")){
return "/directory/"+outcome;
}else if(outcome.equals("/anotherPage.xhtml")){
return "/anotherDirectory/"+outcome;
}else{
return outcome;
}
}
}
Seccond, use a composite component for wrapping the link. The outcome of the h:link is transformed by the bean.
<cc:interface>
<cc:attribute name="outcome"/>
<cc:attribute name="value"/>
</cc:interface>
<cc:implementation>
<h:link outcome="#{outcomeTransformer.getNewOutcome(cc.attrs.outcome)}" value="#{cc.attrs.value}"/>
</cc:implementation>
And finally, here is a using page.
<ez:myLink outcome="page.xhtml" value="A page"/>
<br/>
<ez:myLink outcome="anotherPage.xhtml" value="Another page"/>
Of course, you can use a expression directly in the h:link but with the composite component all the logic of the transformation is in only one place.
just a quick note to let you know that I solved the problem by replacing the standard ViewHandler
with my own ViewHandler
implementation that overrides the getBookmarkableURL
method and performs the replacement upon the URL generated by the parent ViewHandler
.
精彩评论