2014-09-02 54 views
0

我有我的控制器類中創建一個字符串變量使用thymeleaf頁面之間傳遞值,我想用這個如何在Spring MVC的Web應用程序

${time} 

我的代碼,將其打印在JSP頁面如果我不使用thymeleaf視圖解析器,但是如果我使用它,它不起作用。

這裏是我的控制器類

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

我thymeleaf解析器配置:

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

有一個特殊的符號與thymeleaf做到這一點?

+1

想必,你是不是使用JSP與thymeleaf。你什麼意思_不工作_?清楚。你在做什麼?你期望發生什麼?究竟發生了什麼? – 2014-09-02 21:53:30

回答

0

Aesir's answer工作,但它並不需要將我的.jsp頁面更改爲.html頁面。我只是把這個

<div th:text="${time}">TIME_PLACEHOLDER</div> 

而不是隻是$ {time},它沒有建議的HTML標頭。

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> 
相關問題