The use of view technologies in Spring MVC is pluggable. Whether you decide to use Thymeleaf, Groovy Markup Templates,
JSPs, or other technologies is primarily a matter of a configuration change. This chapter covers view technologies
integrated with Spring MVC.
Spring MVC 中使用视图技术的插件式。您决定使用 Thymeleaf、Groovy 标记模板、JSP 或其他技术,主要是配置更改的问题。本章涵盖了与
Spring MVC 集成的视图技术。
We assume you are already familiar with View Resolution.
我们假设您已经熟悉视图分辨率。
The views of a Spring MVC application live within the internal trust boundaries of that application. Views have access
to all the beans of your application context.
Spring MVC 应用的视图存在于该应用的内部信任边界内。视图可以访问应用程序上下文中的所有 bean。
As such, it is not recommended to use Spring MVC’s template support in applications where the templates are editable by
external sources, since this can have security implications.
因此,不建议在模板可由外部来源编辑的应用程序中使用 Spring MVC 的模板支持,因为这可能存在安全风险。
Thymeleaf is a modern server-side Java template engine that emphasizes natural HTML templates that can be previewed in a
browser by double-clicking, which is very helpful for independent work on UI templates (for example, by a designer)
without the need for a running server.
Thymeleaf 是一种现代的服务器端 Java 模板引擎,强调自然 HTML 模板,可以通过双击在浏览器中预览,这对于独立进行 UI
模板工作(例如,由设计师)而不需要运行服务器非常有帮助。
If you want to replace JSPs, Thymeleaf offers one of the most extensive sets of features to make such a transition
easier. Thymeleaf is actively developed and maintained. For a more complete introduction, see
the Thymeleaf project home page.
如果您想替换 JSPs,Thymeleaf 提供了最全面的特性集,使这种过渡更加容易。Thymeleaf 正在积极开发和维护。欲获取更完整的介绍,请参阅
Thymeleaf 项目主页。
The Thymeleaf integration with Spring MVC is managed by the Thymeleaf project. The configuration involves a few bean
declarations, such as ServletContextTemplateResolver, SpringTemplateEngine, and ThymeleafViewResolver.
See Thymeleaf+Spring for more details.
Thymeleaf 与 Spring MVC 的集成由 Thymeleaf 项目管理。配置涉及一些 bean 声明,例如 ServletContextTemplateResolver 、
SpringTemplateEngine 和 ThymeleafViewResolver 。有关更多详细信息,请参阅 Thymeleaf+Spring。
Apache FreeMarker is a template engine for generating any kind of text output from
HTML to email and others. The Spring Framework has built-in integration for using Spring MVC with FreeMarker
templates.
Apache FreeMarker 是一种用于从 HTML 到电子邮件等其他任何类型文本输出的模板引擎。Spring 框架内置了对使用 Spring MVC 和
FreeMarker 模板进行集成的支持。
The following example shows how to configure FreeMarker as a view technology:
以下示例展示了如何配置 FreeMarker 作为视图技术:
The following example shows how to configure the same in XML:
以下示例展示了如何在 XML 中配置相同内容:
Alternatively, you can also declare the FreeMarkerConfigurer bean for full control over all properties, as the
following example shows:
另外,您也可以声明 FreeMarkerConfigurer bean 以完全控制所有属性,如下例所示:
Your templates need to be stored in the directory specified by the FreeMarkerConfigurer shown in the preceding
example. Given the preceding configuration, if your controller returns a view name of welcome, the resolver looks for
the /WEB-INF/freemarker/welcome.ftl template.
您的模板需要存储在前面示例中显示的 FreeMarkerConfigurer 指定的目录中。根据前面的配置,如果您的控制器返回的视图名为
welcome ,则解析器会查找 /WEB-INF/freemarker/welcome.ftl 模板。
FreeMarker 配置
You can pass FreeMarker 'Settings' and 'SharedVariables' directly to the FreeMarker Configuration object (which is
managed by Spring) by setting the appropriate bean properties on the FreeMarkerConfigurer bean. The
freemarkerSettings property requires a java.util.Properties object, and the freemarkerVariables property requires
a java.util.Map. The following example shows how to use a FreeMarkerConfigurer:
您可以通过在 FreeMarkerConfigurer bean 上设置适当的 bean 属性,将 FreeMarker 的'Settings'和'SharedVariables'直接传递给
FreeMarker 的 Configuration 对象(由 Spring 管理)。 freemarkerSettings 属性需要一个 java.util.Properties 对象,而
freemarkerVariables 属性需要一个 java.util.Map 。以下示例展示了如何使用 FreeMarkerConfigurer :
See the FreeMarker documentation for details of settings and variables as they apply to the Configuration object.
查看 FreeMarker 文档以获取有关设置和变量的详细信息,这些信息适用于 Configuration 对象。
Spring provides a tag library for use in JSPs that contains, among others, a <spring:bind/> element. This element
primarily lets forms display values from form-backing objects and show the results of failed validations from a
Validator in the web or business tier. Spring also has support for the same functionality in FreeMarker, with
additional convenience macros for generating form input elements themselves.
Spring 为 JSP 提供了标签库,其中包含 <spring:bind/> 元素等。此元素主要允许表单显示表单后端对象中的值,并显示来自 Web
或业务层的 Validator 中失败的验证结果。Spring 还支持 FreeMarker 中的相同功能,并提供了生成表单输入元素的便利宏。
A standard set of macros are maintained within the spring-webmvc.jar file for FreeMarker, so they are always available
to a suitably configured application.
一套标准的宏在 FreeMarker 的 spring-webmvc.jar 文件中维护,因此它们始终可供适当配置的应用程序使用。
Some of the macros defined in the Spring templating libraries are considered internal (private), but no such scoping
exists in the macro definitions, making all macros visible to calling code and user templates.
一些在 Spring
模板库中定义的宏被认为是内部的(私有的),但在宏定义中不存在这样的作用域,使得所有宏都对调用代码和用户模板可见。
The following sections concentrate only on the macros you need to directly call from within your templates. If you wish
to view the macro code directly, the file is called spring.ftl and is in the
org.springframework.web.servlet.view.freemarker package.
以下章节仅关注您需要在模板中直接调用的宏。如果您想直接查看宏代码,文件名为 spring.ftl ,位于
org.springframework.web.servlet.view.freemarker 包中。
In your HTML forms based on FreeMarker templates that act as a form view for a Spring MVC controller, you can use code
similar to the next example to bind to field values and display error messages for each input field in similar fashion
to the JSP equivalent.
在基于 FreeMarker 模板的 HTML 表单中,这些表单作为 Spring MVC 控制器的表单视图,您可以使用类似于以下示例的代码来绑定字段值,并以类似
JSP 等价物的形式显示每个输入字段的错误消息。
The following example shows a personForm view:
以下示例显示了一个 personForm 视图:
<@spring.bind> requires a 'path' argument, which consists of the name of your command object (it is 'command', unless
you changed it in your controller configuration) followed by a period and the name of the field on the command object to
which you wish to bind.
<@spring.bind> 需要一个 'path' 参数,该参数由你的命令对象名称(默认为 '
command',除非你在控制器配置中更改了它)后跟一个点,以及你希望绑定到命令对象上的字段名称组成。
You can also use nested fields, such as command.address.street. The bind macro assumes the default HTML escaping
behavior specified by the ServletContext parameter defaultHtmlEscape in web.xml.
您还可以使用嵌套字段,例如 command.address.street 。 bind 宏假定由 web.xml 中的 ServletContext 参数
defaultHtmlEscape 指定的默认 HTML 转义行为。
An alternative form of the macro called <@spring.bindEscaped> takes a second argument that explicitly specifies
whether HTML escaping should be used in the status error messages or values. You can set it to true or false as
required. Additional form handling macros simplify the use of HTML escaping, and you should use these macros wherever
possible. They are explained in the next section.
宏的另一种形式称为 <@spring.bindEscaped> ,它接受一个额外的参数,该参数明确指定是否在状态错误消息或值中使用 HTML
转义。您可以根据需要将其设置为 true 或 false 。额外的表单处理宏简化了 HTML 转义的使用,您应尽可能使用这些宏。它们将在下一节中解释。
Additional convenience macros for FreeMarker simplify both binding and form generation (including validation error
display).
额外方便的宏简化了 FreeMarker 的绑定和表单生成(包括验证错误显示)。
It is never necessary to use these macros to generate form input fields, and you can mix and match them with simple HTML
or direct calls to the Spring bind macros that we highlighted previously.
这些宏生成表单输入字段从不必要,您可以将它们与简单的 HTML 或直接调用我们之前强调的 Spring 绑定宏混合搭配。
The following table of available macros shows the FreeMarker Template (FTL) definitions and the parameter list that each
takes:
以下表格显示了可用的宏及其 FreeMarker 模板(FTL)定义和每个宏所接受的参数列表:
Table 6. Table of macro definitions
表 6. 宏定义表
macro 宏
FTL definition FTL 定义
message (output a string from a resource bundle based on the code parameter)
message (根据代码参数从资源包中输出一个字符串)
<@spring.message code/>
messageText (output a string from a resource bundle based on the code parameter, falling back to the value of the
default parameter)
messageText (根据代码参数从资源包中输出字符串,如果失败则回退到默认参数的值)
<@spring.messageText code, text/>
<@spring.messageText 代码,文本/>
url (prefix a relative URL with the application’s context root)
url (在相对 URL 前缀应用上下文根)
<@spring.url relativeUrl/>
<@spring.url 相对 URL/>
formInput (standard input field for gathering user input)
formInput (用于收集用户输入的标准输入字段)
<@spring.formInput path, attributes, fieldType/>
<@spring.formInput 路径, 属性, 字段类型/>
formHiddenInput (hidden input field for submitting non-user input)
formHiddenInput (提交非用户输入的隐藏输入字段)
<@spring.formHiddenInput path, attributes/>
<@spring.formHiddenInput 路径,属性/>
formPasswordInput (standard input field for gathering passwords. Note that no value is ever populated in fields of
this type.)
formPasswordInput (用于收集密码的标准输入字段。请注意,此类字段的值永远不会被填充。)
<@spring.formPasswordInput path, attributes/>
<@spring.formPasswordInput 路径,属性/>
formTextarea (large text field for gathering long, freeform text input)
formTextarea (用于收集长文本的自由格式输入字段)
<@spring.formTextarea path, attributes/>
<@spring.formTextarea 路径,属性/>
formSingleSelect (drop down box of options that let a single required value be selected)
formSingleSelect (下拉选项框,允许选择单个必填值)
<@spring.formSingleSelect path, options, attributes/>
<@spring.formSingleSelect 路径, 选项, 属性/>
formMultiSelect (a list box of options that let the user select 0 or more values)
formMultiSelect (一个允许用户选择 0 个或多个值的选项列表框)
<@spring.formMultiSelect path, options, attributes/>
<@spring.formMultiSelect 路径,选项,属性/>
formRadioButtons (a set of radio buttons that let a single selection be made from the available choices)
formRadioButtons (一组单选按钮,允许从可用选项中选择一个)
<@spring.formRadioButtons path, options separator, attributes/>
<@spring.formRadioButtons 路径,选项分隔符,属性/>
formCheckboxes (a set of checkboxes that let 0 or more values be selected)
formCheckboxes (一组允许选择 0 个或多个值的复选框)
<@spring.formCheckboxes path, options, separator, attributes/>
<@spring.formCheckboxes 路径, 选项, 分隔符, 属性/>
formCheckbox (a single checkbox)formCheckbox (单选框)
<@spring.formCheckbox path, attributes/>
<@spring.formCheckbox 路径,属性/>
showErrors (simplify display of validation errors for the bound field)
showErrors (简化绑定字段的验证错误显示)
<@spring.showErrors separator, classOrStyle/>
<@spring.showErrors 分隔符,classOrStyle/>
In FreeMarker templates, formHiddenInput and formPasswordInput are not actually required, as you can use the normal
formInput macro, specifying hidden or password as the value for the fieldType parameter.
在 FreeMarker 模板中, formHiddenInput 和 formPasswordInput 实际上不是必需的,因为您可以使用正常的 formInput 宏,指定
hidden 或 password 作为 fieldType 参数的值。
The parameters to any of the above macros have consistent meanings:
上述宏的参数具有一致的含义:
path: The name of the field to bind to (ie "command.name")
path : 绑定的字段名称(即 "command.name")
options: A Map of all the available values that can be selected from in the input field. The keys to the map
represent the values that are POSTed back from the form and bound to the command object.
options :在输入字段中可以选择的所有可用值的集合。映射的键代表从表单中 POST 回并绑定到命令对象的值。
Map objects stored against the keys are the labels displayed on the form to the user and may be different from the
corresponding values posted back by the form. Usually, such a map is supplied as reference data by the controller. You
can use any Map implementation, depending on required behavior. For strictly sorted maps, you can use a
SortedMap (such as a TreeMap) with a suitable Comparator and, for arbitrary Maps that should return values in
insertion order, use a LinkedHashMap or a LinkedMap from commons-collections.
映射到键的对象是用户在表单上显示的标签,可能与表单返回的相应值不同。通常,此类映射由控制器作为参考数据提供。您可以根据所需行为使用任何
Map 实现。对于严格排序的映射,您可以使用带有合适 Comparator 的 SortedMap (例如 TreeMap ),而对于应按插入顺序返回值的任意映射,请使用
commons-collections 中的 LinkedHashMap 或 LinkedMap 。
separator: Where multiple options are available as discreet elements (radio buttons or checkboxes), the sequence of
characters used to separate each one in the list (such as <br>).
separator :当有多个选项作为离散元素(单选按钮或复选框)可用时,用于在列表中分隔每个元素的字符序列(如 <br> )。
attributes: An additional string of arbitrary tags or text to be included within the HTML tag itself. This string is
echoed literally by the macro. For example, in a textarea field, you may supply attributes (such as 'rows="5" cols="
60"'), or you could pass style information such as 'style="border:1px solid silver"'.
attributes :在 HTML 标签内部包含的任意标签或文本的附加字符串。该字符串由宏原样输出。例如,在 textarea
字段中,您可以提供属性(如'rows="5" cols="60"'),或者传递样式信息,如'style="border:1px solid silver"'。
classOrStyle: For the showErrors macro, the name of the CSS class that the span element that wraps each error
uses. If no information is supplied (or the value is empty), the errors are wrapped in <b></b> tags.
classOrStyle : 对于 showErrors 宏,用于包装每个错误的 span 元素的 CSS 类名。如果没有提供信息(或值为空),错误将包裹在
<b></b> 标签中。
The following sections outline examples of the macros.
以下章节概述了宏的示例。
(#mvc-views-form-macros-input)Input Fields 输入字段
The formInput macro takes the path parameter (command.name) and an additional attributes parameter (which is
empty in the upcoming example). The macro, along with all other form generation macros, performs an implicit Spring bind
on the path parameter. The binding remains valid until a new bind occurs, so the showErrors macro does not need to
pass the path parameter again — it operates on the field for which a binding was last created.
formInput 宏接受 path 参数( command.name )以及一个额外的 attributes 参数(在即将到来的示例中为空)。该宏以及所有其他表单生成宏都会对路径参数执行隐式
Spring 绑定。绑定在新的绑定发生之前保持有效,因此 showErrors 宏不需要再次传递路径参数——它操作的是最后创建绑定的字段。
The showErrors macro takes a separator parameter (the characters that are used to separate multiple errors on a given
field) and also accepts a second parameter — this time, a class name or style attribute. Note that FreeMarker can
specify default values for the attributes parameter.
showErrors 宏接受一个分隔符参数(用于在给定字段上分隔多个错误的字符)并接受第二个参数——这次是一个类名或样式属性。请注意,FreeMarker
可以为属性参数指定默认值。
The following example shows how to use the formInput and showErrors macros:
以下示例展示了如何使用 formInput 和 showErrors 宏:
The next example shows the output of the form fragment, generating the name field and displaying a validation error
after the form was submitted with no value in the field. Validation occurs through Spring’s Validation framework.
下一个示例显示了表单片段的输出,生成名称字段并在表单提交且字段无值后显示验证错误。验证通过 Spring 的验证框架进行。
The generated HTML resembles the following example:
生成的 HTML 类似于以下示例:
The formTextarea macro works the same way as the formInput macro and accepts the same parameter list. Commonly, the
second parameter (attributes) is used to pass style information or rows and cols attributes for the textarea.
formTextarea 宏与 formInput 宏的工作方式相同,接受相同的参数列表。通常,第二个参数( attributes )用于传递样式信息或
rows 和 cols 属性给 textarea 。
(#mvc-views-form-macros-select)Selection Fields 选择字段
You can use four selection field macros to generate common UI value selection inputs in your HTML forms:
您可以使用四个选择字段宏来生成 HTML 表单中的常见 UI 值选择输入:
formSingleSelect
formMultiSelect
formRadioButtons
formCheckboxes
Each of the four macros accepts a Map of options that contains the value for the form field and the label that
corresponds to that value. The value and the label can be the same.
每个宏都接受一个包含表单字段值及其对应标签的选项集合 Map 。值和标签可以是相同的。
The next example is for radio buttons in FTL. The form-backing object specifies a default value of 'London' for this
field, so no validation is necessary.
下一个示例是关于 FTL 中的单选按钮。表单后端对象为该字段指定了默认值“伦敦”,因此无需验证。
When the form is rendered, the entire list of cities to choose from is supplied as reference data in the model under the
name 'cityMap'. The following listing shows the example:
当表单渲染时,可供选择的整个城市列表作为名为 'cityMap' 的参考数据存储在模型中。以下列表展示了示例:
The preceding listing renders a line of radio buttons, one for each value in cityMap, and uses a separator of "". No
additional attributes are supplied (the last parameter to the macro is missing). The cityMap uses the same String
for each key-value pair in the map. The map’s keys are what the form actually submits as POST request parameters. The
map values are the labels that the user sees. In the preceding example, given a list of three well known cities and a
default value in the form backing object, the HTML resembles the following:
前一个列表渲染了一行单选按钮,每个值对应一个,并使用 "" 作为分隔符。没有提供额外的属性(宏的最后一个参数缺失)。 cityMap
在映射中的每个键值对中使用相同的 String 。映射的键是表单实际提交的 POST
请求参数。映射的值是用户看到的标签。在前面的例子中,给定三个知名城市列表和一个表单背对象中的默认值,HTML 类似于以下内容:
If your application expects to handle cities by internal codes (for example), you can create the map of codes with
suitable keys, as the following example shows:
如果您的应用程序预期通过内部代码(例如)处理城市,您可以创建具有合适键的代码映射,如下例所示:
The code now produces output where the radio values are the relevant codes, but the user still sees the more
user-friendly city names, as follows:
代码现在生成输出,其中单选按钮的值是相关代码,但用户仍然看到更友好的城市名称,如下所示:
Default usage of the form macros described earlier results in HTML elements that are HTML 4.01 compliant and that use
the default value for HTML escaping defined in your web.xml file, as used by Spring’s bind support. To make the
elements be XHTML compliant or to override the default HTML escaping value, you can specify two variables in your
template (or in your model, where they are visible to your templates).
默认情况下,之前描述的表单宏的使用会导致生成符合 HTML 4.01 规范的 HTML 元素,并使用在您的 web.xml 文件中定义的默认 HTML
转义值,正如 Spring 的绑定支持所使用的。为了使元素符合 XHTML 规范或覆盖默认的 HTML
转义值,您可以在模板中(或在模型中,使它们对模板可见)指定两个变量。
The advantage of specifying them in the templates is that they can be changed to different values later in the template
processing to provide different behavior for different fields in your form.
模板中指定它们的优点是,在模板处理过程中可以稍后更改它们的值,为表单中的不同字段提供不同的行为。
To switch to XHTML compliance for your tags, specify a value of true for a model or context variable named
xhtmlCompliant, as the following example shows:
为了使您的标签符合 XHTML 规范,请为名为 xhtmlCompliant 的模型或上下文变量指定值为 true ,如下例所示:
After processing this directive, any elements generated by the Spring macros are now XHTML compliant.
在处理此指令后,由 Spring 宏生成的任何元素现在都符合 XHTML 规范。
In similar fashion, you can specify HTML escaping per field, as the following example shows:
以类似的方式,您可以按字段指定 HTML 转义,如下例所示:
The Groovy Markup Template Engine is primarily
aimed at generating XML-like markup (XML, XHTML, HTML5, and others), but you can use it to generate any text-based
content. The Spring Framework has a built-in integration for using Spring MVC with Groovy Markup.
Groovy 标记模板引擎主要用于生成类似 XML 的标记(XML、XHTML、HTML5 等),但您也可以用它来生成任何基于文本的内容。Spring
框架内置了对使用 Spring MVC 和 Groovy 标记的集成。
The Groovy Markup Template engine requires Groovy 2.3.1+.
The following example shows how to configure the Groovy Markup Template Engine:
以下示例展示了如何配置 Groovy 标记模板引擎:
The following example shows how to configure the same in XML:
以下示例展示了如何在 XML 中配置相同内容:
Unlike traditional template engines, Groovy Markup relies on a DSL that uses a builder syntax. The following example
shows a sample template for an HTML page:
与传统模板引擎不同,Groovy Markup 依赖于使用构建器语法的 DSL。以下示例展示了 HTML 页面的一个示例模板:
The Spring Framework has a built-in integration for using Spring MVC with any templating library that can run on top of
the JSR-223 Java scripting engine. We have tested the following templating
libraries on different script engines:
Spring 框架内置了对使用 Spring MVC 与任何可在 JSR-223 Java 脚本引擎上运行的模板库的集成。我们已在不同的脚本引擎上测试了以下模板库:
Scripting Library 脚本库
Scripting Engine 脚本引擎
Kotlin Script templating
Kotlin 脚本模板
The basic rule for integrating any other script engine is that it must implement the ScriptEngine and Invocable
interfaces.
任何其他脚本引擎集成的基本规则是它必须实现 ScriptEngine 和 Invocable 接口。
You need to have the script engine on your classpath, the details of which vary by script engine:
您需要在类路径上拥有脚本引擎,具体细节因脚本引擎而异:
The Nashorn JavaScript engine is provided with Java 8+. Using the latest
update release available is highly recommended.
Nashorn JavaScript 引擎从 Java 8+版本开始提供。强烈建议使用最新的更新版本。
JRuby should be added as a dependency for Ruby support.
JRuby 应作为依赖项添加以支持 Ruby。
Jython should be added as a dependency for Python support.
Jython 应该作为依赖项添加以支持 Python。
org.jetbrains.kotlin:kotlin-script-util dependency and a META-INF/services/javax.script.ScriptEngineFactory file
containing a org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory line should be added for
Kotlin script support. See this example for more details.
org.jetbrains.kotlin:kotlin-script-util 依赖项以及一个包含 META-INF/services/javax.script.ScriptEngineFactory 行的
org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory 文件应添加以支持 Kotlin
脚本。请参阅此示例以获取更多详细信息。
You need to have the script templating library. One way to do that for JavaScript is
through WebJars.
您需要拥有脚本模板库。对于 JavaScript 来说,一种方法是通过 WebJars 来实现。
You can declare a ScriptTemplateConfigurer bean to specify the script engine to use, the script files to load, what
function to call to render templates, and so on. The following example uses Mustache templates and the Nashorn
JavaScript engine:
您可以声明一个 ScriptTemplateConfigurer bean 来指定要使用的脚本引擎、要加载的脚本文件、调用以渲染模板的功能等。以下示例使用
Mustache 模板和 Nashorn JavaScript 引擎:
The following example shows the same arrangement in XML:
以下示例显示了相同的 XML 排列:
The controller would look no different for the Java and XML configurations, as the following example shows:
控制器在 Java 和 XML 配置中看起来不会有任何区别,如下例所示:
The following example shows the Mustache template:
以下示例显示了 Mustache 模板:
The render function is called with the following parameters:
渲染函数使用以下参数调用:
String template: The template content
String template : 模板内容
Map model: The view model
Map model : 视图模型
RenderingContext renderingContext: The
RenderingContext
that gives access to the application context, the locale, the template loader, and the URL (since 5.0)
RenderingContext renderingContext : 提供对应用程序上下文、区域设置、模板加载器和 URL(自 5.0 以来)访问的
RenderingContext
Mustache.render() is natively compatible with this signature, so you can call it directly.
Mustache.render() 与此签名本机兼容,因此您可以直接调用它。
If your templating technology requires some customization, you can provide a script that implements a custom render
function. For example, Handlerbars needs to compile templates before using them and
requires a polyfill to emulate some browser facilities that are not available
in the server-side script engine.
如果您的模板技术需要一些定制,您可以提供一个实现自定义渲染函数的脚本。例如,Handlebars 需要在使用模板之前编译它们,并且需要一个
polyfill 来模拟一些在服务器端脚本引擎中不可用的浏览器功能。
The following example shows how to do so:
以下示例展示了如何这样做:
Setting the sharedEngine property to false is required when using non-thread-safe script engines with templating
libraries not designed for concurrency, such as Handlebars or React running on Nashorn. In that case, Java SE 8 update
60 is required, due to this bug, but it is generally recommended to
use a recent Java SE patch release in any case.
设置 sharedEngine 属性为 false 是使用非线程安全的脚本引擎与未设计用于并发的模板库(如 Handlebars 或 Nashorn 上运行的
React)时必需的。在这种情况下,需要 Java SE 8 更新 60,由于这个错误,但无论如何,通常推荐使用最近的 Java SE 补丁版本。
polyfill.js defines only the window object needed by Handlebars to run properly, as follows:
polyfill.js 仅定义 Handlebars 正常运行所需的 window 对象,如下所示:
This basic render.js implementation compiles the template before using it. A production-ready implementation should
also store any reused cached templates or pre-compiled templates.
这个基本的 render.js 实现在使用之前会编译模板。一个生产就绪的实现还应存储任何重复使用的缓存模板或预编译模板。
You can do so on the script side (and handle any customization you need — managing template engine configuration, for
example). The following example shows how to do so:
您可以在脚本端这样做(并处理您需要的任何自定义——例如管理模板引擎配置)。以下示例展示了如何操作:
Check out the Spring Framework unit
tests, Java,
and resources,
for more configuration examples.
查看 Spring 框架单元测试、Java 和资源,以获取更多配置示例。
1.10.5. JSP 和 JSTL
The Spring Framework has a built-in integration for using Spring MVC with JSP and JSTL.
Spring 框架内置了对使用 Spring MVC 与 JSP 和 JSTL 集成的支持。
When developing with JSPs, you typically declare an InternalResourceViewResolver bean.
在开发 JSP 时,通常声明一个 InternalResourceViewResolver Bean。
InternalResourceViewResolver can be used for dispatching to any Servlet resource but in particular for JSPs. As a best
practice, we strongly encourage placing your JSP files in a directory under the 'WEB-INF' directory so there can be no
direct access by clients.
InternalResourceViewResolver 可以用于调度到任何 Servlet 资源,尤其是 JSP。作为最佳实践,我们强烈建议将您的 JSP 文件放置在
'WEB-INF' 目录下的一个目录中,以便客户端无法直接访问。
When using the JSP Standard Tag Library (JSTL) you must use a special view class, the JstlView, as JSTL needs some
preparation before things such as the I18N features can work.
当使用 JSP 标准标签库(JSTL)时,必须使用一个特殊的视图类,即 JstlView ,因为 JSTL 在 I18N 功能等事物工作之前需要一些准备。
Spring 的 JSP 标签库
Spring provides data binding of request parameters to command objects, as described in earlier chapters. To facilitate
the development of JSP pages in combination with those data binding features, Spring provides a few tags that make
things even easier.
Spring 提供了将请求参数绑定到命令对象的数据绑定,如前几章所述。为了便于与这些数据绑定功能结合开发 JSP 页面,Spring
提供了一些标签,使事情变得更加简单。
All Spring tags have HTML escaping features to enable or disable escaping of characters.
所有 Spring 标签都具有 HTML 转义功能,以启用或禁用字符的转义。
The spring.tld tag library descriptor (TLD) is included in the spring-webmvc.jar. For a comprehensive reference on
individual tags, browse
the API reference
or see the tag library description.
spring.tld 标签库描述符(TLD)包含在 spring-webmvc.jar 中。有关各个标签的全面参考,请浏览 API 参考或查看标签库描述。
Spring 的表单标签库
As of version 2.0, Spring provides a comprehensive set of data binding-aware tags for handling form elements when using
JSP and Spring Web MVC.
截至 2.0 版本,Spring 为使用 JSP 和 Spring Web MVC 处理表单元素提供了全面的数据绑定感知标签集。
Each tag provides support for the set of attributes of its corresponding HTML tag counterpart, making the tags familiar
and intuitive to use. The tag-generated HTML is HTML 4.01/XHTML 1.0 compliant.
每个标签都为其对应的 HTML 标签提供支持,使标签使用起来既熟悉又直观。标签生成的 HTML 符合 HTML 4.01/XHTML 1.0 规范。
Unlike other form/input tag libraries, Spring’s form tag library is integrated with Spring Web MVC, giving the tags
access to the command object and reference data your controller deals with.
与其他表单/输入标签库不同,Spring 的表单标签库与 Spring Web MVC 集成,使标签能够访问控制器处理的命令对象和引用数据。
As we show in the following examples, the form tags make JSPs easier to develop, read, and maintain.
如下所示,表单标签使得 JSP 的开发、阅读和维护更加容易。
We go through the form tags and look at an example of how each tag is used. We have included generated HTML snippets
where certain tags require further commentary.
我们遍历表单标签,并查看每个标签的用法示例。对于需要进一步说明的标签,我们包含了生成的 HTML 片段。
The form tag library comes bundled in spring-webmvc.jar. The library descriptor is called spring-form.tld.
表单标签库包含在 spring-webmvc.jar 中。库描述符称为 spring-form.tld 。
To use the tags from this library, add the following directive to the top of your JSP page:
为了使用此库中的标签,请将以下指令添加到您的 JSP 页面顶部:
where form is the tag name prefix you want to use for the tags from this library.
form 是您想用于此库中标签的标签名前缀。
This tag renders an HTML 'form' element and exposes a binding path to inner tags for binding. It puts the command object
in the PageContext so that the command object can be accessed by inner tags. All the other tags in this library are
nested tags of the form tag.
此标签渲染 HTML '表单'元素,并暴露绑定路径到内部标签以进行绑定。它将命令对象放入 PageContext
中,以便内部标签可以访问命令对象。此库中的所有其他标签都是 form 标签的嵌套标签。
Assume that we have a domain object called User. It is a JavaBean with properties such as firstName and lastName.
We can use it as the form-backing object of our form controller, which returns form.jsp. The following example shows
what form.jsp could look like:
假设我们有一个名为 User 的域对象。它是一个具有 firstName 和 lastName 等属性的 JavaBean。我们可以将其用作表单控制器的表单后端对象,它返回
form.jsp 。以下示例显示了 form.jsp 可能的样子:
The firstName and lastName values are retrieved from the command object placed in the PageContext by the page
controller. Keep reading to see more complex examples of how inner tags are used with the form tag.
从页面控制器放置在 PageContext 中的命令对象中检索 firstName 和 lastName 值。继续阅读以查看使用 form
标签的内部标签的更复杂示例。
The following listing shows the generated HTML, which looks like a standard form:
以下列表显示了生成的 HTML,看起来像是一个标准表单:
The preceding JSP assumes that the variable name of the form-backing object is command. If you have put the
form-backing object into the model under another name (definitely a best practice), you can bind the form to the named
variable, as the following example shows:
前一个 JSP 假设表单后端对象的变量名为 command 。如果您已将表单后端对象放入模型中并使用另一个名称(这绝对是一个最佳实践),则可以将表单绑定到该命名变量,如下例所示:
input Taginput 标签This tag renders an HTML input element with the bound value and type='text' by default. For an example of this tag,
see The Form Tag. You can also use HTML5-specific types, such as email, tel,
date, and others.
此标签以绑定值和默认的 type='text' 渲染 HTML input 元素。有关此标签的示例,请参阅表单标签。您还可以使用 HTML5 特定的类型,例如
email 、 tel 、 date 等。
checkbox Tagcheckbox 标签This tag renders an HTML input tag with the type set to checkbox.
此标签渲染一个 HTML input 标签,其中 type 设置为 checkbox 。
Assume that our User has preferences such as newsletter subscription and a list of hobbies. The following example
shows the Preferences class:
假设我们的 User 有如订阅通讯和爱好列表等偏好。以下示例显示了 Preferences 类:
The corresponding form.jsp could then resemble the following:
相应的 form.jsp 可能类似于以下内容:
There are three approaches to the checkbox tag, which should meet all your checkbox needs.
有三种方法处理 checkbox 标签,可以满足您所有的复选框需求。
Approach One: When the bound value is of type java.lang.Boolean, the input(checkbox) is marked as checked if the
bound value is true. The value attribute corresponds to the resolved value of the setValue(Object) value
property.
方法一:当绑定值为类型 java.lang.Boolean 时,如果绑定值为 true ,则 input(checkbox) 被标记为 checked 。 value
属性对应于 setValue(Object) 值属性的解析值。
Approach Two: When the bound value is of type array or java.util.Collection, the input(checkbox) is marked as
checked if the configured setValue(Object) value is present in the bound Collection.
方法二:当绑定值类型为 array 或 java.util.Collection 时,如果配置的 setValue(Object) 值存在于绑定的 Collection
中,则 input(checkbox) 被标记为 checked 。
Approach Three: For any other bound value type, the input(checkbox) is marked as checked if the configured
setValue(Object) is equal to the bound value.
方法三:对于任何其他有界值类型,如果配置的 setValue(Object) 等于有界值,则 input(checkbox) 被标记为 checked 。
Note that, regardless of the approach, the same HTML structure is generated. The following HTML snippet defines some
checkboxes:
请注意,无论采用何种方法,都会生成相同的 HTML 结构。以下 HTML 片段定义了一些复选框:
You might not expect to see the additional hidden field after each checkbox.
您可能不会期望在每个复选框后面看到额外的隐藏字段。
When a checkbox in an HTML page is not checked, its value is not sent to the server as part of the HTTP request
parameters once the form is submitted, so we need a workaround for this quirk in HTML for Spring form data binding to
work. The checkbox tag follows the existing Spring convention of including a hidden parameter prefixed by an
underscore (_) for each checkbox. By doing this, you are effectively telling Spring that “the checkbox was visible in
the form, and I want my object to which the form data binds to reflect the state of the checkbox, no matter what.”
当 HTML 页面中的复选框未选中时,一旦表单提交,其值就不会作为 HTTP 请求参数的一部分发送到服务器,因此我们需要为 HTML 中的
Spring 表单数据绑定工作提供一个解决方案。 checkbox 标签遵循现有的 Spring 约定,为每个复选框包含一个以下划线( _
)为前缀的隐藏参数。通过这样做,你实际上是在告诉 Spring,“复选框在表单中可见,并且我希望我的对象能够反映复选框的状态,无论是什么。”
checkboxes Tagcheckboxes 标签This tag renders multiple HTML input tags with the type set to checkbox.
此标签渲染多个 HTML input 标签,其中 type 设置为 checkbox 。
This section build on the example from the previous checkbox tag section. Sometimes, you prefer not to have to list
all the possible hobbies in your JSP page. You would rather provide a list at runtime of the available options and pass
that in to the tag. That is the purpose of the checkboxes tag. You can pass in an Array, a List, or a Map that
contains the available options in the items property. Typically, the bound property is a collection so that it can
hold multiple values selected by the user. The following example shows a JSP that uses this tag:
本节基于上一节 checkbox 标签示例构建。有时,您可能不想在您的 JSP 页面上列出所有可能的爱好。您更愿意在运行时提供一个选项列表并将其传递给标签。这就是
checkboxes 标签的目的。您可以通过传递一个 Array 、一个 List 或一个 Map 来实现这一点,其中包含在 items
属性中的可用选项。通常,绑定属性是一个集合,以便它可以存储用户选择的多个值。以下示例展示了使用此标签的 JSP:
This example assumes that the interestList is a List available as a model attribute that contains strings of the
values to be selected from. If you use a Map, the map entry key is used as the value, and the map entry’s value is
used as the label to be displayed. You can also use a custom object where you can provide the property names for the
value by using itemValue and the label by using itemLabel.
此示例假设 interestList 是一个作为模型属性可用的 List ,其中包含要选择的值的字符串。如果您使用 Map
,则映射条目的键用作值,映射条目的值用作要显示的标签。您还可以使用自定义对象,通过使用 itemValue 提供值属性名称,通过使用
itemLabel 提供标签。
radiobutton Tagradiobutton 标签This tag renders an HTML input element with the type set to radio.
此标签渲染一个 HTML input 元素,其 type 设置为 radio 。
A typical usage pattern involves multiple tag instances bound to the same property but with different values, as the
following example shows:
一个典型的使用模式涉及多个绑定到同一属性但具有不同值的标签实例,如下例所示:
radiobuttons Tagradiobuttons 标签This tag renders multiple HTML input elements with the type set to radio.
此标签渲染多个 HTML input 元素,其中 type 设置为 radio 。
As with the checkboxes tag, you might want to pass in the available options
as a runtime variable. For this usage, you can use the radiobuttons tag. You pass in an Array, a List, or a Map
that contains the available options in the items property. If you use a Map, the map entry key is used as the value
and the map entry’s value are used as the label to be displayed. You can also use a custom object where you can provide
the property names for the value by using itemValue and the label by using itemLabel, as the following example
shows:
与 checkboxes 标签一样,您可能希望将可用选项作为运行时变量传递。对于这种用法,您可以使用 radiobuttons 标签。您传递一个
Array 、一个 List 或一个 Map ,其中包含在 items 属性中的可用选项。如果您使用 Map
,则映射条目的键用作值,映射条目的值用作要显示的标签。您还可以使用自定义对象,其中您可以通过使用 itemValue 提供值的属性名称,通过使用
itemLabel 提供标签,如下例所示:
password Tagpassword 标签This tag renders an HTML input tag with the type set to password with the bound value.
此标签渲染一个类型设置为 password 的 HTML input 标签,并绑定相应的值。
Note that, by default, the password value is not shown. If you do want the password value to be shown, you can set the
value of the showPassword attribute to true, as the following example shows:
请注意,默认情况下,密码值不会显示。如果您希望显示密码值,可以将 showPassword 属性的值设置为 true ,如下例所示:
select Tagselect 标签This tag renders an HTML 'select' element. It supports data binding to the selected option as well as the use of nested
option and options tags.
此标签渲染 HTML 'select'元素。它支持将数据绑定到选定的选项,以及使用嵌套的 option 和 options 标签。
Assume that a User has a list of skills. The corresponding HTML could be as follows:
假设一个 User 有一个技能列表。相应的 HTML 可能如下所示:
If the User’s skill are in Herbology, the HTML source of the 'Skills' row could be as follows:
如果 User’s 技能属于植物学,'技能'行的 HTML 源代码可能如下所示:
option Tagoption 标签This tag renders an HTML option element. It sets selected, based on the bound value. The following HTML shows
typical output for it:
此标签渲染 HTML option 元素。它根据绑定值设置 selected 。以下 HTML 显示了它的典型输出:
If the User’s house was in Gryffindor, the HTML source of the 'House' row would be as follows:
如果 User’s 房子在格兰芬多,'House'行的 HTML 源代码如下:
1
Note the addition of a selected attribute.
注意添加了 selected 属性。
options Tagoptions 标签This tag renders a list of HTML option elements. It sets the selected attribute, based on the bound value. The
following HTML shows typical output for it:
此标签渲染 HTML option 元素的列表。它根据绑定值设置 selected 属性。以下 HTML 显示了它的典型输出:
If the User lived in the UK, the HTML source of the 'Country' row would be as follows:
如果 User 居住在英国,'国家'行的 HTML 源代码如下:
1
Note the addition of a selected attribute.
注意添加了 selected 属性。
As the preceding example shows, the combined usage of an option tag with the options tag generates the same standard
HTML but lets you explicitly specify a value in the JSP that is for display only (where it belongs), such as the default
string in the example: "-- Please Select".
正如前面的示例所示, option 标签与 options 标签的组合使用生成相同的标准 HTML,但允许您在 JSP
中明确指定仅用于显示的值(它应该属于那里),例如示例中的默认字符串:“-- 请选择”。
The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel
refer to bean properties of those item objects, if specified. Otherwise, the item objects themselves are turned into
strings. Alternatively, you can specify a Map of items, in which case the map keys are interpreted as option values
and the map values correspond to option labels. If itemValue or itemLabel (or both) happen to be specified as well,
the item value property applies to the map key, and the item label property applies to the map value.
items 属性通常填充为项目对象的集合或数组。如果指定, itemValue 和 itemLabel
指的是这些项目对象的属性。否则,项目对象本身将被转换为字符串。或者,您可以指定一个项目 Map
,在这种情况下,映射键被解释为选项值,映射值对应于选项标签。如果 itemValue 或 itemLabel
(或两者)也被指定,则项目值属性应用于映射键,项目标签属性应用于映射值。
textarea Tagtextarea 标签This tag renders an HTML textarea element. The following HTML shows typical output for it:
此标签渲染 HTML textarea 元素。以下 HTML 显示了它的典型输出:
hidden Taghidden 标签This tag renders an HTML input tag with the type set to hidden with the bound value. To submit an unbound hidden
value, use the HTML input tag with the type set to hidden. The following HTML shows typical output for it:
此标签渲染一个 HTML input 标签,其中 type 设置为 hidden 的绑定值。要提交未绑定的隐藏值,请使用 HTML input 标签,其中
type 设置为 hidden 。以下 HTML 显示了它的典型输出:
If we choose to submit the house value as a hidden one, the HTML would be as follows:
如果我们选择将 house 值作为隐藏值提交,HTML 将如下所示:
errors Tagerrors 标签This tag renders field errors in an HTML span element. It provides access to the errors created in your controller or
those that were created by any validators associated with your controller.
此标签在 HTML 的 span 元素中渲染字段错误。它提供了访问在您的控制器中创建的错误或由与您的控制器关联的任何验证器创建的错误的方式。
Assume that we want to display all error messages for the firstName and lastName fields once we submit the form. We
have a validator for instances of the User class called UserValidator, as the following example shows:
假设我们希望在提交表单后显示所有关于 firstName 和 lastName 字段的错误信息。我们有一个名为 UserValidator 的验证器,用于
User 类的实例,如下例所示:
The form.jsp could be as follows:
以下可能是 form.jsp 的示例:
If we submit a form with empty values in the firstName and lastName fields, the HTML would be as follows:
如果我们提交一个在 firstName 和 lastName 字段中包含空值的表单,HTML 将如下所示:
What if we want to display the entire list of errors for a given page? The next example shows that the errors tag also
supports some basic wildcarding functionality.
如果我们想显示给定页面的所有错误列表呢?下一个示例显示, errors 标签也支持一些基本的通配符功能。
path="*": Displays all errors.
显示所有错误。
path="lastName": Displays all errors associated with the lastName field.
path="lastName" : 显示与 lastName 字段相关的所有错误。
If path is omitted, only object errors are displayed.
如果省略了 path ,则只显示对象错误。
The following example displays a list of errors at the top of the page, followed by field-specific errors next to the
fields:
以下示例在页面顶部显示错误列表,随后是字段特定的错误位于字段旁边:
The HTML would be as follows:
以下为 HTML 代码:
The spring-form.tld tag library descriptor (TLD) is included in the spring-webmvc.jar. For a comprehensive reference
on individual tags, browse
the API reference
or see the tag library description.
spring-form.tld 标签库描述符(TLD)包含在 spring-webmvc.jar 中。有关各个标签的全面参考,请浏览 API 参考或查看标签库描述。
A key principle of REST is the use of the “Uniform Interface”. This means that all resources (URLs) can be manipulated
by using the same four HTTP methods: GET, PUT, POST, and DELETE. For each method, the HTTP specification defines the
exact semantics.
REST 的关键原则是使用“统一接口”。这意味着所有资源(URL)都可以通过使用相同的四种 HTTP 方法进行操作:GET、PUT、POST 和
DELETE。对于每种方法,HTTP 规范都定义了确切的语义。
For instance, a GET should always be a safe operation, meaning that it has no side effects, and a PUT or DELETE should
be idempotent, meaning that you can repeat these operations over and over again, but the end result should be the
same.
例如,GET 操作始终应该是安全的操作,这意味着它没有副作用,而 PUT 或 DELETE
应该是幂等的,这意味着你可以重复执行这些操作,但最终结果应该是相同的。
While HTTP defines these four methods, HTML only supports two: GET and POST. Fortunately, there are two possible
workarounds: you can either use JavaScript to do your PUT or DELETE, or you can do a POST with the “real” method as an
additional parameter (modeled as a hidden input field in an HTML form).
虽然 HTTP 定义了这四种方法,但 HTML 只支持两种:GET 和 POST。幸运的是,有两种可能的解决方案:您可以使用 JavaScript 来执行 PUT
或 DELETE,或者您可以在 POST 请求中添加一个“真实”方法作为附加参数(在 HTML 表单中模拟为隐藏输入字段)。
Spring’s HiddenHttpMethodFilter uses this latter trick. This filter is a plain Servlet filter and, therefore, it can
be used in combination with any web framework (not just Spring MVC). Add this filter to your web.xml, and a POST with a
hidden method parameter is converted into the corresponding HTTP method request.
Spring 的 HiddenHttpMethodFilter 使用这个后者的技巧。这个过滤器是一个普通的 Servlet 过滤器,因此它可以与任何 Web 框架(不仅仅是
Spring MVC)结合使用。将此过滤器添加到您的 web.xml 中,带有隐藏的 method 参数的 POST 请求将被转换为相应的 HTTP 方法请求。
To support HTTP method conversion, the Spring MVC form tag was updated to support setting the HTTP method. For example,
the following snippet comes from the Pet Clinic sample:
为了支持 HTTP 方法转换,Spring MVC 表单标签已更新以支持设置 HTTP 方法。例如,以下代码片段来自宠物诊所示例:
The preceding example performs an HTTP POST, with the “real” DELETE method hidden behind a request parameter. It is
picked up by the HiddenHttpMethodFilter, which is defined in web.xml, as the following example shows:
前一个示例执行 HTTP POST,将“真正的”DELETE 方法隐藏在请求参数之后。它被 HiddenHttpMethodFilter 捕获,这在 web.xml
中定义,如下例所示:
The following example shows the corresponding @Controller method:
以下示例显示了相应的 @Controller 方法:
The Spring form tag library allows entering dynamic attributes, which means you can enter any HTML5 specific
attributes.
Spring 表单标签库允许输入动态属性,这意味着您可以输入任何 HTML5 特定的属性。
The form input tag supports entering a type attribute other than text. This is intended to allow rendering new HTML5
specific input types, such as email, date, range, and others. Note that entering type='text' is not required,
since text is the default type.
表单 input 标签支持输入除 text 之外的类型属性。这是为了允许渲染新的 HTML5 特定输入类型,例如 email 、 date 、
range 等。请注意,输入 type='text' 不是必需的,因为 text 是默认类型。
You can integrate Tiles - just as any other view technology - in web applications that use Spring. This section
describes, in a broad way, how to do so.
您可以将 Tiles(就像任何其他视图技术一样)集成到使用 Spring 的 Web 应用程序中。本节以广泛的方式描述了如何进行集成。
This section focuses on Spring’s support for Tiles version 3 in the org.springframework.web.servlet.view.tiles3
package.
本节重点介绍 Spring 对 org.springframework.web.servlet.view.tiles3 包中 Tiles 版本 3 的支持。
To be able to use Tiles, you have to add a dependency on Tiles version 3.0.1 or higher
and its transitive dependencies to your project.
要使用 Tiles,您必须将 Tiles 版本 3.0.1 或更高版本及其传递依赖项添加到您的项目中。
To be able to use Tiles, you have to configure it by using files that contain definitions (for basic information on
definitions and other Tiles concepts, see https://tiles.apache.org). In Spring, this is
done by using the TilesConfigurer. The following example ApplicationContext configuration shows how to do so:
要使用 Tiles,您必须通过包含定义的文件来配置它(有关定义和其他 Tiles 概念的基本信息,请参阅 https://tiles.apache.org)。在
Spring 中,这是通过使用 TilesConfigurer 来完成的。以下示例 ApplicationContext 配置显示了如何进行操作:
The preceding example defines five files that contain definitions. The files are all located in the WEB-INF/defs
directory. At initialization of the WebApplicationContext, the files are loaded, and the definitions factory are
initialized. After that has been done, the Tiles included in the definition files can be used as views within your
Spring web application. To be able to use the views, you have to have a ViewResolver as with any other view technology
in Spring: typically a convenient TilesViewResolver.
前一个示例定义了包含定义的五个文件。这些文件都位于 WEB-INF/defs 目录中。在 WebApplicationContext
初始化时,加载这些文件,并初始化定义工厂。完成这些操作后,定义文件中包含的 Tiles 可以作为视图在您的 Spring Web
应用程序中使用。要使用这些视图,您必须像在 Spring 中的任何其他视图技术一样有一个 ViewResolver :通常是一个方便的
TilesViewResolver 。
You can specify locale-specific Tiles definitions by adding an underscore and then the locale, as the following example
shows:
您可以通过添加下划线和地区名称来指定特定地区的 Tiles 定义,如下例所示:
With the preceding configuration, tiles_fr_FR.xml is used for requests with the fr_FR locale, and tiles.xml is
used by default.
使用前面的配置, tiles_fr_FR.xml 用于 fr_FR 区域的请求, tiles.xml 默认使用。
Since underscores are used to indicate locales, we recommended not using them otherwise in the file names for Tiles
definitions.
由于下划线用于表示区域设置,我们建议在 Tiles 定义的文件名中不要使用它们。
UrlBasedViewResolverThe UrlBasedViewResolver instantiates the given viewClass for each view it has to resolve. The following bean
defines a UrlBasedViewResolver:
该 UrlBasedViewResolver 为每个需要解析的视图实例化给定的 viewClass 。以下 bean 定义了一个 UrlBasedViewResolver :
SimpleSpringPreparerFactory andSpringBeanPreparerFactorySimpleSpringPreparerFactory 和 SpringBeanPreparerFactory
As an advanced feature, Spring also supports two special Tiles PreparerFactory implementations. See the Tiles
documentation for details on how to use ViewPreparer references in your Tiles definition files.
作为一个高级功能,Spring 还支持两种特殊的 Tiles PreparerFactory 实现。有关如何在您的 Tiles 定义文件中使用 ViewPreparer
引用的详细信息,请参阅 Tiles 文档。
You can specify SimpleSpringPreparerFactory to autowire ViewPreparer instances based on specified preparer classes,
applying Spring’s container callbacks as well as applying configured Spring BeanPostProcessors. If Spring’s context-wide
annotation configuration has been activated, annotations in ViewPreparer classes are automatically detected and
applied. Note that this expects preparer classes in the Tiles definition files, as the default PreparerFactory does.
您可以通过指定 SimpleSpringPreparerFactory 来自动注入基于指定准备器类的 ViewPreparer 实例,同时应用 Spring 的容器回调以及配置的
Spring BeanPostProcessors。如果 Spring 的全局注解配置已被激活, ViewPreparer 类中的注解将自动检测并应用。请注意,这期望准备器类在
Tiles 定义文件中,就像默认的 PreparerFactory 一样。
You can specify SpringBeanPreparerFactory to operate on specified preparer names (instead of classes), obtaining the
corresponding Spring bean from the DispatcherServlet’s application context.
您可以通过指定 SpringBeanPreparerFactory 来操作指定的准备者名称(而不是类),从 DispatcherServlet 的应用上下文中获取相应的
Spring Bean。
The full bean creation process is in the control of the Spring application context in this case, allowing for the use of
explicit dependency injection configuration, scoped beans, and so on.
整个 Bean 创建过程由本例中的 Spring 应用上下文控制,允许使用显式依赖注入配置、作用域 Bean 等。
Note that you need to define one Spring bean definition for each preparer name (as used in your Tiles definitions). The
following example shows how to define a SpringBeanPreparerFactory property on a TilesConfigurer bean:
请注意,您需要为每个准备器名称(如您的 Tiles 定义中所用)定义一个 Spring Bean 定义。以下示例显示了如何在 TilesConfigurer
Bean 上定义 SpringBeanPreparerFactory 属性:
1.10.7. RSS 和 Atom
Both AbstractAtomFeedView and AbstractRssFeedView inherit from the AbstractFeedView base class and are used to
provide Atom and RSS Feed views, respectively. They are based on ROME project and
are located in the package org.springframework.web.servlet.view.feed.
两者都继承自 AbstractFeedView 基类,分别用于提供 Atom 和 RSS Feed 视图。它们基于 ROME 项目,位于
org.springframework.web.servlet.view.feed 包中。
AbstractAtomFeedView requires you to implement the buildFeedEntries() method and optionally override the
buildFeedMetadata() method (the default implementation is empty). The following example shows how to do so:
AbstractAtomFeedView 需要您实现 buildFeedEntries() 方法,并可选择覆盖 buildFeedMetadata() 方法(默认实现为空)。以下示例展示了如何进行操作:
Similar requirements apply for implementing AbstractRssFeedView, as the following example shows:
类似的要求适用于实现 AbstractRssFeedView ,如下例所示:
The buildFeedItems() and buildFeedEntries() methods pass in the HTTP request, in case you need to access the Locale.
The HTTP response is passed in only for the setting of cookies or other HTTP headers. The feed is automatically written
to the response object after the method returns.
buildFeedItems() 和 buildFeedEntries() 方法传入 HTTP 请求,以便您访问区域设置。仅当需要设置 cookie 或其他 HTTP 标头时才传入
HTTP 响应。方法返回后,内容会自动写入响应对象。
For an example of creating an Atom view, see Alef Arendsen’s Spring Team
Blog entry.
例如,创建 Atom 视图的示例,请参阅 Alef Arendsen 的 Spring 团队博客条目。
1.10.8. PDF 和 Excel
Spring offers ways to return output other than HTML, including PDF and Excel spreadsheets. This section describes how to
use those features.
Spring 提供了除了 HTML 之外返回输出的方式,包括 PDF 和 Excel 表格。本节将描述如何使用这些功能。
文档视图简介
An HTML page is not always the best way for the user to view the model output, and Spring makes it simple to generate a
PDF document or an Excel spreadsheet dynamically from the model data.
一个 HTML 页面并不总是用户查看模型输出的最佳方式,Spring 使得从模型数据动态生成 PDF 文档或 Excel 电子表格变得简单。
The document is the view and is streamed from the server with the correct content type, to (hopefully) enable the client
PC to run their spreadsheet or PDF viewer application in response.
文档是视图,并使用正确的 MIME 类型从服务器流式传输,以便(希望)使客户端 PC 能够运行他们的电子表格或 PDF 查看器应用程序作为响应。
In order to use Excel views, you need to add the Apache POI library to your classpath. For PDF generation, you need to
add (preferably) the OpenPDF library.
为了使用 Excel 视图,您需要将 Apache POI 库添加到您的类路径中。对于 PDF 生成,您需要添加(最好是)OpenPDF 库。
You should use the latest versions of the underlying document-generation libraries, if possible.
您应尽可能使用底层文档生成库的最新版本。
In particular, we strongly recommend OpenPDF (for example, OpenPDF 1.2.12) instead of the outdated original iText 2.1.7,
since OpenPDF is actively maintained and fixes an important vulnerability for untrusted PDF content.
特别推荐使用 OpenPDF(例如,OpenPDF 1.2.12),而不是过时的原始 iText 2.1.7,因为 OpenPDF 是积极维护的,并修复了不受信任 PDF
内容的重要漏洞。
A simple PDF view for a word list could extend org.springframework.web.servlet.view.document.AbstractPdfView and
implement the buildPdfDocument() method, as the following example shows:
一个简单的单词列表 PDF 查看器可以扩展 org.springframework.web.servlet.view.document.AbstractPdfView 并实现
buildPdfDocument() 方法,如下例所示:
A controller can return such a view either from an external view definition (referencing it by name) or as a View
instance from the handler method.
控制器可以从外部视图定义(通过名称引用)或从处理方法作为 View 实例返回此类视图。
Since Spring Framework 4.2, org.springframework.web.servlet.view.document.AbstractXlsView is provided as a base class
for Excel views. It is based on Apache POI, with specialized subclasses (AbstractXlsxView and
AbstractXlsxStreamingView) that supersede the outdated AbstractExcelView class.
自 Spring 框架 4.2 以来, org.springframework.web.servlet.view.document.AbstractXlsView 被提供作为 Excel 视图的基础类。它基于
Apache POI,具有专门的子类( AbstractXlsxView 和 AbstractXlsxStreamingView ),这些子类取代了过时的 AbstractExcelView
类。
The programming model is similar to AbstractPdfView, with buildExcelDocument() as the central template method and
controllers being able to return such a view from an external definition (by name) or as a View instance from the
handler method.
编程模型类似于 AbstractPdfView ,其中 buildExcelDocument() 作为中心模板方法,控制器能够从外部定义(通过名称)或从处理方法作为
View 实例返回此类视图。
Spring offers support for the Jackson JSON library.
Spring 支持 Jackson JSON 库。
Jackson-based JSON MVC Views 基于 Jackson 的 JSON MVC 视图
The MappingJackson2JsonView uses the Jackson library’s ObjectMapper to render the response content as JSON. By
default, the entire contents of the model map (with the exception of framework-specific classes) are encoded as JSON.
For cases where the contents of the map need to be filtered, you can specify a specific set of model attributes to
encode by using the modelKeys property. You can also use the extractValueFromSingleKeyModel property to have the
value in single-key models extracted and serialized directly rather than as a map of model attributes.
对于需要过滤映射内容的情况,您可以使用 modelKeys 属性指定一组特定的模型属性进行编码。您还可以使用
extractValueFromSingleKeyModel 属性,以便在单键模型中直接提取和序列化值,而不是作为模型属性的映射。
You can customize JSON mapping as needed by using Jackson’s provided annotations. When you need further control, you can
inject a custom ObjectMapper through the ObjectMapper property, for cases where you need to provide custom JSON
serializers and deserializers for specific types.
您可以根据需要使用 Jackson 提供的注解来自定义 JSON 映射。当您需要进一步控制时,您可以通过 ObjectMapper 属性注入自定义的
ObjectMapper ,用于需要为特定类型提供自定义 JSON 序列化和反序列化程序的情况。
MappingJackson2XmlView uses the Jackson XML extension’s
XmlMapper to render the response content as XML. If the model contains multiple entries, you should explicitly set the
object to be serialized by using the modelKey bean property. If the model contains a single entry, it is serialized
automatically.
MappingJackson2XmlView 使用 Jackson XML 扩展的 XmlMapper 将响应内容渲染为 XML。如果模型包含多个条目,应显式设置要序列化的对象,使用
modelKey bean 属性。如果模型包含单个条目,则自动序列化。
You can customized XML mapping as needed by using JAXB or Jackson’s provided annotations. When you need further control,
you can inject a custom XmlMapper through the ObjectMapper property, for cases where custom XML you need to provide
serializers and deserializers for specific types.
您可以根据需要使用 JAXB 或 Jackson 提供的注解自定义 XML 映射。当您需要进一步控制时,您可以通过 ObjectMapper 属性注入自定义的
XmlMapper ,对于需要提供特定类型序列化和反序列化器的自定义 XML,您可以这样做。
1.10.10. XML 序列化
The MarshallingView uses an XML Marshaller (defined in the org.springframework.oxm package) to render the response
content as XML. You can explicitly set the object to be marshalled by using a MarshallingView instance’s modelKey
bean property. Alternatively, the view iterates over all model properties and marshals the first type that is supported
by the Marshaller. For more information on the functionality in the org.springframework.oxm package,
see Marshalling XML using O/X Mappers.
MarshallingView 使用一个 XML Marshaller (在 org.springframework.oxm 包中定义)来将响应内容渲染为 XML。您可以通过使用一个
MarshallingView 实例的 modelKey bean 属性来显式设置要序列化的对象。或者,视图会遍历所有模型属性,并序列化 Marshaller
支持的第一个类型。有关 org.springframework.oxm 包中功能的信息,请参阅使用 O/X Mapper 序列化 XML。
XSLT is a transformation language for XML and is popular as a view technology within web applications. XSLT can be a
good choice as a view technology if your application naturally deals with XML or if your model can easily be converted
to XML.
XSLT 是一种用于 XML 的转换语言,在 Web 应用程序中作为视图技术非常流行。如果您的应用程序自然处理 XML 或模型可以轻松转换为
XML,那么 XSLT 可以作为视图技术的良好选择。
The following section shows how to produce an XML document as model data and have it transformed with XSLT in a Spring
Web MVC application.
以下部分展示了如何在 Spring Web MVC 应用程序中生成 XML 文档作为模型数据,并使用 XSLT 对其进行转换。
This example is a trivial Spring application that creates a list of words in the Controller and adds them to the model
map. The map is returned, along with the view name of our XSLT view. See Annotated Controllers for
details of Spring Web MVC’s Controller interface. The XSLT controller turns the list of words into a simple XML
document ready for transformation.
这个示例是一个简单的 Spring 应用程序,它创建一个单词列表在 Controller 中,并将它们添加到模型映射中。返回映射以及我们 XSLT
视图的视图名称。请参阅注解控制器以了解 Spring Web MVC 的 Controller 接口的详细信息。XSLT 控制器将单词列表转换为简单的
XML 文档,以便进行转换。
Configuration is standard for a simple Spring web application: The MVC configuration has to define an XsltViewResolver
bean and regular MVC annotation configuration. The following example shows how to do so:
配置对于简单的 Spring Web 应用程序是标准的:MVC 配置必须定义一个 XsltViewResolver bean 和常规的 MVC 注解配置。以下示例展示了如何进行操作:
We also need a Controller that encapsulates our word-generation logic.
我们还需要一个封装我们的单词生成逻辑的控制器。
The controller logic is encapsulated in a @Controller class, with the handler method being defined as follows:
控制器逻辑封装在 @Controller 类中,处理方法定义如下:
So far, we have only created a DOM document and added it to the Model map. Note that you can also load an XML file as a
Resource and use it instead of a custom DOM document.
到目前为止,我们只创建了一个 DOM 文档并将其添加到 Model 映射中。请注意,您还可以将 XML 文件作为 Resource 加载并使用它来代替自定义
DOM 文档。
There are software packages available that automatically 'domify' an object graph, but, within Spring, you have complete
flexibility to create the DOM from your model in any way you choose.
有可用的软件包可以自动将对象图“DOM 化”,但在 Spring 中,您有完全的灵活性以任何您选择的方式从模型创建 DOM。
This prevents the transformation of XML playing too great a part in the structure of your model data, which is a danger
when using tools to manage the DOMification process.
这防止了 XML 在您的模型数据结构中扮演过于重要的角色,这在使用工具管理 DOM 化过程时是一种危险。
Finally, the XsltViewResolver resolves the “home” XSLT template file and merges the DOM document into it to generate
our view. As shown in the XsltViewResolver configuration, XSLT templates live in the war file in the WEB-INF/xsl
directory and end with an xslt file extension.
最后, XsltViewResolver 解析“home” XSLT 模板文件并将 DOM 文档合并到其中以生成我们的视图。如图 XsltViewResolver
配置所示,XSLT 模板位于 WEB-INF/xsl 目录下的 war 文件中,并以 xslt 文件扩展名结尾。
The following example shows an XSLT transform:
以下示例展示了 XSLT 转换:
The preceding transform is rendered as the following HTML:
前一个转换被渲染为以下 HTML: