How to push url onto value stack in Struts 2

I’m using Struts 2.3.16.

How do I push an action URL onto the value stack?

I’ve tried:

<s:push value="methodUrl">
  <s:url action="action" method="method" />
</s:push>

<s:push value="methodUrl">
  <s:url action="action" method="method" var="methodUrl" />
</s:push>

<s:push>
  <s:url action="action" method="method" var="methodUrl" />
</s:push>

All the above fail without logging any errors even though I have struts.devMode=true. Only the failure of the third option was truly expected since value is required for s:push.

Background: I need to pass the URL to a JavaScript function that is in a separate .js file from a select tag like the following:

<s:select name="actionAttribute" list="attributeList"
          listKey="key" listValue="value"
          onchange="ajaxFunction('%{methodUrl}')" />

I know that I can use '<s:url action="action" method="method" />' in the JS function if the function is defined in my .jsp file, but that doesn’t work when the JavaScript is in a different file.

As I typed the above paragraph I realized that I can define a JavaScript function in my JSP that will pass the URL to the ajaxFunction.

So now my question is purely academic.

Is there a way to s:push an s:url onto the value stack?

Answer

If you use var attribute of the url tag it will put the value to the value stack.

<s:url action="action" method="method" var="methodUrl" />
<s:select name="actionAttribute" list="attributeList"
          listKey="key" listValue="value"
          onchange="ajaxFunction('%{#methodUrl}')" />

you can also use a function without parameter

<s:select name="actionAttribute" list="attributeList"
          listKey="key" listValue="value"
          onchange="ajaxFunction()" />
<script type="text/javascript">
  function ajaxFunction(){
    var methodUrl = '<s:property value="%{#methodUrl}"/>';
    // or even better
    var methodUrl2 = '<s:url action="action" method="method" var="methodUrl" />';
  }
</script>

ok, if you want to push a value into the value stack you should use this tag, but the value should be a reference to the object, that would convert to string url and passed as a parameter to JS function

<s:url action="action" method="method" var="methodUrl" />
<s:push value="%{#methodUrl}">
  <s:select name="actionAttribute" list="attributeList"
          listKey="key" listValue="value"
          onchange="ajaxFunction('%{top}')" />
  <script type="text/javascript">
    function ajaxFunction(url){
      alert(url);
    }
  </script>
</s:push>

Leave a Reply

Your email address will not be published. Required fields are marked *