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.

Example

  • 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"\]
Reason

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.

Solution

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:
@Controller
@RequestMapping("/productDetails")
public class ProductDetailsFormController {
...
}
And so my form tag looks like:
<form:form modelAttribute="product" action="productDetails">
...
</form:form>
This appears to work correctly for me, please let me know if you have any issues with this approach.

Technorati Tags: , ,

Pasting code snippets to your blog easily with FormatMySourceCode

When I was preparing my last blog post on disabling HTML elements (in JSPs) with JSTL's "c:if" I needed to change a lot of the JSP markup to prepare it for adding to my posting - the angled opening and closing tags were causing quite a problem.

I was about to painstakingly go through changing them all to their 'lt' and 'gt' XML entity equivalents and then remembered a site I bookmarked sometime ago:

FormatMySourceCode.blogspot.com

It's a very handy webpage with a box to paste your code into, select a few options such as tab width and whether you want an embedded stylesheet and then click "Format Text". It promptly returns with your code (of any kind) converted into a web-friendly version which is perfect for pasting straight into your blog post.

It a great yet simple idea by Greg Houston and oh so very useful!

Technorati Tags: , , ,