Hi I'm trying to send a select option to a controller from the user. I've had trouble with this for about a week and I can't figure it out. I'm loading my Car entity into the view and just want it passed back to the controller in the orderVehicle function.
My Controller CarViewController.java
@Controller
@RequestMapping("/car-list")
public class CarViewController {
@Autowired
private CarService carService;
@GetMapping
public String carList(Model model) {
Location limerick = new Location("Limerick");
Location cork = new Location("Cork");
//Drop down/table lists per location
ArrayList<Car> location1cars = new ArrayList<>();
ArrayList<Car> location2cars = new ArrayList<>();
ArrayList<Car> cars = (ArrayList<Car>) carService.getAllCars();
for (int i = 0; i < cars.size() / 2; i ) {
location1cars.add(cars.get(i));
}
for (int i = cars.size() / 2; i < cars.size(); i ) {
location2cars.add(cars.get(i));
}
model.addAttribute("location1", limerick);
model.addAttribute("location1vehicles", location1cars);
return "car-list";
}
@PostMapping("/order")
public String orderVehicle(@RequestParam(value = "SelectVehicle") Car vehicle, @ModelAttribute Car car) {
System.out.println(car.getVehicleID());
System.out.println(vehicle.getVehicleID());
System.out.println("Test");
return "order";
}
}
My view car-list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Vehicle List</title>
<h1>Location List</h1>
<h2 th:text="${location1.locationName}">Locations</h2>
<h3>Vehicle List</h3>
<table >
<tr th:each="vehicle : ${location1vehicles}">
<td th:text="${vehicle.name}">Vehicle Name</td>
<td th:text="${vehicle.BodyType}">Vehicle Body Style</td>
<td th:text="${vehicle.EngineSize}">Vehicle Engine Size</td>
<td th:text="${vehicle.fuel}">Vehicle Fuel Type</td>
<td th:text="${vehicle.SeatCapacity}">Vehicle Seat Capacity</td>
</tr>
</table>
<h4>Select Vehicle</h4>
<form th:action="@{/order}" th:object="${car}">
<select name="SelectVehicle" id="SelectVehicle">
<option value="0">Select Vehicle</option>
<option th:each="vehicle : ${location1vehicles}"
th:value="${vehicle}"
th:text="${vehicle.name}"></option>
</select>
<button type="submit" th:value="#{vehicle.vehicleID}">Order Vehicle</button>
</form>
</head>
</html>
When I click the button in the view I get a 404 error. I see the object reference in the link, how can I access that object and get rid of this error? What I'm looking for in my controller is to able to access the vehicle ID which is the primary key of Car so that I can query my db for the car the user selected. Thanks.
CodePudding user response:
In controller class you have given the request mapping as '/car-list'. So any other mappings of the class would be accessed by that. So to access the '/order' mapping you need to give full path in th:action '@{/car-list/order}'.