I've implemented a Servlet Filter to fix the resulting HTML output before it is handed over to the client. It removes all duplicates of <link>
und <script>
elements at all – not only limited to these particular RichFaces embeds.
public class RichFacesDuplicatesFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Ignore resources...
final String path = ((HttpServletRequest) request).getServletPath();
if (path.startsWith("/javax.faces.resource")) {
chain.doFilter(request, response);
return;
}
// Wrapper via https://stackoverflow.com/a/23381235
CapturingResponseWrapper wrapper = new CapturingResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, wrapper);
String content = wrapper.getCaptureAsString();
content = this.removeDuplicates(content, "<link [^>]+\\/>");
content = this.removeDuplicates(content, "<script [^>]+><\\/script>");
response.getWriter().write(content);
}
private String removeDuplicates(String content, String regex) {
int index = 0;
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL | Pattern.MULTILINE);
Matcher matcher = pattern.matcher(content);
while (matcher.find(index)) {
index = matcher.end();
content = content.substring(0, index)
+ content.substring(index).replace(matcher.group(), "");
matcher = pattern.matcher(content);
}
return content;
}
}
This adds a (very) little overhead to each request and solves that problem for now. We hope to get rid of RichFaces at all in the future.
PS: Wrapper via https://stackoverflow.com/a/23381235