Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date binding in springmvc in yyyy-MM-dd format

<tr class="rowsAdded">
        <td><input name="item" class="form-control" type="text" placeholder="Item" /></td>
        <td><input name="amount" class="form-control" type="number" placeholder="Amount" /></td>
        <td><input name="expenseDate" class="form-control" type="date"placeholder="ExpenseDate" /></td>
</tr>

Below is my controller and Init Binder

@RequestMapping (value = "/saveExpenses", method=RequestMethod.POST)
    public String saveExpenses (@RequestBody ExpenseDetailsListVO expenseDetailsListVO, Model model,BindingResult result) {
        if (result.hasErrors()) {
            System.out.println(result.getFieldError().getField().toString()+" error");
        }
        System.out.println(expenseDetailsListVO);       
        return "success";
    }

@InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
     dateFormat.setLenient(false);
     webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
     }

In this way the date format which I want is not working, this is the output what I am getting expenseDate=Wed Mar 18 05:30:00 IST 2015 But I want it into a particular format like yyyy-MM-dd... suggest me the way to do it.

like image 304
Sharique Avatar asked Dec 03 '22 17:12

Sharique


1 Answers

Wouldn't this be easier?

Entity or Form-Backing-Object:

class Foo {

  /* handles data-binding (parsing) and display if spring form tld or spring:eval */
  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
  private Date expenseDate;

  ...
}

In a form:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<form:form modelAttribute="modelAttributeName">
  <form:input type="date" path="expenseDate" />
</form:form>

Or just to display:

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<spring:eval expression="modelAttributeName.expenseDate" />

Some pedantic notes:

  1. Use CSS for layouts, not tables. See Bootstrap's grid system.
  2. Use the Post-Redirect-Get pattern for forms.
  3. Use Spring's Form taglib for proper HTML escaping and CSRF protection
  4. Use @Validated in your controller handler methods to validate
  5. You're missing a space before "placeholder" in your form

See my post here for best practices: Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security

like image 177
Neil McGuigan Avatar answered Dec 05 '22 06:12

Neil McGuigan