如何在 Spring MVC 中使用 Handlebars?

How to use Handlebars in Spring MVC?

我有软件包,但我不确定如何使用它。我是否只是像使用 .jsp 文件一样使用它们?

我试过这样的方法:

test.hbs

<p>{{message}}</p>

在我的控制器中:

private static class M {
    private final String message;

    public M(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

@RequestMapping("/test")
public ModelAndView testView() {
    ModelAndView mav = new ModelAndView("test.hbs");
    M m = new M("Hello, world!");

    mav.addObject("m", m);

    return mav;
}

我收到错误:javax.servlet.ServletException:无法在名称为 'dispatcher'[=13 的 servlet 中解析名称为 'test.hbs' 的视图=]

我已经把test.hbs正常放在/WEB-INF/views/test.hbs里了。如果我把任何 .jsp 文件放在那里,它就可以工作。但出于某种原因 .hbs 不起作用。有什么想法吗?

Spring MVC 没有对 Handlebars 的开箱即用支持(有关支持的视图技术列表,请参阅 official documentation)。

话虽如此,但可以直接向 Spring MVC 添加对任何基于 JVM 的视图技术的支持。在高层次上,这需要实现 org.springframework.web.servlet.View 及其对应的 org.springframework.web.servlet.ViewResolver.

幸运的是,已经有 an open source project 提供这种集成。可以按照以下步骤将此项目集成到现有 Spring MVC 应用程序中。

Step 1: Add the library to the build system (assuming Maven)

<dependency>
  <groupId>com.github.jknack</groupId>
  <artifactId>handlebars-springmvc</artifactId>
  <version>4.0.6</version>
</dependency>

Step 2: Configure a Handlebars ViewResolver for the Spring MVC application in dispatcher-servlet.xml (or equivalent Java configuration)

<bean class="com.github.jknack.handlebars.springmvc.HandlebarsViewResolver">
  <property name="prefix" value="/WEB-INF/views/"/>
  <property name="suffix" value=".hbs"/>
</bean>

Step 3: Add Handlebars views to the application

鉴于上述配置,应将 Handlebars 视图添加到 /WEB-INF/views/ 文件夹下。

Step 4: Load Handlebars views

@RequestMapping("/test")
public ModelAndView testView() {
  ModelAndView mav = new ModelAndView("test");
  M m = new M("Hello, world!");

  mav.addObject("m", m);

  return mav;
}

请注意,视图名称不应包含 .hbs,因为后缀已添加到配置中。