首页 > 解决方案 > 将 Spring 模型发送到 Freemarker 头标签,没有特定路线

问题描述

我在从 Spring 发送到 Freemarker 时遇到问题。我正在使用一项服务,我需要从调用方法中获取脚本并将脚本放在 head 标记中。我对所有页面使用相同的 header.ftl。也就是说,我的 head.ftl 类似于:

<html>
<head>
   // head content
</head>
<body> // But no close tag for body.

在其他 ftl 中,我会这样做:

<#include "header.ftl">
// then continue with body content

这就是我正在做的事情:

在处理多个 RequestMappings 的 UI 控制器中,我添加:

@ModelAttribute("client")
public Client getTheClient() {
    return new Client();
}

这个 UI 控制器中的其他方法大多是:

@RequestMapping(value="/apple")
public void apple(HttpServletRequest req, HttpServletResponse res) {
  // bind the page with a "apple.ftl" templage
}

在 head 标签中,我这样做:

<script type="text/javascript">${client.getScript()}</script>

但它找不到“客户”。(说未定义之类的)然后我添加

<#import "/spring.ftl as spring">
<@spring.bind "client">

在脚本之前,现在它显示“读取导入的 spring.ftl 时出错”。(我也不知道spring.ftl在哪里。我只是关注互联网上的其他帖子。)

其他帖子正在讨论为 RequestMapping 提供特定路由,并且主要使用 jsp 作为前端。但就我而言,情况有所不同。

任何人都可以帮忙吗?对此,我真的非常感激!!!

标签: javaspringspring-mvcfreemarker

解决方案


我不知道您的Client对象看起来像,也可能有助于发布您的模型。

但是,我发现了以下几件事:

首先,每个控制器都需要 url 映射。添加一个到你的getTheClient()一个:

@RequestMapping("/client/get", method = RequestMethod.GET)
public ModelAndView getTheClient() {
    ModelAndView mav = new ModelAndView("index");
    mav.addObject("client", new Client());

    return mav;
}

其次,您引用模型和访问它的方式不正确。正确的方法

<script type="text/javascript">${client.name}</script>

假设模型名称为Client,字段为name(无需使用 set 或 get 前缀)。


推荐阅读