Skip to main content

Spring's form tags: make sure you set the action

A colleague and I found a problem recently where if you specify a parameter on the URL which takes you to a Spring-powered form, and then submit that form you end up with multiple values for the same field item in the controller.

  • http://localhost/productDetails?serialNumber=12345A
    Loads the product details form with serial number 12345A and displays the product details
  • User enters a different serial number 98765Z in the serialNumber input box and clicks "Get product details"
  • Application received a serialNumber parameter contain an array of Strings: \["12345A", "98765Z"\]

If you use Spring's " tags but don't specify an action the taglib will create one for you in the resulting HTML. This will be the URL that you used to access your form, so if you pass a serialNumber in a GET request, the serialNumber will be part of the action URL as well as a field within your form - hence an array of serial numbers.


Another colleague (Richard) cleverly suggested that it could be to do with the form's action attribute and he was correct: to stop this behaviour you have to specify an action. You should be able to just use the mapping URL that you have bound into the controller (without the slash), so in my case my Controller looks like:
public class ProductDetailsFormController {
And so my form tag looks like:
<form:form modelAttribute="product" action="productDetails">
This appears to work correctly for me, please let me know if you have any issues with this approach.

Technorati Tags: , ,


Unknown said…
Thanks a lot.. .this solved my problem :)
Unknown said…
Thanks, it is useful also with forms with a table of results in the same page. While sorting & paging, displaytag puts get parameters in the request, and Spring puts them in the action url of the Spring-powered-form (with the results you have shown).
With your hint, the form is working again! The only problem here is that you lose the displaytag parameters, so you lose sorting and things like that. I think you can live with that!
Unknown said…
It works for me