我有一个我在控制器类中创建的字符串变量,我想使用此
在jsp页面中打印它${time}
如果我不使用百日咳视图解析器,我的代码可以正常工作,但如果我使用它,它就不起作用。
这是我的控制器类
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
String thetime = "the time";
model.addAttribute("time", thetime );
return "home.jsp";
}
我的.jsp页面
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${time}. </P>
</body>
</html>
我的百里香叶解析器配置:
@Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
resolver.setCacheable(false);
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.setMessageSource(messageSource());
return engine;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
String[] vistas = {"*.html", "*.jsp"};
resolver.setTemplateEngine(templateEngine());
resolver.setOrder(1);
resolver.setViewNames(vistas);
resolver.setCache(false);
return resolver;
}
@Bean
public SpringResourceTemplateResolver thymeleafSpringResource() {
SpringResourceTemplateResolver vista = new SpringResourceTemplateResolver();
vista.setTemplateMode("HTML5");
return vista;
}
是否有一个特殊的符号用百里香叶做这个?
答案 0 :(得分:0)
Aesir's answer有效,但没有必要将我的.jsp页面更改为.html页面。我只是把这个
<div th:text="${time}">TIME_PLACEHOLDER</div>
而不仅仅是$ {time},它没有建议的HTML标头。
答案 1 :(得分:0)
您已将视图解析器设置为Thymeleaf,但您尝试呈现JSP,这就是它无法正常工作的原因。
如果您希望将该文件转换为Thymeleaf格式,则需要看起来像这样(或大约),扩展名必须是.html而不是.jsp:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is <div th:text=#{time}>TIME_PLACEHOLDER</div> </P>
</body>
</html>