'GetMapping endpoint for a button which takes inputs from 2 text fields

I have a basic html page with 2 textboxes and a button. I need to make the button respond after the entries in the textbox

View

The body of the html looks like this :

<div class="row">
  <div class="col-2">
    <input type="text" class="form-control" id="txtFrom" placeholder="start date(yyyy-mm-dd)"
      required="required">
  </div>
  <div class="col-2">
    <input type="text" class="form-control" id="txtTo" placeholder="end date(yyyy-mm-dd)" required="required">
  </div>
</div>
<div>
  <br>
</div>
<div class="row">
  <div class="row-2">
    <!--                        <input type="button" value="Validate"> -->
    <a th:attr="href='/formular" class="btn btn-primary btn-sml" role="button" aria-disabled="true">Check</a>
  </div>
</div>

I am not able to establish a controller for the same (for the GetMapping annotation) I expect it to be @GetMapping("/formular?from={dateFrom}&to={dateTo}")

Code:

 @GetMapping("/formular?from={dateFrom}&to={dateTo}")
 public String formData(@PathVariable String dateFrom, @PathVariable String dateTo, Model model) throws IOException, SQLException {

    logger.info("inside the datefrom dateto");
    return "formular";
 }

But that does not help. It does not print the log message after entering the dates and clicking the button.

Could anyone suggest?



Solution 1:[1]

You're missing the name attribute (which is what is put in the url when you submit the form). Your form should look something like this (extra attributes omitted):

<form method="GET" th:action="@{/formular}">
  <input type="text" name="from" />
  <input type="text" name="to" />
  <input type="submit" />
</form>

And to get the variables in your controllers, I don't think you should be using @PathVariables. Rather, just regular @RequestParams.

@GetMapping("/formular")
public String formular(@RequestParam("from") String from, @RequestParam("to") String to) {
  System.out.println(from);
  System.out.println(to);
  return "formular";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Metroids