Spring MVC Controller NumberFormat Annotation Pattern Issue in BigDecimal

后端 未结 2 1471
盖世英雄少女心
盖世英雄少女心 2021-01-21 09:53

I have a spring controller which is taking multiple BigDecimal RequestParams.

My application locale is en_US but just for this controller method I need to

相关标签:
2条回答
  • 2021-01-21 10:22

    You can use PropertyEditorSupport to handle the form input as follows:

    Create class extending PropertyEditorSupport to convert String received from client to BigDecimal, for example:

    import java.beans.PropertyEditorSupport;
    import java.math.BigDecimal;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import java.util.Locale;
    
    public class BigDecimalEditor extends PropertyEditorSupport {
    
        public void setAsText(String text) {
            NumberFormat formatter = NumberFormat.getNumberInstance(Locale.GERMAN);
            try {
                Number number = formatter.parse(text);
                BigDecimal bigDecimal = BigDecimal.valueOf(number.doubleValue());
                setValue(bigDecimal);
            } catch (ParseException e) {
                // handle exception here
            }
        }
    }
    

    And bind it with the controller, as:

    @RestController
    @RequestMapping(value = "/employee")
    public class EmployeeController {
    
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(BigDecimal.class, new BigDecimalEditor());
        }
    
        @RequestMapping(value = "/create", method = RequestMethod.POST)
        public ModelAndView create(
                @RequestParam("amount") @NumberFormat(pattern = "#.###,##") BigDecimal amount) {
            System.out.println(amount);
            return new ModelAndView();
        }
    }
    
    0 讨论(0)
  • 2021-01-21 10:23

    I solved my problem with: @RequestParam(value="amount1", required=false) @NumberFormat(pattern="#0,00") BigDecimal amount1

    0 讨论(0)
提交回复
热议问题