java - 将 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 作为前端。但就我而言,情况有所不同。
任何人都可以帮忙吗?对此,我真的非常感激!!!
解决方案
我不知道您的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 前缀)。
推荐阅读
- javascript - 没有数据库的完整 CRUD 应用程序可能吗?
- sql - 如何在雪花中调用名为“组”的列?
- c++ - 将 char 数组传递给函数 C++
- amazon-web-services - 使用 CloudFormation 在现有 AWS S3 存储桶中创建文本文件
- dsl - 是否可以导出由 JetBrains MPS 创建的 DSL 编译器并独立使用(例如从另一个 Java 程序调用它)
- xcode - 第一次运行后刷新 Swift UI 中的文本
- python - Python Tweepy Bot 随机发送图像和相应的文本标题
- r - 在使用 Shiny 的 R 中,有没有办法使用 checkboxGroupInput 的先前状态?
- ruby-on-rails - SQLite3::SQLException: no such table: main.creators: (事件和用户模型同简单有很多,属于关联)
- excel - 为什么我的代码没有遍历 word 文档中的表格?