Spring Boot应用如何通过REST AJAX在主页展示数据库表格数据
根路径404问题修复步骤
1. 确认静态资源存放位置
Spring Boot 默认会扫描 src/main/resources/static 目录下的静态资源,你需要把 index.html 和 listCarsSelling.js 直接放在该目录下,不要嵌套额外文件夹。如果放在了子目录下,访问根路径自然会报404,需要对应调整访问地址。
2. 配置根路径映射
如果文件存放位置正确仍然访问根路径404,添加根路径到index页面的映射即可,两种实现方式二选一:
方式A:通过Web配置类实现
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index.html"); } }
方式B:通过Controller接口实现
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { @GetMapping("/") public String index() { return "forward:/index.html"; } }
3. 修复现有代码的已知错误
你当前的js代码存在拼写错误,会导致请求失败时看不到报错提示:
// 错误写法 allert(msg.responseText); // 修正为 alert(msg.responseText);
另外同域部署场景下可以把ajax的url简化为 /ListCarsSelling,不需要写完整的ip端口,避免后续部署环境变动要反复修改地址。
额外注意点
- 如果你在
application.properties/application.yml中配置了server.servlet.context-path上下文路径,访问地址需要加上对应前缀,ajax请求的url也要同步修改。
修改完成后重启Spring Boot应用,访问http://localhost:8080即可正常加载主页,自动拉取接口数据渲染表格。
内容的提问来源于stack exchange,提问作者1i10
相关产品推荐
相关产品推荐

