Home > OS >  How to create dynamic url in Spring Thymeleaf
How to create dynamic url in Spring Thymeleaf

Time:07-05

@GetMapping("/deposit")
public String deposit(@RequestParam("amount") double amount,@RequestParam ("id") int id) {

    if (amount > 0) {
        accountService.deposit(id, amount);
    }
    return "redirect:/account";
}

I have two parameters that I need to send from my html file, my problem is that 'amount' parameter should be coming from html file. How can I dynamically do that?

 <input type="number" id="amount">
 <a th:href="@{/account/deposit(id=${account.id}, amount=????)}">Deposit</a>

I want to put the input value into amount in th:href would appreciate any help.

CodePudding user response:

As it is mentioned by @andrewJames it would be mush easier to submit this value using form. For example:

In your HTML

<form th:action="@{/account/deposit(id=${account.id})}" method="post">
    <input type="number" id="amount" name="amount">
    <button type="submit">Deposit</button>
</form>

In your Controller

@PostMapping( "/deposit" )
public String onDepositSubmit( @RequestParam Long id, @RequestParam Integer amount ) {
    if (amount > 0) {
        accountService.deposit(id, amount);
    }
    return "redirect:/account";
}

This would be the easiest solution. However, it is possible to dinamically alter a link as at the client-side the link is already rendered to a normal link (e.g. /account/deposit?id=12345), so you can manipulate it using JS as you wish, for example something like this (using JQuery):

<input type="number" id="amount">
<a th:href="@{/account/deposit(id=${account.id},amount=0)}" id="amount_link">Deposit</a>

<script>
    let amountInput = $( '#amount' )
    let amountLink = $( '#amount_link' )
    amountInput.keyup( function() {
        let url = new URL( amountLink.attr( 'href' ) );
        url.searchParams.set( 'amount', amountInput.val() )
        amountLink.attr( 'href', url.toString() )
    } )
</script>

Which would create a keyup event listener on input and update link every time the character is typed or deleted. However, this is needlessly complicated and as such is considered a bad practice.

  • Related