Spring MVC通过添加自定义注解格式化数据的操作方法
来源:爱站网时间:2019-12-10编辑:网友分享
Spring MVC通过添加自定义注解格式化数据的操作方法,相信初学者都很感兴趣,这也是我们在开发项目的时候会使用的功能,其实spring MVC在处理参数绑定数据和模型数据输出时,都要使用注释格式化才能操作,今天爱站技术频道为大家细细讲解。
Spring MVC通过添加自定义注解格式化数据的操作方法,相信初学者都很感兴趣,这也是我们在开发项目的时候会使用的功能,其实spring MVC在处理参数绑定数据和模型数据输出时,都要使用注释格式化才能操作,今天爱站技术频道为大家细细讲解。
springmvc 自定义注解 以及自定义注解的解析
一、自定义注解名字
@Target({ElementType.TYPE, ElementType.METHOD}) //类名或方法上
@Retention(RetentionPolicy.RUNTIME)//运行时
@component//自定义多个注解,且在一个类中添加两个或以上的,只需要加一个 否则会实例化多次。
public @interface SocketMapping {
String value() default "";//参数
}
二、测试类
@SocketMapping("/a")
public class TestAnno {
@SocketMapping(value="/b")
public void ss(){
System.out.println(11);
}
}
三、解析测试类所在的包,反射
ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver();
Resource[] res = rpr.getResources("classpath*:websocket/**.class");//测试类的包
for(int i=0;i<res.length;i++){
String className = res[i].getURL().getPath();
className = className.split("(classes/)|(!/)")[1];
className = className.replace("/", ".").replace(".class", "");//获取到文件结构 com.xl.joe.testAnno
Class<?> cla = Class.forName(className);//获取到文件类
if(cla.isAnnotationPresent(SocketMapping.class)){//判断是否存在自定义注解
System.out.println(cla.getAnnotation(SocketMapping.class).value());//获取自定义注解的属性值
}
Object o = SpringContextUtil.getBean("testAnno");//获取类对象
Method[] methods = cla.getMethods();//获取类的方法
for(Method method:methods){
if(method.isAnnotationPresent(SocketMapping.class)){//找到自定义注解
method.invoke(o, new Object[]{});//反射改方法
}
}
}
遇到一个问题
接口传入开始时间、结束时间,格式为yyyyMMdd,要求查询的数据必须用给定的时间段进行过滤。
比如
http://127.0.0.1:8095/iportal-dev/v1/sms/sending/list?stime=20161001&etime=20161130
但是服务端接受时间后,按照业务要求,应该格式为
20161001 00:00:00< 时间段 <20161130 23:59:59
stime可以使用springMVC默认提供的@DateTimeFormat(pattern = "yyyyMMdd")可以得到正确的开始时间,但是结束时间,默认的格式注解就不能完成需求了~
仿照@DateTimeFormat自定义接口
因为是仿照的,有些可以用的方法就继承下来了,并不需要大改。
@MyDateTimeFormat注解
package cn.jpush.iportal.common.support;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import java.lang.annotation.*;
/**
* 使用方法与@DateTimeFormat一致,但是通过它进行注解的字段,会格式化为当天的23:59:59.
* 其他格式的用法也可以支持.
* @author Administrator
*
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface MyDateTimeFormat {
String style() default "SS";
ISO iso() default ISO.NONE;
String pattern() default "";
}
@MyDateTimeFormat注解处理类
package cn.jpush.iportal.common.support;
import org.springframework.context.support.EmbeddedValueResolutionSupport;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
import java.util.*;
public class MyDataTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory<MyDateTimeFormat> {
private static final Set<Class<?>> FIELD_TYPES;
static {
Set<Class<?>> fieldTypes = new HashSet<Class<?>>(4);
fieldTypes.add(Date.class);
fieldTypes.add(Calendar.class);
fieldTypes.add(Long.class);
FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
}
@Override
public Set<Class<?>> getFieldTypes() {
return FIELD_TYPES;
}
@Override
public Printer<?> getPrinter(MyDateTimeFormat annotation, Class<?> fieldType) {
return getFormatter(annotation, fieldType);
}
@Override
public Parser<?> getParser(MyDateTimeFormat annotation, Class<?> fieldType) {
return getFormatter(annotation, fieldType);
}
protected Formatter<Date> getFormatter(MyDateTimeFormat annotation, Class<?> fieldType) {
MyDateFormatter formatter = new MyDateFormatter();
formatter.setStylePattern(resolveEmbeddedValue(annotation.style()));
formatter.setIso(annotation.iso());
formatter.setPattern(resolveEmbeddedValue(annotation.pattern()));
return formatter;
}
}
重载parse接口
通过调用原来的处理函数super.parse(text, locale) ,得到转化的Date对象,然后再添加相关的处理业务,然后返回Date。
package cn.jpush.iportal.common.support;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.datetime.DateFormatter;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class MyDateFormatter extends DateFormatter {
@Override
public Date parse(String text, Locale locale) throws ParseException {
Date target = super.parse(text, locale);
//+1天
Date date = DateUtils.ceiling(new Date(target.getTime() + 1), Calendar.DATE);
//减1ms,得出23:59:59
Date result =new Date(date.getTime()-1);
return result;
}
}
向SpringMVC注册我们的自定义注解处理类
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addFormatters(FormatterRegistry registry) {
MyDataTimeFormatAnnotationFormatterFactory annoFormater =new MyDataTimeFormatAnnotationFormatterFactory();
registry.addFormatterForFieldAnnotation(annoFormater);
}
以上的内容就是关于Spring MVC通过添加自定义注解格式化数据的操作方法,其实要想找到适合自己的操作方法并不是一件容易的事,我们不能盲目选择。
