4
<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.

Sharique
  • 781
  • 5
  • 12
  • 33
  • 1
    I suppose your ExpenseDetailsListVO class has a member of type Date. When you call println on expenseDetailsListVO it will simply call the toString() method of that Date member. Your binder is not involved in any way. Hence you get the default String representation of Date. You can either change the way you print your object or you can use a new class that extends Date, but with a different toString(), to store your expense date. – fsaftoiu Mar 21 '15 at 14:57
  • Yes you're right... member is of Date type because in backend also it is of type date so while converting from VO to DO it wud be easy... so what should I do now?? – Sharique Mar 21 '15 at 14:59
  • @Sharique try `dateFormat.format(yourDateObj)` – Abhishek Nayak Mar 21 '15 at 15:12

3 Answers3

10

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

Community
  • 1
  • 1
Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
8

I don't know will this answer help you or not ? One of my Entity Class like below...

@Entity
@Table(name = "TAIMS_INC_INCIDENT")
public class Incident implements Serializable{

    @DateTimeFormat(pattern = "dd/MM/yyyy") // This is for bind Date with @ModelAttribute
    @Temporal(TemporalType.DATE)
    @Column(name = "inc_date")
    private Date incidentDate;

}

And Input Like this.. GUI

<input type="text" id="incident-date" name="incidentDate" value="23/08/2017" />

Spring Controller Method Here..

    @RequestMapping(value = "/saveIncident.ibbl", method = RequestMethod.POST)
    public ModelAndView saveIncident(
                @ModelAttribute("incident")
                Incident incident,
                BindingResult result){

                System.out.println(incident.getIncidentDate());
                // Wed Aug 23 00:00:00 BDT 2017

    }

This is working fine. The Incident incident Contains incidentDate = Wed Aug 23 00:00:00 BDT 2017

If you do not want to use @DateTimeFormat(pattern = "dd/MM/yyyy") in Entity class then put the method below in Controller Class...

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
Mr. Mak
  • 837
  • 1
  • 11
  • 25
0

What I am saying is that your binder probably works just fine. What it does is it takes a String in format yyyy-MM-dd from your HTTP request's body and converts it into a Date object. But that's all it does. What you do with that Date object after that is up to you. If you want to pass it along as a String to some other part of your program you should convert it, perhaps using SimpleDateFormatter.

fsaftoiu
  • 376
  • 2
  • 5
  • Hey thaks for the suggestion!! HTTP request body is binding it in yyyy-MM-dd format, but can I change the format of it before binding takes place, like in this format dd-MM-yyyy – Sharique Mar 21 '15 at 15:18
  • You can leave it's type as String, than in your binder first convert it to Date than back to the String format you actually want. I should say this seems rather weird, but since you provide no info about what exactly you want to do with that date, I can't make any other suggestions – fsaftoiu Mar 21 '15 at 15:21
  • I was just asking for the knowledge... I just want to convert it into date object and then save it into database... So where should I convert it into Object..I mean how?? – Sharique Mar 21 '15 at 15:31
  • It's already an object, the exact class is Date. Just pass that to your database saving method and it should be ok. – fsaftoiu Mar 21 '15 at 15:32
  • but it is of type String and my backend pojo class has date type...and suppose if I convert that one into Date type also but then in my database also it is of Date type – Sharique Mar 21 '15 at 15:35
  • Here's how this works : 1-request comes in; 2-spring MVC calls your binder and converts expenseDate to Date; 3-spring MVC calls your saveExpenses method. At this point, the date in the expenseDate member of your expenseDetailsListVO is already of type Date – fsaftoiu Mar 21 '15 at 15:39