我正在使用Thymeleaf为我的网页和Spring创建模板。以下是Spring app-servlet.xml中的配置:
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
<property name="viewNames" value="*.html,*.xhtml" />
</bean>
我还有一个带方法的控制器:
@Controller
public class HomeController {
@RequestMapping(value="/")
public String index(){
return "index";
}
}
这是webapp / WEB-INF / views / index.html中的html页面:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<title>Spring MVC Example</title>
</head>
<body>
<div th:include="templates/fragments/header::header"></div>
<h1>Hello on a second page!</h1>
<p>Click <a th:href="@{/hello}">here</a> to go back.</p>
<div th:include="templates/fragments/footer::footer"></div>
</body>
</html>
这是web.xml:
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/app-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
当我访问主页http://localhost:8080/app-web
时,我出现以下错误:
GRAVE: Servlet.service() for servlet [app] in context with path [/app-web] threw exception [Could not resolve view with name 'index' in servlet with name 'app'] with root cause
javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'app'
我不明白,因为在Dispatcher中,我加载了app-servlet.xml,其中我有templateEngine和templateViewResolver,它在目录WEB-INF / views和.html扩展名中配置。 如果有人可以提供帮助,谢谢
答案 0 :(得分:0)
我已经解决了这个错误。豆ThymeleafResolver出错了。错误是我定义的视图名称的两倍。首先,在bean templateResolver中我指定了它的后缀(.html)。其次,在下面的ThymeleafViewResolver bean中定义,我使用* .html和* .xhtml。
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
**<property name="viewNames" value="*.html,*.xhtml" />**
</bean>
在
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
</bean>