スクリプトビュー

Spring Framework には、Spring MVCJSR-223 (英語) Java スクリプトエンジン上で実行できるテンプレートライブラリと使用するための組み込みの統合があります。さまざまなスクリプトエンジンで次のテンプレートライブラリをテストしました。

スクリプトライブラリ スクリプトエンジン

ERB (英語)

JRuby (英語)

文字列テンプレート (英語)

Jython (英語)

他のスクリプトエンジンを統合するための基本的なルールは、ScriptEngine および Invocable インターフェースを実装する必要があるということです。

要件

クラスパスにスクリプトエンジンが必要です。詳細はスクリプトエンジンによって異なります。

  • JRuby (英語) は、Ruby サポートの依存関係として追加する必要があります。

  • Jython (英語) は、Python サポートの依存関係として追加する必要があります。

スクリプトテンプレート

ScriptTemplateConfigurer Bean を宣言することで、使用するスクリプトエンジン、ロードするスクリプトファイル、テンプレートをレンダリングするために呼び出す関数などを指定できます。次の例では、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: アプリケーションコンテキスト、ロケール、テンプレートローダー、URL へのアクセスを提供する RenderingContext (Javadoc)

次の例に示すように、コントローラーはモデル属性を設定し、ビュー名を指定するために使用されます。

  • 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"
	}
}

その他の構成例については、Spring Framework 単体テスト、Java [GitHub] (英語) リソース [GitHub] (英語) を参照してください。