我有一个MainController,它是一个RestController,它使用单独的类中的Java代码(CommandInterpreter.java)按价格获取车辆列表。运行时,'/ vehicles-by-price'已经显示了我要格式化的列表。我想获取返回的列表并将其格式化为表格,但我不确定如何执行此操作。
我目前在'resources / static'中有一个index.html,它显示在主页上。有没有办法为'/ vehicles-by-price'页面制作一个html文件来显示哪个列表传递给它(或者我可以在html中使用的js文件)显示在表中?
我是Spring的新手,所以文件的任何代码/必要结构都会有所帮助!
MainController:
@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;
}
}
答案 0 :(得分:2)
@RestController将以Rest Style(默认json)返回响应。因此,如果您正在使用ajax调用构建单页应用程序并调用Rest Web服务,那么RestController将非常有用。
如果您想显示产品的完整新页面,那么您可以使用@Controller,它将使用viewResolver将您重定向到适当的视图,并且您可以显示存储在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;
}
}
示例资源/ 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>
答案 1 :(得分:1)
您需要将@RestController更改为@Controller,并将返回值更改为您的视图文件路径
@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 String getVehiclesByPrice() {
vehicles = ci.getVehiclesByPrice(vehicles);
ModelAndView model = new ModelAndView();
model.addObject("vehicles",vehicles)
return "your view file path";
}
}