Reputation: 16291
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.
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.
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;
}
}
}
Are there any other solutions for the problem?
Upvotes: 4
Views: 2545
Reputation: 926
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;
}
}
btw, this is for wicket 6. You can do similar stuff though in 1.5 and previous versions.
Upvotes: 1
Reputation: 3583
you could ask for the URL of the page and then redirect
String fullUrl = RequestCycle.get().getUrlRenderer()
.renderFullUrl(Url.parse((String) urlFor(RedirectPage.class,parameters)));
setResponsePage(new RedirectPage(fullUrl+"#anchor"));
Upvotes: 0