我使用thymeleaf返回index.html文件,但它不起作用。它不返回索引页,而只返回 1 个跨度。我想返回正确的index.html文件,我该怎么办?我返回“index”,但再次运行时只有一个跨度标签
这是控制器文件
package com.example.warehouse.controller;
import com.example.warehouse.dto.OrderDTO;
import com.example.warehouse.dto.OrderListDTO;
import com.example.warehouse.dto.ResponseCommonDTO;
import com.example.warehouse.services.WareHouseServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
@RestController
public class WarehouseController {
@Autowired
WareHouseServices wareHouseServices;
@GetMapping("/")
public String myView1() {
return "index";
}
@RequestMapping ("/home")
public String myView(Model model) {
List<OrderListDTO> orderListDTOS = wareHouseServices.displayOrderList();
model.addAttribute("order", orderListDTOS);
return "index";
}
}
index.html
<!DOCTYPE html>
My View
<h1>Welcome to My View</h1>
<p>This is a sample view without using a template engine.</p>
<ul>
<li>
<span th:text="*{order.getIdOrder()}"></span> : <span th:text="*{order.getIdWarehouse()}"> </span>
</li>
</ul>
[result](https://i.stack.imgur.com/3j4pk.png)
I want to return the correct index.html file
使用
@RestController
注释控制器会使控制器尝试直接在响应正文中返回内容。您可以通过多种方式配置 RestController 返回,例如使用 ResponseEntity
。此外,Spring MVC 尝试自动转换数据。
@RestController
public class WarehouseController {
//...
}
但是您想要的是通过 Thymeleaf 视图返回 HTML 页面。为此,您必须正确设置 Thymeleaf 并用
@Controller
注释控制器。这样 Spring MVC 就知道通过 ModelAndView 来处理请求。
模型始终在发挥作用,如果您只返回一个字符串,Spring 将尝试查找具有该特定名称的视图。您还可以进一步配置此行为,例如当返回
ModelAndView
而不是字符串时。
@Controller
public class WarehouseController {
//...
}