从控制器访问百日咳片段

时间:2014-01-15 05:59:30

标签: java spring web thymeleaf

嗨,我是百老汇的新手。当我试图从我的控制器访问百日咳片段时,它说片段或模板不存在.Below是我的控制器代码,用于访问我的片段。

控制器

@RequestMapping(value="/firstpage")
public String firstPage(){
  return "mainpage::firstpage";
}

我的百万美元拦截器文件是

public class ThymeleafLayoutInterceptor extends HandlerInterceptorAdapter {
private static final String LayoutFile = "mainHTML/layoutFile";
private static final String ReturnedHtmlFile = "returnedHTML";

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView == null || !modelAndView.hasView()) {
        return;
    }

    String originalViewName = modelAndView.getViewName();
    if (originalViewName.startsWith("redirect:") || originalViewName.startsWith("forward:")) {
        return;
    }
    modelAndView.setViewName(LayoutFile);
    modelAndView.addObject(ReturnedHtmlFile,originalViewName);
}
}

,我的spring配置文件是

@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class BeanConfig {
@Bean 
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setOrder(1);
    return resolver;
}
@Bean 
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    return engine;
}
@Bean 
public ThymeleafViewResolver thymeleafViewResolver() {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine());
    return resolver;
}
}

我的布局文件是

<!DOCTYPE html>
 <html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">
 <body>
<div th:include="${returnedHTML}" class="contents"></div>
 </body>
</html>

最后是我的mainpage.html文件

<html>
<body>
  <div th:fragment="firstpage">
   Hi...This is my first page 
 </div>
 </body>
</html>

当我在控制器中返回字符串作为“mainpage”时,主页面的所有内容都会出现。但是如果我们尝试以片段形式访问它会返回上面提到的错误消息。任何人都可以帮我解决我的问题。

1 个答案:

答案 0 :(得分:0)

我相信你做的一切都是正确的。

我认为问题是org.thymeleaf.standard.processor.attr.StandardIncludeFragmentAttrProcessor(实际上是org.thymeleaf.standard.processor.attr.AbstractStandardFragmentHandlingAttrProcessor)在评估表达式之前尝试解析片段:$ {returnedHTML} 。由于字符串“$ {returnedHTML}”尚未包含片段,因此模板将无法正确处理。

请参阅org.thymeleaf.standard.processor.attr.AbstractStandardFragmentHandlingAttrProcessor.computeFragment(Arguments,Element,String,String):List

当您不在拦截器中交换变量并从控制器返回片段时,它将像魅力一样工作。我假设您实现了类似于此处描述的自定义布局技术:http://blog.codeleak.pl/2013/11/thymeleaf-template-layouts-in-spring.html。我是对的吗?