服务于 Html 来自 Spring RestController

Serve To Html From Spring RestController

我有一个 MainController,它是一个 RestController,它使用单独的 class (CommandInterpreter.java) 中的 java 代码按价格顺序获取车辆列表。当 运行 时,'/vehicles-by-price' 已经显示我要格式化的列表。我想获取返回的列表并将其格式化为 table,但我不确定该怎么做。

我目前在 'resources/static' 中有一个 index.html 显示在主页上。有没有一种方法可以为“/vehicles-by-price”页面制作一个 html 文件来显示传递给它的列表(或者我可以在 html 中使用的 js 文件)显示在 table?

我是 Spring 的新手,所以文件的任何 code/necessary 结构都会有所帮助!

主控制器:

@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 更改为@Controller,并将return 值更改为您的视图文件路径

    @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";

  }
}

@RestController 将 return 以 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;
    }
}

示例 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>