java_dude
java_dude

Reputation: 4088

@NumberFormat Annotation not working

Trying to show the currency symbol in JSP but I don't see it. Did my research and I just don`t know what more should I add to get it working. This is what I have.

<mvc:annotation-driven />

Controller

@NumberFormat(style = Style.CURRENCY)
private Double value = 50.00;

@ModelAttribute("value")
@NumberFormat(style = Style.CURRENCY)
public Double getValue() {
    return value;
}

@RequestMapping(method = RequestMethod.GET)
public ModelAndView loadForm(@ModelAttribute("user") User user) {
    ModelAndView instance 
    modelAndView.addObject("value", 100.00);
    return modelAndView;
}

JSP

<spring:bind path="value">
     <input type="text" name="${value}" value="${value}"/>
</spring:bind>

<spring:bind path="value">
     ${value}
</spring:bind>

Output

 <input type="text" name="value" value="100.0"/>

 100.0

Upvotes: 3

Views: 14133

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Try using the string literal value for the name attribute instead of resolving it with EL

<spring:bind path="value">
     <input type="text" name="value" value="${value}"/>
</spring:bind>

Also, move the field value into a new object. Currently I do not believe the code is using the field in the controller or the getter in the controller.

public class MyForm(){

    @NumberFormat(style = Style.CURRENCY)
    private Double value = 50.00;

    @ModelAttribute("value")
    @NumberFormat(style = Style.CURRENCY)
    public Double getValue() {
        return value;
    }
}

Then add the object to the model in the controller:

@RequestMapping(method = RequestMethod.GET)
public ModelAndView loadForm(@ModelAttribute("user") User user) {
    ModelAndView instance 
    modelAndView.addObject("myForm", new MyForm());
    return modelAndView;
}

Then access via the jsp:

<spring:bind path="myForm.value">
     <input type="text" name="${status.expression}" value="${status.value}"/>
</spring:bind>

<spring:bind path="myForm.value">
     ${status.value}
</spring:bind>

The major issue at the moment with the code is that it is not using the field/accessor, it is simply placing a value in the model, which does not use any of the annotated fields/methods.

References: http://www.captaindebug.com/2011/08/using-spring-3-numberformat-annotation.html#.UOAO_3fghvA

How is the Spring MVC spring:bind tag working and what are the meanings of status.expression and status.value?

Upvotes: 3

Related Questions