渲染整个Wicket Header in Body

时间:2014-10-28 12:38:04

标签: java wicket wicket-6

我将我的Wicket Pages(版本6.x)渲染成PortletContainer - 实际上很好(有一些限制)。

其中一个是,我不能使用任何ajax,因为我的html标记没有html和head标记,它只是我正在呈现的body标记的内容。

我尝试使用有效的HeaderResponseContainer - 只要标记中有head标记即可。如果不存在,IHeaderResponseDecorator将不会设置为RequestCycle

即使没有head标记,我也不确定将body标记中呈现的内容呈现在head中的某个容器中的最佳方法是什么。

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

它似乎是一个黑客,但它的工作原理。如果有人能提出更清洁的解决方案,请在此处发布。

否则在类似情况下这可能会有所帮助:

在您的Application类中:

@Override
protected WebResponse newWebResponse(WebRequest webRequest,
        HttpServletResponse httpServletResponse) {
    return new MyWebResponse((ServletWebRequest) webRequest,
            httpServletResponse);
}

MyWebResponse的实施:

public class MyWebResponse extends ServletWebResponse {
    static Pattern bodyContentPattern = Pattern.compile("<body[^>]*>((?s).*)</body>");
    static Pattern headContentPattern = Pattern.compile("<head[^>]*>((?s).*)</head>");

    public MyWebResponse(ServletWebRequest webRequest,
            HttpServletResponse httpServletResponse) {
        super(webRequest, httpServletResponse);
    }

    @Override
    public void write(CharSequence sequence) {
        String string = sequence.toString();
        // if there is a html tag, take the body content, append the header content in
        // a div tag and write it to the output stream
        if (string.contains("</html>")) {
            StringBuilder sb = new StringBuilder();
            sb.append(findContent(string, bodyContentPattern));

            String headContent = findContent(string, headContentPattern);
            if (headContent != null && headContent.length() > 0) {
                sb.append("<div class=\"head\">");
                sb.append(headContent);
                sb.append("</div>");
            }
            super.write(sb.toString());
        } else {
            super.write(sequence);
        }
    }

    private String findContent(String sequence, Pattern p) {
        Matcher m = p.matcher(sequence);
        if (m.find()) {
            return m.group(1);
        }
        return sequence;
    }
}