ThymeleafViewResolver手动视图渲染
@Controller
@RequestMapping("/goods")
public class GoodsController {
//手动渲染需要的模板解析器
@Resource
private ThymeleafViewResolver thymeleafViewResolver;
@RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
@ResponseBody
public String toList(Model model,
User user,
HttpServletRequest request,
HttpServletResponse response) {
//将user放入到model, 携带该下一个模板使用
model.addAttribute("user", user);
//如果从Redis没有获取到页面, 手动渲染页面,并存入到redis
WebContext webContext =
new WebContext(request, response, request.getServletContext(),
request.getLocale(), model.asMap());
//生成页面,key值为templates里面页面的名字
String html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
return html;
}
}
注意事项:
-
<!-- 要先引入jar --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
@RequestMapping里要有参数 produces = “text/html;charset=utf-8”
-
thymeleafViewResolver.getTemplateEngine().process(“goodsList”, webContext); 中的goodsList为templates里面页面的名字(资源名称html)