springmvc中自定義日期轉換器及其jsp頁面日期顯示的一個常用標籤

在默認情況下,springmvc不能將String類型轉成Date類型,必須自定義類型轉換器

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

/**
 * 處理類
 * @author 梧桐下的茵
 *
 */
@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController {
	public EmpAction(){
		this.setCommandClass(Emp.class);
		System.out.println("EmpAction() ");
	}
	
	/**
	 * 自定義類型轉換器,將String -> Date類型(格式yyyy-MM-dd)
	 */
	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		//向springmvc內部注入一個自定義的類型轉換器
		//參數一:將String轉換成什麼類型的字節碼
		//參數二:自定義轉換規則
		//true表示日期可以爲空
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
	
	/**
	 * obj表示封裝後的實體
	 * error表示封裝時產生的異常
	 */
	@Override
	protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object obj, BindException error)
			throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message","增加員工成功");
		System.out.println("handle() ");
		Emp emp = (Emp) obj;
		System.out.println(emp.getUsername() + ":" + emp.getGender()+ ":" + emp.getHiredate().toLocaleString());
		
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}

}

日期顯示標籤fmt

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	success.jsp<br/>
	成功<br/>
	${requestScope.message}<br/>
	姓名:${requestScope.emp.username}<br/>
	性別:${requestScope.emp.gender}<br/>
	
	入職時間:${requestScope.emp.hiredate}<br/>
	<hr/>
	入職時間:<fmt:formatDate 
				value="${requestScope.emp.hiredate}"
				type="date"
				dateStyle="medium"
			/>
	
	<!-- 
		1)fmt:formatDate 來源於 http://java.sun.com/jsp/jstl/fmt
		2)fmt:formatDate作用是格式化日期的顯示,例如:2015年5月10日 星期日
		3)value表示需要格式化的值
		4)type表示顯示日期,時間,都顯示
		  type=date表示只顯示日期
		  type=time表示只顯示時間
		  type=both表示日期時間均顯示
		5)dateStyle表示顯示日期的格式:short/medium/default/long/full
	-->
	
  </body>
</html>

當不繼承也不實現接口時,日期轉換器可以這樣寫

/**
	 * 自定義類型轉換器
	 */
	@InitBinder
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder)throws Exception{
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章