如何在Wicket的setResponsePage()中添加锚点? [英] How to add anchor in Wicket's setResponsePage()?

查看:115
本文介绍了如何在Wicket的setResponsePage()中添加锚点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要将访问某个URL的用户重定向到Wicket页面,并滚动到该页面的锚点.例如,用户直接链接到http://.../target/url/123.然后,从数据库中查找123 id.随后,将根据是否找到该实体将用户重定向到其他页面.

We need to redirect users that access a certain url to a Wicket page and scroll to a anchor in the page. E.g., the users link directly to http://.../target/url/123. Afterwards, the 123 id is looked up from database. Subsequently, the user will be redirected to a different page based on if the entity was found or not.

获取实体后,应将用户重定向到http://.../another/url/123#element123.我们如何用Wicket实现这一目标?该页面也应该在没有锚点的情况下也可以访问,并且最好是通用的解决方案.

After the entity has been fetched the user should be redirected to http://.../another/url/123#element123. How can we achieve this with Wicket? The page should also be accessible without the anchor, and preferably, the solution should be generic.

我想出的一种解决方案是,当PageParameters包含名为anchor的条目时,重写PageParametersEncoder逻辑以将#anchor附加到URL.但是,这意味着我还需要扩展自己的Url类以附加锚点.

One solution I came up with is to override the PageParametersEncoder logic to append #anchor to url when the PageParameters contains an entry named anchor. However, this means that I also need to extend the Url class with my own to append the anchor.

public class ExtendedEncoder extends PageParametersEncoder {

    public static final String ANCHOR = "anchor";

    @Override
    public Url encodePageParameters(PageParameters pageParameters) {
        Url fromSuper = super.encodePageParameters(pageParameters.remove(ANCHOR));
        return new ExtendedUrl(fromSuper,
                pageParameters.get(ANCHOR).toOptionalString());

    }
}

public class ExtendedUrl extends Url {
        private String anchor;

        private ExtendedUrl(Url url, String anchor) {
            super(url);
            this.anchor = anchor;
        }

        @Override
        public String toString(StringMode mode, Charset charset) {
            return super.toString(mode, charset)
                   + anchor == null ? "" : "#" + anchor;
        }
    }
}

还有其他解决方法吗?

推荐答案

以下代码将javascript代码段呈现到目标页面的html中,从而在页面加载后将页面集中在url中指定的锚点上.

The following code renders a javascript snippet into the html of your target page that upon page load will focus the page on the anchor specified in the url.

@Override
public void renderHead(IHeaderResponse response) {
    super.renderHead(response);
    long anchor = getRequest().getQueryParameters().getParameterValue("anchor").toLong(0);
    if (anchor > 0) {
        response.render(new OnLoadHeaderItem("location.href='#anchor" + anchor + "';"));
        anchor = 0;
    }
}

顺便说一句,这是给检票口6的.尽管在1.5和更低版本中,您也可以做类似的事情.

btw, this is for wicket 6. You can do similar stuff though in 1.5 and previous versions.

这篇关于如何在Wicket的setResponsePage()中添加锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆