0

I'm using spring mvc. In the controller, I want to get parameter as java Bean Order. Order bean has several parameters, one of them is dueDate (java.util.Date).

@RequestMapping("/toAddOrder")
public ModelAndView addOrder(Order order, BindingResult bindingResult){
    return new ModelAndView("redirect:toViewOrder");
}

@InitBinder
protected void initBinder(
        WebDataBinder binder) throws ServletException {
   binder.registerCustomEditor(byte[].class,
            new ByteArrayMultipartFileEditor());

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

Problem is if I not set value for dueDate before submiting form to controller. Then will meet error. BAD_REQUEST, because dueDate is null or "".

So, I want to know, how to avoid this problem? Solutions I can found are as follows. 1. js check before submit form. 2. not binding as Order, get parameters from HttpServletRequest request

Extra questions I found for last 2 solutions. If Order Bean has too many parameters, so I will need to write long code to get and set value, this may add load for me in future.

tereško
  • 58,060
  • 25
  • 98
  • 150
chendu
  • 534
  • 5
  • 10

1 Answers1

0

I have solved this problem. Because I'm a new to Spring MVC. I tried several methods. But I think follow methods may help if you meet the same problems.

add in your controller

@InitBinder
protected void initBinder( WebDataBinder binder) throws ServletException {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

But I meet the new questions.

If I submit form in value "". I always get error.code typeMismatch.

I already configed in message.properties file

#bean level error message
typeMismatch.order.dueDate = order.dueDate format not match "YYYY-MM-DD"

#global type not match message
typeMismatch = data type not match

But when I print error message in head of page, I always get code typeMismatch but not typeMismatch.order.dueDate.

<#if error?has_content>
    <#list error.allErrors as item>
       <@spring.message "${item.code?if_exists}"/><br/>
    </#list>
</#if>

Anyone knows how to solve this questions?

chendu
  • 534
  • 5
  • 10