Skip to content

Instantly share code, notes, and snippets.

@AlBaker
Created June 12, 2011 17:28
Show Gist options
  • Save AlBaker/1021789 to your computer and use it in GitHub Desktop.
Save AlBaker/1021789 to your computer and use it in GitHub Desktop.
Spring Controller with Date objects
package mypackage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DateController {
@RequestMapping("/dates", method=RequestMethod.GET)
public ModelAndView getDate(@RequestParam(value="date", required=false) Date date) {
ModelAndView mv = new ModelAndView();
if (date == null) {
date = new Date();
}
mv.addObject("date", date);
mv.setView("dates");
return mv;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment