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(&quot;yyyy-MM-dd&quot;));
* 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;
} }

springMVC的一些工具类的更多相关文章

  1. java导出数据EXCEL的工具类(以spring-webmvc-4.0.4jar为基础)

    1.本工具类继承于  spring-webmvc-4.0.4jar文件心中的一个类   AbstractExcelView 2.代码如下 package com.skjd.util; import j ...

  2. SpringMVC Http请求工具代码类

    在SpringMVC的源代码中也提供了一个封装过的ThreadLocal,其中保存了每次请求的HttpServletRequest对象,(详细请看org.springframework.web.con ...

  3. SpringMvc数据校验@Valid等注解的使用与工具类抽取

    最近在重构老项目的代码,发现校验入参占用了很多代码,之前我对这一块的认识局限于使用StringUtils等工具来多个if块进行判断,代码是没什么问题,但是总写这些令人生烦,毕竟写代码也要讲究优雅的嘛, ...

  4. springmvc返回json数据的工具类

    在ssm框架下,MVC向前端返回数据的json工具类代码如下: public class JsonResult<T> { public static final int SUCCESS=0 ...

  5. SpringMVC 常用工具类与接口

    ClassPathResource 在类路径下读取资源 public final String getPath()public boolean exists()public InputStream g ...

  6. springMVC+redis+redis自定义工具类 的配置

    1. maven项目,加入这一个依赖包即可, <dependency> <groupId>redis.clients</groupId> <artifactI ...

  7. excel读取 工具类

    package cn.yongche.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOExce ...

  8. 第13天 JSTL标签、MVC设计模式、BeanUtils工具类

    第13天 JSTL标签.MVC设计模式.BeanUtils工具类 目录 1.    JSTL的核心标签库使用必须会使用    1 1.1.    c:if标签    1 1.2.    c:choos ...

  9. 一个基于POI的通用excel导入导出工具类的简单实现及使用方法

    前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...

随机推荐

  1. android 6.0 SDK中删除HttpClient的相关类的解决方法

    一.出现的情况 在eclipse或 android studio开发, 设置android SDK的编译版本为23时,且使用了httpClient相关类的库项目:如android-async-http ...

  2. BZOJ-1050 旅行comf 并查集+乱搞

    好久以前codevs上做过的,拿着改了改.. 1050: [HAOI2006]旅行comf Time Limit: 10 Sec Memory Limit: 162 MB Submit: 2194 S ...

  3. 洛谷P2014 TYVJ1051 选课

    题目描述 在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习.现在有N门功课,每门课有个学分,每门课有一 ...

  4. Linux 基础网络设置

    一.查看以及测试网络 查看及测试网络配置是管理Linux网络服务的第一步,本节将学习Linux系统中的网络查看以及测试命令.其中讲解的大多数命令以普通用户权限就可以完成操作,但是普通用户在执行&quo ...

  5. 了解 Nginx 基本概念

    前言 本篇是我学习 Nginx 的一些笔记,主要内容讲述了一些了解 Nginx 需要的基本概念.然后探讨一下 Nginx 的模块化的组织架构,以及各个模块的分类.工作方式.职责和提供的相关指令. 主要 ...

  6. tp三大自动

    ThinkPHP三大自动 (2012-03-21 10:48:56) 转载▼ 标签: thinkphp 三大自动 自动验证 自动完成 自动填充 自动映射 字段映射 杂谈 分类: php 一.自动验证 ...

  7. Effective Java之最佳建议

    #Effective Java之最佳建议 此书中,目前给我帮助最大的两条建议是: - 检查参数的有效性 - 不要忽略异常 ###检查参数的有效性 对于这一条,使我感同身受的原因是:在Web项目中,前期 ...

  8. SpringMvc 相关,bean map转换,百度天气,base64.js,jsBase64.java;

    1. Map<String, Object>与JavaBean[POJO, Model]转换; //model public class model{ private int id; pr ...

  9. Poj 3233 Matrix Power Series(矩阵二分快速幂)

    题目链接:http://poj.org/problem?id=3233 解题报告:输入一个边长为n的矩阵A,然后输入一个k,要你求A + A^2 + A^3 + A^4 + A^5.......A^k ...

  10. Unity3d 去掉exe版本的边框

    原地址:http://blog.sina.com.cn/s/blog_697b1b8c0101gd4h.html using System; using System.Runtime.InteropS ...