springMVC的一些工具類,主要有轉換器,讀取器
讀取文件:
package cn.edu.hbcf.common.springmvc; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer{ private static Map<String, Object> ctxPropertiesMap; @Override protected void processProperties( ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); ctxPropertiesMap = new HashMap<String, Object>(); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); ctxPropertiesMap.put(keyStr, value); } } public static Object getContextProperty(String name) { return ctxPropertiesMap.get(name); } }
springMVC中日期轉換:
package cn.edu.hbcf.common.springmvc; import java.beans.PropertyEditorSupport; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import org.apache.commons.lang.StringUtils; /** * spring中日期轉換 * * <pre> * @InitBinder * public void initBinder(WebDataBinder binder) { * binder.registerCustomEditor(Date.class, new DateConvertEditor()); * // binder.registerCustomEditor(Date.class, new * // DateConvertEditor("yyyy-MM-dd")); * binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); * } * </pre> * * * @author LiPenghui * @date 2011-8-10 下午1:48:37 */ public class DateConvertEditor extends PropertyEditorSupport{ private DateFormat format; public DateConvertEditor(){ this.format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } public DateConvertEditor(String format){ this.format=new SimpleDateFormat(format); } /** Date-->String **/ public String getAsText(){ if(getValue()==null){ return ""; } return this.format.format(getValue()); } /** String-->Date **/ public void setAsText(String text){ if(!StringUtils.isNotBlank(text)){ setValue(null); }else{ try { setValue(this.format.parse(text)); } catch (ParseException e) { throw new IllegalArgumentException("不能被轉換的日期字符串,請檢查!", e); } } } }
日期另一個轉換器(暫時沒用到)
package cn.edu.hbcf.common.springmvc; import java.text.ParseException; import java.util.Date; import org.springframework.core.convert.converter.Converter; import cn.edu.hbcf.common.utils.DateUtils; public class DateCovertor implements Converter<String,Date>{ @Override public Date convert(String date) { if(date != null){ try { return DateUtils.convertStringToDate(date, "yyyy-MM-dd HH:mm:ss"); } catch (ParseException e) { try { return DateUtils.convertStringToDate(date, "yyyy-MM-dd"); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } return null; } }
int類型轉換器:
package cn.edu.hbcf.common.springmvc; import java.beans.PropertyEditorSupport; import org.springframework.util.StringUtils; /** * * @author QQ int 2012-5-30 類型轉換器 * */ public class IntegerConvertEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } if (!StringUtils.hasText(text)) { setValue(null); } else { setValue(Integer.parseInt(text));// 這句話是最重要的,他的目的是通過傳入參數的類型來匹配相應的databind } } /** * Format the Date as String, using the specified DateFormat. */ @Override public String getAsText() { return getValue().toString(); } }
integer轉換器:
package cn.edu.hbcf.common.springmvc; import org.springframework.core.convert.converter.Converter; import org.springframework.util.StringUtils; /** * Integer轉換器 * @author qiangqiang * */ public class IntegerConvertor implements Converter<String,Integer>{ @Override public Integer convert(String s) { if("".equals(s)){ return 0; } else if (StringUtils.hasText(s)) { return Integer.parseInt(s); } return null; } }
接收異常,暫時沒用到
package cn.edu.hbcf.common.springmvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class MyHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) { // TODO Auto-generated method stub return null; } }
不知道干嘛用的:
package cn.edu.hbcf.common.springmvc; import javax.servlet.http.HttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; /** * @author 帳前卒 */ public class MyMultipartResolver extends CommonsMultipartResolver { private String excludeUrls; private String[] excludeUrlArray; public String getExcludeUrls() { return excludeUrls; } public void setExcludeUrls(String excludeUrls) { this.excludeUrls = excludeUrls; this.excludeUrlArray = excludeUrls.split(","); } /** * 這里是處理Multipart http的方法。如果這個返回值為true,那么Multipart http body就會MyMultipartResolver 消耗掉.如果這里返回false * 那么就會交給后面的自己寫的處理函數處理例如剛才ServletFileUpload 所在的函數 * @see org.springframework.web.multipart.commons.CommonsMultipartResolver#isMultipart(javax.servlet.http.HttpServletRequest) */ @Override public boolean isMultipart(HttpServletRequest request) { for (String url : excludeUrlArray) { // 這里可以自己換判斷 if (request.getRequestURI().contains(url)) { return false; } } return super.isMultipart(request); } }
總體類,和springMVC配置中對應:
package cn.edu.hbcf.common.springmvc; import java.util.Date; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; public class MyWebBindingInitializer implements WebBindingInitializer { public void initBinder(WebDataBinder binder, WebRequest request) { binder.registerCustomEditor(Date.class, new DateConvertEditor("yyyy-MM-dd")); binder .registerCustomEditor(String.class, new StringTrimmerEditor( false)); binder.registerCustomEditor(int.class, new IntegerConvertEditor()); binder.registerCustomEditor(String[].class, new StringArrayConvertEditor()); } }
以靜態變量保存Spring Application, 可以在任何代碼任何地方任何時候取出ApplicationContext
package cn.edu.hbcf.common.springmvc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 以靜態變量保存Spring Application, 可以在任何代碼任何地方任何時候取出ApplicationContext * * @author LiPenghui * */ public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); /** * 實現ApplicationContextAware接口的context注入函數,將其存入靜態變量 */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextHolder.applicationContext = applicationContext; logger.debug("SpringContextHolder注入ApplicationContext"); } /** * 獲取存儲在靜態變量中的ApplicationContext * * @return */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 從靜態變量ApplicationContext中獲取Bean,自動轉型為所賦值對象的類型 * @param <T> * @param name * @return */ @SuppressWarnings("unchecked") public static <T> T getBean(String name){ checkApplicationContext(); return (T) applicationContext.getBean(name); } @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz){ checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除ApplicationContext靜態變量. */ public static void cleanApplicationContext(){ applicationContext=null; } /** * 檢查是否獲取到了ApplicationContext */ private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException( "applicationContext未注入,請在applicationContext.xml中定義SpringContextHolder"); } } }
string數組轉換:
package cn.edu.hbcf.common.springmvc; import java.beans.PropertyEditorSupport; import org.springframework.util.StringUtils; public class StringArrayConvertEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = ""; } if (!StringUtils.hasText(text)) { setValue(null); } else { setValue(text);// 這句話是最重要的,他的目的是通過傳入參數的類型來匹配相應的databind } } /** * Format the Date as String, using the specified DateFormat. */ @Override public String getAsText() { return getValue().toString(); } }
StringConerter
package cn.edu.hbcf.common.springmvc; import org.springframework.core.convert.converter.Converter; public class StringConerter implements Converter<String,String>{ @Override public String convert(String source) { if(source != null){ return source.trim(); } return null; } }
