Search code examples
htmlforms

how to get path variable in URL instead of query param in form submit get request without JavaScript?


I have the form:

<form class="form" action="/bars" method="get" >
    <input  type="text" class="form-control" name="pid" id="pid" />
    <button  type="submit">Find By PID</button>
</form>

When submitted, I want to get URL as /bars/123 (assuming 123 was entered in input field). Instead I get /bars/?pid=123. How can I solve this without using JavaScript? I am using thymeleaf 3 with Spring Boot 2 where my controller code looks like:

@GetMapping("/bars/{pid}")
public List<Bar> findBypid(@PathVariable Integer pid, ... ) {
    Bar bar barService.findBypid(pid);
    // code omitted 
    // ......
}

I am not sure how ThymeLeaf can help here without using JavaScript.


Solution

  • You can't. Html (and ThymeLeaf) just wasn't built to work this way. You can either use JavaScript, or add special controller methods that forwards to the correct url. Something like this for example:

    @GetMapping("/bars")
    public String forwarder(@RequestParam String pid) {
        return "redirect:/bars/" + pid;
    }
    
    @GetMapping("/bars/{pid}")
    public List<Bar> findBypid(@PathVariable Integer pid, ... ) {
        Bar bar barService.findBypid(pid);
        // code omitted 
        // .
        // .
        // .
    }