Spring与Thymeleaf新手求助:Thymeleaf无法展示MySQL数据
Hey there! Let's figure out why your data isn't showing up on the page. Since your controller code got cut off, I'll walk through the most common pitfalls based on what you've shared, plus some fixes to get you back on track:
1. Request Mapping Mismatch
You're accessing localhost:8080, but your controller uses @RequestMapping(value = "/index"). That means you should be visiting localhost:8080/index instead. If you want the root path to work, update the mapping to:
@RequestMapping(value = "/", method = RequestMethod.GET)
2. Missing Model Data in Controller
Even if your service fetches data from MySQL, you need to pass it to the Thymeleaf view via the Model object. Here's a complete, corrected controller example:
@Controller public class HomeController { // Constructor injection is preferred over setter injection for better immutability private final TicketService ticketService; @Autowired public HomeController(TicketService ticketService) { this.ticketService = ticketService; } @RequestMapping(value = "/", method = RequestMethod.GET) public String loadHomePage(Model model) { // Fetch data from service and add it to the model List<Ticket> tickets = ticketService.getAllTickets(); model.addAttribute("tickets", tickets); // Return the name of your Thymeleaf template (e.g., home.html in src/main/resources/templates) return "home"; } }
3. Thymeleaf Template Syntax Errors
Make sure your HTML template correctly references the model data. Here's a basic example of how to display the ticket list:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Ticket List</title> </head> <body> <h1>My Tickets</h1> <table> <thead> <tr> <th>ID</th> <th>Title</th> <th>Status</th> </tr> </thead> <tbody> <!-- Loop through the "tickets" list from the model --> <tr th:each="ticket : ${tickets}"> <td th:text="${ticket.id}"></td> <td th:text="${ticket.title}"></td> <td th:text="${ticket.status}"></td> </tr> </tbody> </table> </body> </html>
4. Quick Checks to Rule Out Other Issues
- Entity Getters: Ensure your
Ticketentity class has public getter methods for all fields you want to display (Thymeleaf uses these to access properties). - Service Layer Validation: Test if
ticketService.getAllTickets()actually returns data. Add aSystem.out.println(tickets)in the controller to verify. - Database Connection: Double-check your
application.properties(orapplication.yml) for correct MySQL credentials:spring.datasource.url=jdbc:mysql://localhost:3306/your_db_name?useSSL=false&serverTimezone=UTC spring.datasource.username=your_username spring.datasource.password=your_password - Logs: Check your application startup logs for errors (e.g., SQL exceptions, missing dependencies, or template not found errors).
内容的提问来源于stack exchange,提问作者Wero

