views:

331

answers:

1

In struts, I'd like to have a base URL (an <s:url...) set up with a some parameters (<s:param...), and then either add parameters to that URL or change the values of some parameters. For example:

<s:url action="getSomeData" id="baseDataUrl">
    <s:param name="someID" value="%{currentID}"/>
</s:url>

I can then do <s:property value="baseDataUrl" /> and it'll spit out something like /getSomeData.do?someID=5. (I'm keeping the params simple for this example, but you can imagine having many more default params. For instance, the app I'm working on has 3 params that are the same for every URL, and two that change.)

I'd like to be able to add or change parameters after defining that base URL. I'm dreaming up two approaches:

<s:url base="baseDataUrl" id="breadUrl">
    <s:param name="bread" value="%{'toast'}"/>
</s:url>

And then <s:property value="breadUrl" /> would result in /getSomeData.do?someID=5&bread=toast. Another approach is to define the base URL with placeholders:

<s:url action="getSomeData" id="baseDataUrl">
    <s:param name="someID" value="%{currentID}"/>
    <s:param name="bread" />
    <s:param name="jelly" />
</s:url>

And then fill them in when I ask for the property:

<s:param url="baseDataUrl" name="bread" value="%{'toast'}"/>
<s:param url="baseDataUrl" name="jelly" value="%{selectedJam}"/>

So <s:property value="baseDataUrl" /> would result in /getSomeData.do?someID=5&bread=toast&jelly=7.

The docs for s:url (http://struts.apache.org/2.0.14/docs/url.html) say "Dynamic Attributes Allowed: false" so I think I'm venturing into custom-tag territory. This feels like such a common use case (define a base URL with some params, and then add or change some of them) that I don't want to reinvent the wheel. Searching has yielded nothing, but maybe I'm not looking for the right thing. I'm open to a wide variety of suggestions!

+1  A: 

Here are few options that I can think of

  1. Use an action called "delegatorAction" and write only the extra params that is needed. You could write an Action/Handler which then "infers" the other params (in this case "someID"). This could be complicated and you may have to alter this code everytime there is a change to your url handling logic
  2. You could write your own url tag and say and have a property like "base" the way you have suggested, which just evaluates the base attribute and adds any param to it (You could subclass the Url Tag for that)
  3. The most simplistic approach could be to first declare the 3 params as a url and then add the extra parameters using standard s:property tags (Heck I cant get to output xml code even with proper formatting dont know why, must be because of chrome)

In this approach you are merely appending strings at the end.

Calm Storm
#3 is the approach I ended up going with -- I defined a few base URLs and then s:property'd them to death. It's not the most elegant solution but it reduced my LOC by almost 60%! Thanks.
jibberia