banner



How To Create Textarea In Jsp

18. View technologies

18.1 Introduction

One of the areas in which Spring excels is in the separation of view technologies from the rest of the MVC framework. For example, deciding to use Velocity or XSLT in place of an existing JSP is primarily a matter of configuration. This chapter covers the major view technologies that work with Spring and touches briefly on how to add new ones. This chapter assumes you are already familiar with Section 17.5, "Resolving views" which covers the basics of how views in general are coupled to the MVC framework.

18.2 JSP & JSTL

Spring provides a couple of out-of-the-box solutions for JSP and JSTL views. Using JSP or JSTL is done using a normal view resolver defined in the WebApplicationContext. Furthermore, of course you need to write some JSPs that will actually render the view.

[Note] Note

Setting up your application to use JSTL is a common source of error, mainly caused by confusion over the different servlet spec., JSP and JSTL version numbers, what they mean and how to declare the taglibs correctly. The article How to Reference and Use JSTL in your Web Application provides a useful guide to the common pitfalls and how to avoid them. Note that as of Spring 3.0, the minimum supported servlet version is 2.4 (JSP 2.0 and JSTL 1.1), which reduces the scope for confusion somewhat.

18.2.1 View resolvers

Just as with any other view technology you're integrating with Spring, for JSPs you'll need a view resolver that will resolve your views. The most commonly used view resolvers when developing with JSPs are the InternalResourceViewResolver and the ResourceBundleViewResolver. Both are declared in the WebApplicationContext:

                              <!-- the ResourceBundleViewResolver -->                            <bean              id="viewResolver"              class="org.springframework.web.servlet.view.ResourceBundleViewResolver"              >              <property              name="basename"              value="views"              />              </bean>                              # And a sample properties file is uses (views.properties in WEB-INF/classes):                            welcome.(class)=org.springframework.web.servlet.view.JstlView welcome.url=/WEB-INF/jsp/welcome.jsp  productList.(class)=org.springframework.web.servlet.view.JstlView productList.url=/WEB-INF/jsp/productlist.jsp

As you can see, the ResourceBundleViewResolver needs a properties file defining the view names mapped to 1) a class and 2) a URL. With a ResourceBundleViewResolver you can mix different types of views using only one resolver.

              <bean              id="viewResolver"              class="org.springframework.web.servlet.view.InternalResourceViewResolver"              >              <property              name="viewClass"              value="org.springframework.web.servlet.view.JstlView"              />              <property              name="prefix"              value="/WEB-INF/jsp/"              />              <property              name="suffix"              value=".jsp"              />              </bean>            

The InternalResourceBundleViewResolver can be configured for using JSPs as described above. 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.

18.2.2 'Plain-old' JSPs versus JSTL

When using the Java Standard Tag Library you must use a special view class, the JstlView, as JSTL needs some preparation before things such as the I18N features will work.

18.2.3 Additional tags facilitating development

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. All Spring tags have HTML escaping features to enable or disable escaping of characters.

The tag library descriptor (TLD) is included in the spring-webmvc.jar. Further information about the individual tags can be found in the appendix entitled Appendix G, spring.tld.

18.2.4 Using Spring's form tag library

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. 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.

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. As you will see in the following examples, the form tags make JSPs easier to develop, read and maintain.

Let's 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.

Configuration

The form tag library comes bundled in spring-webmvc.jar. The library descriptor is called spring-form.tld.

To use the tags from this library, add the following directive to the top of your JSP page:

                <%@                taglib                prefix="form"                uri="http://www.springframework.org/tags/form"                %>              

... where form is the tag name prefix you want to use for the tags from this library.

The form tag

This tag renders an HTML 'form' tag 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 .

Let's assume we have a domain object called User. It is a JavaBean with properties such as firstName and lastName. We will use it as the form backing object of our form controller which returns form.jsp. Below is an example of what form.jsp would look like:

                <form:form>                <table>                <tr>                <td>First Name:</td>                <td>                <form:input                path="firstName"                                  />                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <form:input                path="lastName"                                  />                </td>                </tr>                <tr>                <td                colspan="2"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </table>                </form:form>              

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.

The generated HTML looks like a standard form:

                <form                method="POST"                >                <table>                <tr>                <td>First Name:</td>                <td>                <input                name="firstName"                type="text"                value="Harry"                />                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <input                name="lastName"                type="text"                value="Potter"                />                </td>                </tr>                <tr>                <td                colspan="2"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </table>                </form>              

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), then you can bind the form to the named variable like so:

                <form:form                commandName="user"                >                <table>                <tr>                <td>First Name:</td>                <td>                <form:input                path="firstName"                                  />                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <form:input                path="lastName"                                  />                </td>                </tr>                <tr>                <td                colspan="2"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </table>                </form:form>              

The input tag

This tag renders an HTML 'input' tag using the bound value and type='text' by default. For an example of this tag, see the section called "The form tag". Starting with Spring 3.1 you can use other types such HTML5-specific types like 'email', 'tel', 'date', and others.

The checkbox tag

This tag renders an HTML 'input' tag with type 'checkbox'.

Let's assume our User has preferences such as newsletter subscription and a list of hobbies. Below is an example of the Preferences class:

                public                class                Preferences {                private                boolean                receiveNewsletter;                private                String[] interests;                private                String favouriteWord;                public                boolean                isReceiveNewsletter() {                return                receiveNewsletter;       }                public                void                setReceiveNewsletter(boolean                receiveNewsletter) {                this.receiveNewsletter = receiveNewsletter;       }                public                String[] getInterests() {                return                interests;       }                public                void                setInterests(String[] interests) {                this.interests = interests;       }                public                String getFavouriteWord() {                return                favouriteWord;       }                public                void                setFavouriteWord(String favouriteWord) {                this.favouriteWord = favouriteWord;       }   }

The form.jsp would look like:

                <form:form>                <table>                <tr>                <td>Subscribe to newsletter?:</td>                                  <%-- Approach 1: Property is of type java.lang.Boolean --%>                                <td>                <form:checkbox                path="preferences.receiveNewsletter"                />                </td>                </tr>                <tr>                <td>Interests:</td>                <td>                                  <%-- Approach 2: Property is of an array or of type java.util.Collection --%>                                Quidditch:                <form:checkbox                path="preferences.interests"                value="Quidditch"                />                Herbology:                <form:checkbox                path="preferences.interests"                value="Herbology"                />                Defence Against the Dark Arts:                <form:checkbox                path="preferences.interests"                value="Defence Against the Dark Arts"                />                </td>                </tr>                <tr>                <td>Favourite Word:</td>                <td>                                  <%-- Approach 3: Property is of type java.lang.Object --%>                                Magic:                <form:checkbox                path="preferences.favouriteWord"                value="Magic"                />                </td>                </tr>                </table>                </form:form>              

There are 3 approaches to the checkbox tag which should meet all your checkbox needs.

  • 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.

  • 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.

  • 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.

Note that regardless of the approach, the same HTML structure is generated. Below is an HTML snippet of some checkboxes:

                <tr>                <td>Interests:</td>                <td>                Quidditch:                <input                name="preferences.interests"                type="checkbox"                value="Quidditch"                />                <input                type="hidden"                value="1"                name="_preferences.interests"                />                Herbology:                <input                name="preferences.interests"                type="checkbox"                value="Herbology"                />                <input                type="hidden"                value="1"                name="_preferences.interests"                />                Defence Against the Dark Arts:                <input                name="preferences.interests"                type="checkbox"                value="Defence Against the Dark Arts"                />                <input                type="hidden"                value="1"                name="_preferences.interests"                />                </td>                </tr>              

What you might not expect to see is the additional hidden field after each checkbox. When a checkbox in an HTML page is not checked, its value will not be 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 in order 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 will be bound to reflect the state of the checkbox no matter what ".

The checkboxes tag

This tag renders multiple HTML 'input' tags with type 'checkbox'.

Building 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 pass in an Array, a List or a Map containing the available options in the "items" property. Typically the bound property is a collection so it can hold multiple values selected by the user. Below is an example of the JSP using this tag:

                <form:form>                <table>                <tr>                <td>Interests:</td>                <td>                                  <%-- Property is of an array or of type java.util.Collection --%>                                <form:checkboxes                path="preferences.interests"                items="${interestList}"                />                </td>                </tr>                </table>                </form:form>              

This example assumes that the "interestList" is a List available as a model attribute containing strings of the values to be selected from. In the case where you use a Map, the map entry key will be used as the value and the map entry's value will be used as the label to be displayed. You can also use a custom object where you can provide the property names for the value using "itemValue" and the label using "itemLabel".

The radiobutton tag

This tag renders an HTML 'input' tag with type 'radio'.

A typical usage pattern will involve multiple tag instances bound to the same property but with different values.

                <tr>                <td>Sex:</td>                <td>Male:                <form:radiobutton                path="sex"                value="M"                />                <br/>                Female:                <form:radiobutton                path="sex"                value="F"                />                </td>                </tr>              

The radiobuttons tag

This tag renders multiple HTML 'input' tags with type 'radio'.

Just like the checkboxes tag above, you might want to pass in the available options as a runtime variable. For this usage you would use the radiobuttons tag. You pass in an Array, a List or a Map containing the available options in the "items" property. In the case where you use a Map, the map entry key will be used as the value and the map entry's value will be used as the label to be displayed. You can also use a custom object where you can provide the property names for the value using "itemValue" and the label using "itemLabel".

                <tr>                <td>Sex:</td>                <td>                <form:radiobuttons                path="sex"                items="${sexOptions}"                />                </td>                </tr>              

The password tag

This tag renders an HTML 'input' tag with type 'password' using the bound value.

                <tr>                <td>Password:</td>                <td>                <form:password                path="password"                                  />                </td>                </tr>              

Please note that by default, the password value is not shown. If you do want the password value to be shown, then set the value of the 'showPassword' attribute to true, like so.

                <tr>                <td>Password:</td>                <td>                <form:password                path="password"                value="^76525bvHGq"                showPassword="true"                                  />                </td>                </tr>              

The select tag

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.

Let's assume a User has a list of skills.

                <tr>                <td>Skills:</td>                <td>                <form:select                path="skills"                items="${skills}"                />                </td>                </tr>              

If the User's skill were in Herbology, the HTML source of the 'Skills' row would look like:

                <tr>                <td>Skills:</td>                <td>                <select                name="skills"                multiple="true"                >                <option                value="Potions"                >Potions</option>                <option                value="Herbology"                selected="selected"                >Herbology</option>                <option                value="Quidditch"                >Quidditch</option>                </select>                </td>                </tr>              

The option tag

This tag renders an HTML 'option'. It sets 'selected' as appropriate based on the bound value.

                <tr>                <td>House:</td>                <td>                <form:select                path="house"                >                <form:option                value="Gryffindor"                />                <form:option                value="Hufflepuff"                />                <form:option                value="Ravenclaw"                />                <form:option                value="Slytherin"                />                </form:select>                </td>                </tr>              

If the User's house was in Gryffindor, the HTML source of the 'House' row would look like:

                <tr>                <td>House:</td>                <td>                <select                name="house"                >                <option                value="Gryffindor"                selected="selected"                >Gryffindor</option>                <option                value="Hufflepuff"                >Hufflepuff</option>                <option                value="Ravenclaw"                >Ravenclaw</option>                <option                value="Slytherin"                >Slytherin</option>                </select>                </td>                </tr>              

The options tag

This tag renders a list of HTML 'option' tags. It sets the 'selected' attribute as appropriate based on the bound value.

                <tr>                <td>Country:</td>                <td>                <form:select                path="country"                >                <form:option                value="-"                label="--Please Select"                />                <form:options                items="${countryList}"                itemValue="code"                itemLabel="name"                />                </form:select>                </td>                </tr>              

If the User lived in the UK, the HTML source of the 'Country' row would look like:

                <tr>                <td>Country:</td>                <td>                <select                name="country"                >                <option                value="-"                >--Please Select</option>                <option                value="AT"                >Austria</option>                <option                value="UK"                selected="selected"                >United Kingdom</option>                <option                value="US"                >United States</option>                </select>                </td>                </tr>              

As the example shows, the combined usage of an option tag with the options tag generates the same standard HTML, but allows you to 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".

The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel simply refer to bean properties of those item objects, if specified; otherwise, the item objects themselves will be stringified. Alternatively, you may 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 and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.

The textarea tag

This tag renders an HTML 'textarea'.

                <tr>                <td>Notes:</td>                <td>                <form:textarea                path="notes"                rows="3"                cols="20"                                  />                </td>                <td>                <form:errors                path="notes"                                  />                </td>                </tr>              

The hidden tag

This tag renders an HTML 'input' tag with type 'hidden' using the bound value. To submit an unbound hidden value, use the HTML input tag with type 'hidden'.

                <form:hidden                path="house"                                  />              

If we choose to submit the 'house' value as a hidden one, the HTML would look like:

                <input                name="house"                type="hidden"                value="Gryffindor"                />              

The errors tag

This tag renders field errors in an HTML 'span' tag. It provides access to the errors created in your controller or those that were created by any validators associated with your controller.

Let's assume 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.

                public                class                UserValidator                implements                Validator {                public                boolean                supports(Class candidate) {                return                User.class.isAssignableFrom(candidate);       }                public                void                validate(Object obj, Errors errors) {           ValidationUtils.rejectIfEmptyOrWhitespace(errors,                "firstName",                "required",                "Field is required.");           ValidationUtils.rejectIfEmptyOrWhitespace(errors,                "lastName",                "required",                "Field is required.");       }   }

The form.jsp would look like:

                <form:form>                <table>                <tr>                <td>First Name:</td>                <td>                <form:input                path="firstName"                                  />                </td>                                  <%-- Show errors for firstName field --%>                                <td>                <form:errors                path="firstName"                                  />                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <form:input                path="lastName"                                  />                </td>                                  <%-- Show errors for lastName field --%>                                <td>                <form:errors                path="lastName"                                  />                </td>                </tr>                <tr>                <td                colspan="3"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </table>                </form:form>              

If we submit a form with empty values in the firstName and lastName fields, this is what the HTML would look like:

                <form                method="POST"                >                <table>                <tr>                <td>First Name:</td>                <td>                <input                name="firstName"                type="text"                value=""                />                </td>                                  <%-- Associated errors to firstName field displayed --%>                                <td>                <span                name="firstName.errors"                >Field is required.</span>                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <input                name="lastName"                type="text"                value=""                />                </td>                                  <%-- Associated errors to lastName field displayed --%>                                <td>                <span                name="lastName.errors"                >Field is required.</span>                </td>                </tr>                <tr>                <td                colspan="3"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </table>                </form>              

What if we want to display the entire list of errors for a given page? The example below shows that the errors tag also supports some basic wildcarding functionality.

  • path="*" - displays all errors

  • path="lastName" - displays all errors associated with the lastName field

  • if path is omitted - object errors only are displayed

The example below will display a list of errors at the top of the page, followed by field-specific errors next to the fields:

                <form:form>                <form:errors                path="*"                cssClass="errorBox"                                  />                <table>                <tr>                <td>First Name:</td>                <td>                <form:input                path="firstName"                                  />                </td>                <td>                <form:errors                path="firstName"                                  />                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <form:input                path="lastName"                                  />                </td>                <td>                <form:errors                path="lastName"                                  />                </td>                </tr>                <tr>                <td                colspan="3"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </table>                </form:form>              

The HTML would look like:

                <form                method="POST"                >                <span                name="*.errors"                class="errorBox"                >Field is required.<br/>Field is required.</span>                <table>                <tr>                <td>First Name:</td>                <td>                <input                name="firstName"                type="text"                value=""                />                </td>                <td>                <span                name="firstName.errors"                >Field is required.</span>                </td>                </tr>                <tr>                <td>Last Name:</td>                <td>                <input                name="lastName"                type="text"                value=""                />                </td>                <td>                <span                name="lastName.errors"                >Field is required.</span>                </td>                </tr>                <tr>                <td                colspan="3"                >                <input                type="submit"                value="Save Changes"                                  />                </td>                </tr>                </form>              

HTTP Method Conversion

A key principle of REST is the use of the Uniform Interface. This means that all resources (URLs) can be manipulated using the same four HTTP methods: GET, PUT, POST, and DELETE. For each method, the HTTP specification defines the exact semantics. For instance, a GET should always be a safe operation, meaning that is 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. 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 simply do a POST with the 'real' method as an additional parameter (modeled as a hidden input field in an HTML form). This latter trick is what Spring's HiddenHttpMethodFilter does. This filter is a plain Servlet Filter and therefore it can be used in combination with any web framework (not just Spring MVC). Simply add this filter to your web.xml, and a POST with a hidden _method parameter will be converted into the corresponding HTTP method request.

To support HTTP method conversion the Spring MVC form tag was updated to support setting the HTTP method. For example, the following snippet taken from the updated Petclinic sample

                <form:form                method="delete"                >                <p                class="submit"                >                <input                type="submit"                value="Delete Pet"                />                </p>                </form:form>              

This will actually perform an HTTP POST, with the 'real' DELETE method hidden behind a request parameter, to be picked up by the HiddenHttpMethodFilter, as defined in web.xml:

<filter>     <filter-name>httpMethodFilter</filter-name>     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter>  <filter-mapping>     <filter-name>httpMethodFilter</filter-name>     <servlet-name>petclinic</servlet-name> </filter-mapping>

The corresponding @Controller method is shown below:

                                  @RequestMapping(method = RequestMethod.DELETE)                                public                String deletePet(                  @PathVariable                                int                ownerId,                                  @PathVariable                                int                petId) {                this.clinic.deletePet(petId);                return                "redirect:/owners/"                + ownerId; }

HTML5 Tags

Starting with Spring 3, the Spring form tag library allows entering dynamic attributes, which means you can enter any HTML5 specific attributes.

In Spring 3.1, 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.

18.3 Tiles

It is possible to integrate Tiles - just as any other view technology - in web applications using Spring. The following describes in a broad way how to do this.

NOTE: This section focuses on Spring's support for Tiles 2 (the standalone version of Tiles, requiring Java 5+) in the org.springframework.web.servlet.view.tiles2 package as as well as Tiles 3 in the org.springframework.web.servlet.view.tiles3 package. Spring also continues to support Tiles 1.x (a.k.a. "Struts Tiles", as shipped with Struts 1.1+; compatible with Java 1.4) in the original org.springframework.web.servlet.view.tiles package.

18.3.1 Dependencies

To be able to use Tiles you have to have a couple of additional dependencies included in your project. The following is the list of dependencies you need.

  • Tiles version 2.1.2 or higher

  • Commons BeanUtils

  • Commons Digester

  • Commons Logging

18.3.2 How to integrate Tiles

To be able to use Tiles, you have to configure it using files containing definitions (for basic information on definitions and other Tiles concepts, please have a look at http://tiles.apache.org). In Spring this is done using the TilesConfigurer. Have a look at the following piece of example ApplicationContext configuration:

              <bean              id="tilesConfigurer"              class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"              >              <property              name="definitions"              >              <list>              <value>/WEB-INF/defs/general.xml</value>              <value>/WEB-INF/defs/widgets.xml</value>              <value>/WEB-INF/defs/administrator.xml</value>              <value>/WEB-INF/defs/customer.xml</value>              <value>/WEB-INF/defs/templates.xml</value>              </list>              </property>              </bean>            

As you can see, there are five files containing definitions, which are all located in the 'WEB-INF/defs' directory. At initialization of the WebApplicationContext, the files will be loaded and the definitions factory will be initialized. After that has been done, the Tiles includes 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 just as with any other view technology used with Spring. Below you can find two possibilities, the UrlBasedViewResolver and the ResourceBundleViewResolver.

UrlBasedViewResolver

The UrlBasedViewResolver instantiates the given viewClass for each view it has to resolve.

                <bean                id="viewResolver"                class="org.springframework.web.servlet.view.UrlBasedViewResolver"                >                <property                name="viewClass"                value="org.springframework.web.servlet.view.tiles2.TilesView"                />                </bean>              

ResourceBundleViewResolver

The ResourceBundleViewResolver has to be provided with a property file containing viewnames and viewclasses the resolver can use:

                <bean                id="viewResolver"                class="org.springframework.web.servlet.view.ResourceBundleViewResolver"                >                <property                name="basename"                value="views"                />                </bean>              
... welcomeView.(class)=org.springframework.web.servlet.view.tiles2.TilesView welcomeView.url=welcome                                  (this is the name of a Tiles definition)                                vetsView.(class)=org.springframework.web.servlet.view.tiles2.TilesView vetsView.url=vetsView                                  (again, this is the name of a Tiles definition)                                findOwnersForm.(class)=org.springframework.web.servlet.view.JstlView findOwnersForm.url=/WEB-INF/jsp/findOwners.jsp ...

As you can see, when using the ResourceBundleViewResolver, you can easily mix different view technologies.

Note that the TilesView class for Tiles 2 supports JSTL (the JSP Standard Tag Library) out of the box, whereas there is a separate TilesJstlView subclass in the Tiles 1.x support.

SimpleSpringPreparerFactory and SpringBeanPreparerFactory

As an advanced feature, Spring also supports two special Tiles 2 PreparerFactory implementations. Check out the Tiles documentation for details on how to use ViewPreparer references in your Tiles definition files.

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-config has been activated, annotations in ViewPreparer classes will be automatically detected and applied. Note that this expects preparer classes in the Tiles definition files, just like the default PreparerFactory does.

Specify SpringBeanPreparerFactory to operate on specified preparer names instead of classes, obtaining the corresponding Spring bean from the DispatcherServlet's application context. The full bean creation process will be in the control of the Spring application context in this case, allowing for the use of explicit dependency injection configuration, scoped beans etc. Note that you need to define one Spring bean definition per preparer name (as used in your Tiles definitions).

                <bean                id="tilesConfigurer"                class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"                >                <property                name="definitions"                >                <list>                <value>/WEB-INF/defs/general.xml</value>                <value>/WEB-INF/defs/widgets.xml</value>                <value>/WEB-INF/defs/administrator.xml</value>                <value>/WEB-INF/defs/customer.xml</value>                <value>/WEB-INF/defs/templates.xml</value>                </list>                </property>                                  <!-- resolving preparer names as Spring bean definition names -->                                <property                name="preparerFactoryClass"                value="org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory"                />                </bean>              

18.4 Velocity & FreeMarker

Velocity and FreeMarker are two templating languages that can be used as view technologies within Spring MVC applications. The languages are quite similar and serve similar needs and so are considered together in this section. For semantic and syntactic differences between the two languages, see the FreeMarker web site.

18.4.1 Dependencies

Your web application will need to include velocity-1.x.x.jar or freemarker-2.x.jar in order to work with Velocity or FreeMarker respectively and commons-collections.jar is required for Velocity. Typically they are included in the WEB-INF/lib folder where they are guaranteed to be found by a Java EE server and added to the classpath for your application. It is of course assumed that you already have the spring-webmvc.jar in your 'WEB-INF/lib' directory too! If you make use of Spring's 'dateToolAttribute' or 'numberToolAttribute' in your Velocity views, you will also need to include the velocity-tools-generic-1.x.jar

18.4.2 Context configuration

A suitable configuration is initialized by adding the relevant configurer bean definition to your '*-servlet.xml' as shown below:

                              <!--   This bean sets up the Velocity environment for us based on a root path for templates.   Optionally, a properties file can be specified for more control over the Velocity   environment, but the defaults are pretty sane for file based template loading. -->                            <bean              id="velocityConfig"              class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"              >              <property              name="resourceLoaderPath"              value="/WEB-INF/velocity/"              />              </bean>                              <!--    View resolvers can also be configured with ResourceBundles or XML files. If you need   different view resolving based on Locale, you have to use the resource bundle resolver.  -->                            <bean              id="viewResolver"              class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"              >              <property              name="cache"              value="true"              />              <property              name="prefix"              value=""              />              <property              name="suffix"              value=".vm"              />              </bean>            
                              <!-- freemarker config -->                            <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">   <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/> </bean>                              <!--    View resolvers can also be configured with ResourceBundles or XML files. If you need   different view resolving based on Locale, you have to use the resource bundle resolver.  -->                            <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">   <property name="cache" value="true"/>   <property name="prefix" value=""/>   <property name="suffix" value=".ftl"/> </bean>
[Note] Note

For non web-apps add a VelocityConfigurationFactoryBean or a FreeMarkerConfigurationFactoryBean to your application context definition file.

18.4.3 Creating templates

Your templates need to be stored in the directory specified by the *Configurer bean shown above. This document does not cover details of creating templates for the two languages - please see their relevant websites for information. If you use the view resolvers highlighted, then the logical view names relate to the template file names in similar fashion to InternalResourceViewResolver for JSP's. So if your controller returns a ModelAndView object containing a view name of "welcome" then the resolvers will look for the /WEB-INF/freemarker/welcome.ftl or /WEB-INF/velocity/welcome.vm template as appropriate.

18.4.4 Advanced configuration

The basic configurations highlighted above will be suitable for most application requirements, however additional configuration options are available for when unusual or advanced requirements dictate.

velocity.properties

This file is completely optional, but if specified, contains the values that are passed to the Velocity runtime in order to configure velocity itself. Only required for advanced configurations, if you need this file, specify its location on the VelocityConfigurer bean definition above.

                <bean                id="velocityConfig"                class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"                >                <property                name="configLocation"                value="/WEB-INF/velocity.properties"                />                </bean>              

Alternatively, you can specify velocity properties directly in the bean definition for the Velocity config bean by replacing the "configLocation" property with the following inline properties.

                <bean                id="velocityConfig"                class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"                >                <property                name="velocityProperties"                >                <props>                <prop                key="resource.loader"                >file</prop>                <prop                key="file.resource.loader.class"                >                org.apache.velocity.runtime.resource.loader.FileResourceLoader                </prop>                <prop                key="file.resource.loader.path"                >${webapp.root}/WEB-INF/velocity</prop>                <prop                key="file.resource.loader.cache"                >false</prop>                </props>                </property>                </bean>              

Refer to the API documentation for Spring configuration of Velocity, or the Velocity documentation for examples and definitions of the 'velocity.properties' file itself.

FreeMarker

FreeMarker 'Settings' and 'SharedVariables' can be passed directly to the FreeMarker Configuration object 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.

                <bean                id="freemarkerConfig"                class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"                >                <property                name="templateLoaderPath"                value="/WEB-INF/freemarker/"                />                <property                name="freemarkerVariables"                >                <map>                <entry                key="xml_escape"                value-ref="fmXmlEscape"                />                </map>                </property>                </bean>                <bean                id="fmXmlEscape"                class="freemarker.template.utility.XmlEscape"                />              

See the FreeMarker documentation for details of settings and variables as they apply to the Configuration object.

18.4.5 Bind support and form handling

Spring provides a tag library for use in JSP's that contains (amongst other things) a <spring:bind/> tag. This tag primarily enables forms to display values from form backing objects and to show the results of failed validations from a Validator in the web or business tier. From version 1.1, Spring now has support for the same functionality in both Velocity and FreeMarker, with additional convenience macros for generating form input elements themselves.

The bind macros

A standard set of macros are maintained within the spring-webmvc.jar file for both languages, so they are always available to a suitably configured application.

Some of the macros defined in the Spring libraries are considered internal (private) but no such scoping exists in the macro definitions making all macros visible to calling code and user templates. The following sections concentrate only on the macros you need to be directly calling from within your templates. If you wish to view the macro code directly, the files are called spring.vm / spring.ftl and are in the packages org.springframework.web.servlet.view.velocity or org.springframework.web.servlet.view.freemarker respectively.

Simple binding

In your html forms (vm / ftl templates) that act as the 'formView' for a Spring form controller, you can use code similar to the following to bind to field values and display error messages for each input field in similar fashion to the JSP equivalent. Note that the name of the command object is "command" by default, but can be overridden in your MVC configuration by setting the 'commandName' bean property on your form controller. Example code is shown below for the personFormV and personFormF views configured earlier;

                  <html>                ...                <form                action=""                method="POST"                >                Name:   #springBind( "command.name" )                <input                type="text"                name="${status.expression}"                value="$!status.value"                                  />                <br>                #foreach($error in $status.errorMessages)                <b>$error</b>                <br>                

0 Response to "How To Create Textarea In Jsp"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel