脚本视图
Spring框架内置了集成机制,可以将Spring MVC与任何能够在JSR-223 Java脚本引擎上运行的模板库结合使用。我们已经在不同的脚本引擎上测试了以下模板库:
提示
整合任何其他脚本引擎的基本规则是,该引擎必须实现ScriptEngine和Invocable接口。
要求
你需要在类路径(classpath)中包含脚本引擎,不同脚本引擎的详细要求有所不同:
脚本模板
你可以声明一个ScriptTemplateConfigurerbean来指定要使用的脚本引擎、要加载的脚本文件、调用哪个函数来渲染模板等等。以下示例使用了Jython Python引擎:
- Java
- Kotlin
- Xml
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.scriptTemplate();
}
@Bean
public ScriptTemplateConfigurer configurer() {
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngineName("jython");
configurer.setScripts("render.py");
configurer.setRenderFunction("render");
return configurer;
}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.scriptTemplate()
}
@Bean
fun configurer() = ScriptTemplateConfigurer().apply {
engineName = "jython"
setScripts("render.py")
renderFunction = "render"
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:view-resolvers>
<mvc:script-template/>
</mvc:view-resolvers>
<mvc:script-template-configurer engine-name="jython" render-function="render">
<mvc:script location="render.py"/>
</mvc:script-template-configurer>
</beans>
渲染函数使用以下参数被调用:
String template:模板内容Map model:视图模型RenderingContext renderingContext:RenderingContext,它提供了对应用程序上下文、区域设置(locale)、模板加载器以及URL的访问权限
控制器用于填充模型属性并指定视图名称,如下例所示:
- Java
- Kotlin
@Controller
public class SampleController {
@GetMapping("/sample")
public String test(Model model) {
model.addAttribute("title", "Sample title");
model.addAttribute("body", "Sample body");
return "template";
}
}
@Controller
class SampleController {
@GetMapping("/sample")
fun test(model: Model): String {
model["title"] = "Sample title"
model["body"] = "Sample body"
return "template"
}
}