首页 > 解决方案 > Spring mvc:有没有办法调用另一个控制器,获取响应并将其填充到模型属性?

问题描述

我有两个 mvc 样式端点返回模板文件名称作为视图名称,在同一个类路径中:/source 和 /target。source_template 有一个变量,该变量需要由另一个模板的内容填充,比如 target_template。

@RestController
class SomeController {

    @GetMapping("/source")
    public String source(Model model) {       
        model.addAttribute("attr1", /*call endpoint /target and add the response of parsed template 'target_template' here */);

        return "source_template";
    }

    @GetMapping("/target")
    public String target(Model model) {
        model.addAttribute("attr2", "good");
        //may be continue the nested invocation n number of times
        return "target_template";
    }
}

给定 source_template.html: Hai, $attr1 和 target_template.html: 这是 $attr2 的一天

话虽如此,我调用 url /source,我应该得到“嘿,这是美好的一天”。

我可以直接调用 target() 方法,但这不会呈现模板。或者我应该直接使用模板引擎api链接模板文件,放置上下文对象,解析模板并返回字符串,这违背了spring mvc的全部目的。或者我可以使用resttemplate,但这需要一个绝对url,并且性能会受到影响。那么,还有其他方法可以做到吗?

标签: spring-mvc

解决方案


推荐阅读