使用Thymeleaf和Spring Boot打开新页面 - 前端与后端交互指南
在前端使用Thymeleaf和后端使用Spring Boot来打开一个新的页面可以通过以下步骤来实现:\n\n1. 在后端创建一个控制器(Controller)类,该类负责处理前端请求并返回相应的页面。可以使用@Controller注解来标识该类为控制器。\n\n2. 在控制器中创建一个方法,用于处理打开新页面的请求。可以使用@RequestMapping注解来指定请求的URL路径。在方法体中,使用Model对象来传递数据给前端页面。\n\njava\n@Controller\npublic class MyController {\n\n @RequestMapping("/newpage")\n public String openNewPage(Model model) {\n // 在这里可以添加数据到Model对象中,以便在前端页面显示\n model.addAttribute("message", "Hello Thymeleaf!");\n\n // 返回新页面的名称,Thymeleaf会根据该名称找到对应的HTML模板文件\n return "newpage";\n }\n}\n\n\n3. 在前端创建一个HTML模板文件,用于显示新页面的内容。可以使用Thymeleaf的语法来动态展示后端传递的数据。\n\nhtml\n<!DOCTYPE html>\n<html xmlns:th="http://www.thymeleaf.org">\n<head>\n <meta charset="UTF-8">\n <title>New Page</title>\n</head>\n<body>\n <h1 th:text="${message}"></h1>\n</body>\n</html>\n\n\n4. 启动Spring Boot应用程序,并在浏览器中访问对应的URL路径,即可打开新页面并显示后端传递的数据。\n\n需要注意的是,Thymeleaf的模板文件需要放置在src/main/resources/templates目录下,以便Spring Boot能够正确加载并渲染页面。
原文地址: https://www.cveoy.top/t/topic/pQai 著作权归作者所有。请勿转载和采集!