Spring Boot前端向Controller传递航班号参数失效问题求助
解决方案:实现表格行点击跳转并传递航班号
问题分析
当前代码存在几个关键问题:
- 表格行未绑定点击事件,无法触发跳转逻辑
- Controller仅调用查询方法但未将航班数据存入Model,预订页面无法获取详情
<td>上误用th:field属性,该属性仅适用于表单输入元素(如input、select)
下面提供两种可行的实现方案:
方案一:用Thymeleaf将整行转为可点击链接
直接给<tr>添加跳转逻辑,通过Thymeleaf生成带参数的URL:
修改后的Thymeleaf代码
<table border="solid"> <tr> <th>Airline</th> <th>Flight Number</th> <th>Departure</th> <th>Arrival</th> <th>Date</th> <th>Seats available</th> <th>Price</th> </tr> <tr th:each="flight : ${flightList}" style="cursor: pointer;" onclick="window.location.href = '@{/booking/booking-page(flightNumber=${flight.flightNumber})}'"> <td th:text="${flight.airlineName}"></td> <td th:text="${flight.flightNumber}"></td> <td th:text="${flight.departure}"></td> <td th:text="${flight.arrival}"></td> <td th:text="${flight.date}"></td> <td th:text="${flight.availableSeats}"></td> <td th:text="${flight.price}"></td> </tr> </table>
修改后的Controller代码
需将查询到的航班数据存入Model,供预订页面调用:
@Controller @RequestMapping("/booking") public class BookingController { @Autowired private FlightService flightService; @GetMapping("/booking-page") public String getBookingPage(@RequestParam("flightNumber") String flightNumber, Model model) { Flight flight = flightService.findFlightByFlightNumber(flightNumber); model.addAttribute("selectedFlight", flight); return "bookFlight"; } }
方案二:用JavaScript监听行点击(支持复杂交互)
如果需要更灵活的交互逻辑,可通过JS处理点击事件:
Thyleaf代码
<table border="solid"> <tr> <th>Airline</th> <th>Flight Number</th> <th>Departure</th> <th>Arrival</th> <th>Date</th> <th>Seats available</th> <th>Price</th> </tr> <tr th:each="flight : ${flightList}" style="cursor: pointer;" data-flight-number="${flight.flightNumber}"> <td th:text="${flight.airlineName}"></td> <td th:text="${flight.flightNumber}"></td> <td th:text="${flight.departure}"></td> <td th:text="${flight.arrival}"></td> <td th:text="${flight.date}"></td> <td th:text="${flight.availableSeats}"></td> <td th:text="${flight.price}"></td> </tr> </table> <script> document.querySelectorAll('table tr[data-flight-number]').forEach(row => { row.addEventListener('click', function() { const flightNumber = this.getAttribute('data-flight-number'); window.location.href = `/booking/booking-page?flightNumber=${flightNumber}`; }); }); </script>
Controller代码与方案一一致
同样需要将查询到的航班数据添加到Model中。
补充说明
- 添加
cursor: pointer样式,明确提示用户行可点击 - 确保
flightService.findFlightByFlightNumber方法能正确返回对应Flight对象 - 预订页面
bookFlight.html可通过${selectedFlight}获取航班详情
内容的提问来源于stack exchange,提问作者Hisham Gundagi
相关产品推荐
相关产品推荐

