How do I include an anchor name when forwarding from an Action? (i.e., how can I make the page returned to the browser jump to a specific section out of an Action?)

Answer 1. If you name an anchor in your page (<a name="something">) and you want the browser to jump to that specific anchor when it is rendered, you would generally do something like <a href="mypage.htm#something"> if you were doing it from a link. Or, from a servlet, you might attach #something to the end of the page name when using a dispatcher to forward. If you try to append #something to the end of a forward name from an Action though (return mapping.findForward("myForward#something")(wink) you will find that Struts throws an exception about not being able to find the forward. That is because it is looking for a forward that is literally "myForward#something" and won't find it.

Answer 2. In theory at least (can someone verify this, I'm being lazy!) you could actually name your forward "myForward#something", and it should work. However, this ties your page design a little too much to your Struts config, and that's probably not a good idea. The better solution is to use a little snippet of Javascript on the client like so:

<head>
<script>
  function jumpToAnchor() {
    <% if (request.getAttribute("hash") != null) { %>
      location.hash = "<%=request.getAttribute("hash")%>";
    <% } %>
  }
</script>
</head>
<body onLoad="jumpToAnchor();">

Then, all you need to do is add an attribute named "hash" to the request right before you return the forward from your Action. The value of the attribute is simply the name of the anchor you wish to jump to. Voila, all set!

This article has been originally submitted by Frank Zammetti.

  • No labels