用户在页面中输入时,需要输入的日期格式是:yyyy-MM-dd.然后在后台的MVC才能认识,将页面中传来的日期数据(String类)转化为Date类型的数据(util包下的).然后再进行相应的格式化操作.
下面是MVC中Controller中的代码:
package com.mi.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
@Controller
@RequestMapping("user")
public class MyController extends MultiActionController{
@InitBinder
public void init(WebDataBinder dataBinder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
CustomDateEditor dateEditor = new CustomDateEditor(dateFormat,true);
dataBinder.registerCustomEditor(Date.class, dateEditor);
}
@RequestMapping("date")
public ModelAndView date(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String ss = dateFormat.format(date);
ModelAndView mv = new ModelAndView();
mv.addObject("date", ss);
mv.setViewName("MyJsp");
return mv;
}
}
本文介绍了一种在MVC架构中实现日期格式化的具体方法,通过使用CustomDateEditor及SimpleDateFormat来确保从前端传来的日期字符串能正确转换为Date类型,并在控制器中展示格式化后的日期。
1万+

被折叠的 条评论
为什么被折叠?



