Pre-populated <form:input> field (spring-for

2019-08-08 12:21发布

问题:

I have a <form:form> in my jsp page with several <form:input> fields (so, fields are databound). Some of those fields are populated by user, but some, instead of waiting for user to enter some value, need to pre-populated with the value of parameter sent to this page from another jsp page, through the spring controller. How to write that parametar into <form:input> so user doesn't have to?

回答1:

If I understand your question correctly, you want to prepopulate some fields with values already submitted previously.

All you need to understand is that with the Spring form taglib, Spring expects you to put a command object in the model and will bind the values in that command object to the form fields.

If you don't specify the key for this command object in the model, the taglib will look for it with the key "command". You can specify a different name though with the commandName attribute on the form tag, such as:

<form:form commandName="myModelObject">

Spring would now look for an object in the model named myModelObject to use to bind the form tags.

The other thing you then need to do is in the form tags in your Spring form, reference the fields in your command object. So, for example, let's say your command object has a field firstName, you'd have an input tag like this:

<form:input path="firstName" />

The path attribute tells the attribute what fields in the command object it should bind with.

So then you simply put the command object in your model with the appropriate fields prepopulated and the corresponding form fields will have those values prepopulated. Such as if you put an object in the model with the name myModelObject that has a field firstName, it will be prepopulated with whatever firstName is currently set to in that object.