1
可以的哦,试试看:
先定义一个自己的@UpperCase
:
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface UpperCase {
}
在定义一个formatter的工厂
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
import java.text.ParseException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class UpperAnnotationFormatterFactory implements AnnotationFormatterFactory<UpperCase> {
@Override
public Set<Class<?>> getFieldTypes() {
Set<Class<?>> fieldTypes = new HashSet<>();
fieldTypes.add(String.class);
return Collections.unmodifiableSet(fieldTypes);
}
@Override
public Printer<String> getPrinter(UpperCase annotation, Class<?> fieldType) {
return configureFormatterFrom(annotation);
}
@Override
public Parser<String> getParser(UpperCase annotation, Class<?> fieldType) {
return configureFormatterFrom(annotation);
}
private Formatter<String> configureFormatterFrom(UpperCase annotation) {
return new Formatter<String>() {
@Override
public String print(String object, Locale locale) {
return object;
}
@Override
public String parse(String text, Locale locale) throws ParseException {
return text.toUpperCase();
}
};
}
}
最后,注册一下上面这个工厂
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldAnnotation(new UpperAnnotationFormatterFactory());
}
}
现在你再看看,你的代码
@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") @UpperCase String text) {
System.out.println(text); // 这个地方的text就已经被大写了
return "form";
}