Spring Boot和FreeMarker

8
我正在尝试完成Spring Boot和FreeMarker集成的简单示例(基于我在网络上发现的教程)。由于某些原因,我的视图无法解析到FreeMarker模板(我认为这是问题所在)。
在浏览器中启动时的结果只是返回TFL视图文件的名称,即“index”。因此,控制器被调用并返回字符串“index”,但似乎没有触发拉入FTL文件本身的任何触发器。如果您能提供帮助,将不胜感激...
我有以下配置类,其中我定义了视图解析器和Free Maker配置。
@Configuration
public class MvcConfigurer extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver viewResolver() {
        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setCache(true);
        resolver.setPrefix("");
        resolver.setSuffix(".ftl");
        resolver.setContentType("text/html; charset=UTF-8");
        return resolver;
    }

    @Bean
    public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
        FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
        factory.setTemplateLoaderPaths("classpath:templates", "src/main/resource/templates");
        factory.setDefaultEncoding("UTF-8");
        FreeMarkerConfigurer result = new FreeMarkerConfigurer();
        result.setConfiguration(factory.createConfiguration());
        return result;
    }
}

那么我有以下控制器:

@RestController
public class HelloController {

    /**
     * Static list of users to simulate Database
     */
    private static List<User> userList = new ArrayList<User>();

    //Initialize the list with some data for index screen
    static {
        userList.add(new User("Bill", "Gates"));
        userList.add(new User("Steve", "Jobs"));
        userList.add(new User("Larry", "Page"));
        userList.add(new User("Sergey", "Brin"));
        userList.add(new User("Larry", "Ellison"));
    }

    /**
     * Saves the static list of users in model and renders it 
     * via freemarker template.
     * 
     * @param model 
     * @return The index view (FTL)
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("model") ModelMap model) {

        model.addAttribute("userList", userList);

        return "index";
    }

    /**
     * Add a new user into static user lists and display the 
     * same into FTL via redirect 
     * 
     * @param user
     * @return Redirect to /index page to display user list
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("user") User user) {

        if (null != user && null != user.getFirstname()
                && null != user.getLastname() && !user.getFirstname().isEmpty()
                && !user.getLastname().isEmpty()) {

            synchronized (userList) {
                userList.add(user);
            }
        }
        return "redirect:index.html";
    }
}

最后,我在“src/main/resource/templates”中存储了以下FTL文件。

<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
    <a href="http://viralpatel.net"><img height="37" width="236" border="0px" src="http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align="left"/></a>
    FreeMarker Spring MVC Hello World
</H2>
</div>

<div id="content">

  <fieldset>
    <legend>Add User</legend>
  <form name="user" action="add.html" method="post">
    Firstname: <input type="text" name="firstname" /> <br/>
    Lastname: <input type="text" name="lastname" />   <br/>
    <input type="submit" value="   Save   " />
  </form>
  </fieldset>
  <br/>
  <table class="datatable">
    <tr>
        <th>Firstname</th>  <th>Lastname</th>
    </tr>
    <#list model["userList"] as user>
    <tr>
        <td>${user.firstname}</td> <td>${user.lastname}</td>
    </tr>
    </#list>
  </table>

</div>  
</body>
</html> 

1
你使用的Spring Boot版本是什么?你知道Spring Boot支持Freemarker模板自动配置吗?看看这个和这个。 - geoand
嗨,我正在使用Spring Boot v1.2.5.RELEASE。谢谢,我现在会查看这些链接。 - Hugh Lacey
2个回答

13
问题在于您的控制器使用了错误的注释。 您应该使用@Controller而不是@RestController@RestController用于指示从控制器发送的响应应发送到浏览器,通常是映射为JSON的对象。 这与添加@ResponseBody相同。

谢谢!就是这个问题...现在已经改好了,而且运行良好。你发现得真好。 - Hugh Lacey

3
虽然你已经得到了答案。但你的帖子有两点需要注意。
首先,在Spring Boot中配置Freemarker模板非常简单。无需使用WebMvcConfigurerAdapter。只需将以下内容的属性放置在类路径上即可: ```html Freemarker Spring Boot WebMvcConfigurerAdapter ```
spring.freemarker.template-loader-path: /templates
spring.freemarker.suffix: .ftl

其次,@Controller 用于将类注释为Spring MVC Controller。 @RestController 注释的类与 @Controller 相同,但处理程序方法上的 @ResponseBody 是暗示的。因此,在您的情况下必须使用 @Controller
这是从 Spring Boot FreeMarker Hello World Example帖子中找到的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接