[英]Serve To Html From Spring RestController
我有一个MainController,它是一个RestController,它使用Java代码在单独的类(CommandInterpreter.java)中按价格顺序获取车辆列表。 运行时,“ / vehicles-by-price”已经显示了我要格式化的列表。 我想获取返回的列表并将其格式化为表格,但是我不确定如何执行此操作。
我目前在主页上显示的“ resources / static”中有一个index.html。 有没有一种方法可以使“ / vehicles-by-price”页面显示html文件,从而将列表传递给它(或者我可以在html中使用的js文件)以显示在表格中?
我是Spring的新手,所以文件的任何代码/必要结构都将有所帮助!
主控制器:
@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将您重定向到适当的视图,并且可以显示存储在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>
您需要将@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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.