Reputation: 83
I want to make a search function that will filter data by type of letter.
Form:
<form action="/viewall/filterBy" th:object="${letter}" method="get">
<table class="table table-bordered" style="width:100%">
<tbody>
<tr>
<th>
<select class="form-control" id="type_form" th:field="*{id_type}" name="id_type">
<option disabled="disabled" selected="selected" value="0">--Select--</option>
<option th:each="type : ${letter_types}" th:value="${type.id}" th:text="${type.name}"></option>
</select>
</th>
</tr>
<tr>
<th>
<button style="display: block" class="btn btn-info"> <i class="fa fa-search"></i> Search</button>
</th>
</tr>
</tbody>
</table>
</form>
Controller
@RequestMapping (value="/viewall/filterBy", method= RequestMethod.GET) public String filterBy(Model model,@ModelAttribute("letter") LetterModel letter, @RequestParam(value="id_type", required=true) Integer id_type) {
....
return "letter-view";
}
If I execute, the URL is below:
My question is, Is it possible to change the URL, so it become
Thank you in advance. Any help is appreciated.
Upvotes: 1
Views: 453
Reputation: 2004
You can have the following url type:
http://localhost:8080/viewall/filterBy/3
then your Controller
mapping will be like the following:
@RequestMapping (value="/viewall/filterBy/{id_type}", method= RequestMethod.GET)
public String filterBy(Model model, @PathVariable(name = "id_type") int idType) {
....
return "letter-view";
}
or more simplified approach:
@GetMapping (value="/viewall/filterBy/id_type/{id}")
public String filterBy(Model model, @PathVariable(name = "id") int idType) {
....
return "letter-view";
}
UPDATE
Now since your URL pattern has changed you have to submit the form via javascript. You have to concat the selected value to your URL and then submit the form. To submit the form via javascript see the following codes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<select class="form-control" id="type_form" th:field="*{id_type}" name="id_type">
<option disabled="disabled" selected="selected" value="0">--Select--</option>
<option th:each="type : ${letter_types}" th:value="${type.id}" th:text="${type.name}"></option>
</select>
<button onclick="submitForm()"> SUBMIT </button> <!--this will call the submitForm() javascript function given below -->
<script type="text/javascript">
function submitForm() {
var selectedOption = document.getElementById("type_form"); // the <select> is assigned to the variable using its id
window.location = "/viewall/filterBy/" + selectedOption.value; // here we concat the url with the selected option and assign it to the action of the form
}
</script>
</body>
</html>
Upvotes: 1