gpt4 book ai didi

java - 从 Spring RestController 服务到 Html

转载 作者:行者123 更新时间:2023-12-01 20:08:20 26 4
gpt4 key购买 nike

我有一个 MainController,它是一个 RestController,它使用单独的类(CommandInterpreter.java)中的 java 代码按价格顺序获取车辆列表。运行时,“/vehicles-by-price”已经显示了我想要格式化的列表。我想获取返回的列表并将其格式化为表格,但我不确定如何执行此操作。

我目前在“resources/static”中有一个index.html,它显示在主页上。有没有办法为“/vehicles-by-price”页面创建一个 html 文件来显示,该文件将列表传递给它(或我可以在 html 中使用的 js 文件)以在表格中显示? p>

我是 Spring 新手,因此任何代码/必要的文件结构都会很有帮助!

主 Controller :

@RestController
public class MainController {
//Get CommandInterpreter object
private CommandInterpreter ci = new CommandInterpreter();
private List<Vehicle> vehicles;

MainController () throws Exception {
//Set up list of vehicles from JSON
vehicles = ci.parseJsonVehicles();
}

@RequestMapping("/vehicles-by-price")
public List<Vehicle> getVehiclesByPrice() {
vehicles = ci.getVehiclesByPrice(vehicles);
return vehicles;
}
}

最佳答案

@RestController 将以 Rest 样式(默认 json)返回响应。因此,如果您正在构建单页应用程序并使用 ajax 调用来调用 Rest Web 服务,那么 RestController 将很有用。

如果您想显示产品的完整新页面,那么您可以使用 @Controller,它将使用 viewResolver 将您重定向到适当的 View ,并且您可以显示存储在 ModelAndView 中的数据。

对于使用 html,您可以使用 Thymeleaf,它使用 html 文件,但有更多选项来渲染复杂对象并支持 El。

示例代码:

@Controller
public class MainController {
//Get CommandInterpreter object
private CommandInterpreter ci = new CommandInterpreter();
private List <Vehicle> vehicles;

MainController() throws Exception {
//Set up list of vehicles from JSON
vehicles = ci.parseJsonVehicles();
}

@RequestMapping("/vehicles-by-price")
public ModelAndView getVehiclesByPrice() {
vehicles = ci.getVehiclesByPrice(vehicles);

ModelAndView mv = new ModelAndView();
mv.add("vehicles", vehicles);
mv.setViewName("vehiclesByPrice");
return mv;
}
}

示例 resources/static/vehiclesByPrice.html 模板:

<!DOCTYPE HTML>
<html
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table>
<tr th:each="vehicle : ${vehicles}">
<td th:text="${vehicle}">1</td>
</tr>
</table>
</body>
</html>

关于java - 从 Spring RestController 服务到 Html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com