3

I am using spring-3.2 version.

@RequestMapping("/company={companyId}/branch={branchId}/employee={employeeId}/info")

The requestmapping is used to map a URL, so in this case when ever a URL is called using

<a href="company=1/branch=1/employee=1/info" > employee info </a>

the method is called in the controller with the exact @RequestMapping annotation, now I want to create the "a href" tag dynamically and want to create companyId,branchId,or employeeId dynamically.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
abhishek ameta
  • 2,326
  • 7
  • 28
  • 35

3 Answers3

12

You could of course build the string pointing to the respective URL dynamically.

A first option would be using a javascript function. However, even this function has to take the IDs from somewhere. In my example, I suppose that there are javascript variables which already contain the right IDs.

function createDynamicURL()
{
    //The variable to be returned
    var URL;

    //The variables containing the respective IDs
    var companyID=...
    var branchID=...
    var employeeID=...

    //Forming the variable to return    
    URL+="company=";
    URL+=companyID;
    URL+="/branch=";
    URL+=branchID;
    URL+="/employee=";
    URL+=employeeID;
    URL+="/info";

    return URL;
}

Then your html would be like:

<a href="javascript:window.location=createDynamicURL();" > employee info </a>

Another, more elegant solution would be to use the onClick event:

<a href="#" onclick="RedirectURL();return false;" > employee info </a>

with the function

function RedirectURL()
{
    window.location= createDynamicURL();
}

Hope I helped!

miss.serena
  • 1,170
  • 1
  • 11
  • 28
Pantelis Natsiavas
  • 5,293
  • 5
  • 21
  • 36
  • my "javascript:createDynamicURL();" is not getting called., – abhishek ameta Dec 30 '13 at 07:05
  • No I haven't checked it yet . I think javascript function is not getting called from inside the html tag. – abhishek ameta Dec 30 '13 at 07:08
  • You could use the F12 button on Chrome or Mozilla and debug javascript using breakpoints. There you will see if anything goes wrong... – Pantelis Natsiavas Dec 30 '13 at 07:09
  • This is mostly correct. I just edited it to add window.location= to the top answer. It didn't work without it. Otherwise this was a great suggestion. Thanks. – miss.serena Sep 24 '14 at 00:31
  • Is it also possible to remove words from the URL? When trying this I get 'undefined' in my URL. Please take a look at my question: https://stackoverflow.com/q/62367518/13290801 – MeL Jun 14 '20 at 06:43
0

We can use following example:

<a id="addBtn" href="#" onclick="get_dynamic_url();">Google</a></p>

<script>
function get_dynamic_url() {
    url = "Your dynamic url value";
    $("#addBtn").attr("href", url);
    return true;
}
</script>
Walk
  • 1,531
  • 17
  • 21
0

It is 2022. Use URLSearchParams or URL to build url.

Docs have everything you need.

atilkan
  • 4,527
  • 1
  • 30
  • 35