当前位置:网站首页>@Introduction and three usages of controlleradvice
@Introduction and three usages of controlleradvice
2022-07-07 14:54:00 【nsnsttn】
Study @ControllerAdvice
First ,@ControllerAdvice It's essentially a @Component, So it will also be used as a build scan .
added @ControllerAdvice Classes of are declared for those (@ExceptionHandler、@InitBinder or @ModelAttribute annotated ) Method
Professional @Component , For more than one Controller Shared by classes .
To put it bluntly , Namely aop A realization of thought , You told me you need interception rules , I'll help you stop them , Specifically, you want to do more detailed interception screening and processing after interception ,
By yourself @ExceptionHandler
、@InitBinder
or @ModelAttribute
These three annotations and the methods annotated by them are self-defined .
- @ExceptionHandler How to annotate : Used to capture Controller Different types of exceptions thrown in , So as to achieve the purpose of global exception processing ;
- @InitBinder How to annotate : Resolution for registering custom parameters in the request , So as to achieve the purpose of customizing the request parameter format ;
- @ModelAttribute How to annotate : Indicates that this method will execute the target Controller Method is executed before
!!! These three annotations can be used in ordinary Controller Class using the ,ControllerAdvice Only the scope can be customized ( Default all )
1. Scope of action
ControllerAdvice Various designations are provided Advice How rules are defined , By default, nothing is written , It is Advice all Controller, Of course, you can also specify rules in the following ways
such as :
- Specified package
matching org.my.pkg All under the package and its sub packages Controller
@ControllerAdvice(basePackages="org.my.pkg")
Of course, it can also be specified in the form of an array , Such as :
@ControllerAdvice(basePackages={
"org.my.pkg", "org.my.other.pkg"}),
- Specify the annotation
You can also specify annotations to match , For example, I made one myself @CustomAnnotation annotation , I want to match all that are decorated by this annotation Controller, It can be written like this :@ControllerAdvice(annotations={
CustomAnnotation.class})
2. Preset global data @ModelAttribute
Use @ModelAttribute
Can be in controller Store data before request
// 1. No return value method , Put in Model, Customize key ,value
@ModelAttribute()
public void presetParam(Model model) {
model.addAttribute("globalAttr", " I am a global parameter ");
}
// 2. No designation name, Return value method , The return value is map,int etc. ,key Namely map,int etc. ,,value Is the return value
@ModelAttribute()
public Map<String, String> presetParam2() {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
return map1;
}
// 3. Appoint name, Return value method ,key Namely name,value Is the return value
@ModelAttribute(name = "map2")
public Map<String, String> presetParam3() {
Map<String, String> map = new HashMap<String, String>();
map.put("key2", "value2");
return map;
}
// 4. Request parameters can be accepted
@ModelAttribute()
public void presetParam4(@RequestParam("name") String name,Model model) {
model.addAttribute("name", name);
}
Use
//1. Use Model Take out
@GetMapping("model")
public String methodOne(Model model) {
Map<String, Object> modelMap = model.asMap();
System.out.println(modelMap.get("name").toString()); // Pass in name Value
return modelMap.get("globalAttr").toString();
}
//2. Use ModelMap Take out
@GetMapping("modelMap")
public String methodThree(ModelMap modelMap) {
return modelMap.get("map").toString();
}
//[email protected]() Appoint key, Take it out directly
@GetMapping("modelAttribute")
public String methodTwo(@ModelAttribute("map2") Map map2) {
return map2.toString();
}
3. Handling global exceptions @ExceptionHandler
// @Validated Parameter checking , analysis BindingResult And return
@ExceptionHandler(BindException.class)
@ResponseBody
public JsonResult exceptionHandler(BindException e, BindingResult result) {
List<FieldError> fieldErrors = result.getFieldErrors();
String collect = fieldErrors.stream().map(f -> f.getField()+":"+f.getDefaultMessage()).collect(Collectors.joining(","));
return new JsonResult(JsonResult.Validated_ERROR, collect);
}
// Here is the general exception handler , All unexpected Exception Exceptions are handled here
@ExceptionHandler(Exception.class)
@ResponseBody
public JsonResult exceptionHandler(Exception e) {
return new JsonResult(JsonResult.SYSTEM_ERROR, e.getMessage());
}
4. Request parameter preprocessing @InitBinder
Use the default attribute editor
@InitBinder
public void initBinder(WebDataBinder dataBinder){
/* * Create a string trimming editor * Parameters {boolean emptyAsNull}: Empty string ("") As null */
StringTrimmerEditor trimmerEditor = new StringTrimmerEditor(true);
/* * Register custom editor * Take two parameters {Class<?> requiredType, PropertyEditor propertyEditor} * requiredType: The type of processing required * propertyEditor: Property editor ,StringTrimmerEditor Namely propertyEditor A subclass of */
dataBinder.registerCustomEditor(String.class, trimmerEditor);
// Convert a string in date format to Date object
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
dataBinder.addValidators(paramVOValidator);
}
Custom property editor
/** * @description: prevent xss Inject * @params: String Type conversion , Pass in all String Conduct HTML code , prevent XSS attack * @return: */
//@InitBinder
protected void initBinder2(WebDataBinder binder) {
System.out.println("22222222222222");
// Custom property editor PropertyEditorSupport
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : "";
}
});
}
Custom parameter verification @Validated!!!
@Data
public class ParamVO implements Serializable {
@ApiModelProperty("age")
private Integer age;
@ApiModelProperty("name")
private String name;
}
@Component
public class ParamVOValidator implements Validator {
/** * @description: Only when the conditions are met * @params: * @return: */
@Override
public boolean supports(Class<?> clazz) {
// Only support ParamVO Verification of type objects
return ParamVO.class.equals(clazz);
}
/** * @description: Custom validation rules * @params: * @return: */
@Override
public void validate(Object target, Errors errors) {
ParamVO paramVO = (ParamVO) target;
String userName = paramVO.getName();
if (StringUtils.isEmpty(userName) || userName.length() < 8) {
errors.rejectValue("name", "valid.userNameLen", new Object[]{
"minLength", 8}, " User name cannot be less than 8 position ");
}
}
}
@Autowired
private ParamVOValidator paramVOValidator;
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.addValidators(paramVOValidator);
}
Be careful !!!
These three annotations can be used in ordinary Controller Class using the ,ControllerAdvice Only the scope can be customized ( Default all )
边栏推荐
- 2022pagc Golden Sail award | rongyun won the "outstanding product technology service provider of the year"
- 因员工将密码设为“123456”,AMD 被盗 450Gb 数据?
- What is cloud primordial? This time, I can finally understand!
- Jetson AGX Orin CANFD 使用
- The world's first risc-v notebook computer is on pre-sale, which is designed for the meta universe!
- Navigation — 这么好用的导航框架你确定不来看看?
- Niuke real problem programming - Day12
- 2022云顾问技术系列之高可用专场分享会
- Nllb-200: meta open source new model, which can translate 200 languages
- Data connection mode in low code platform (Part 2)
猜你喜欢
Niuke real problem programming - day13
Used by Jetson AgX Orin canfd
MySQL installation configuration 2021 in Windows Environment
8大模块、40个思维模型,打破思维桎梏,满足你工作不同阶段、场景的思维需求,赶紧收藏慢慢学
上半年晋升 P8 成功,还买了别墅!
CTFshow,信息搜集:web9
比尔·盖茨晒48年前简历:“没你们的好看”
Niuke real problem programming - Day11
Jetson AGX Orin CANFD 使用
PyTorch模型训练实战技巧,突破速度瓶颈
随机推荐
CTFshow,信息搜集:web7
ES日志报错赏析-trying to create too many buckets
Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist
Es log error appreciation -- allow delete
Half an hour of hands-on practice of "live broadcast Lianmai construction", college students' resume of technical posts plus points get!
寺岗电子称修改IP简易步骤
Niuke real problem programming - Day11
全球首款 RISC-V 笔记本电脑开启预售,专为元宇宙而生!
JSON解析实例(Qt含源码)
Niuke real problem programming - Day12
Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?
A laravel background management expansion package you can't miss - Voyager
潘多拉 IOT 开发板学习(HAL 库)—— 实验12 RTC实时时钟实验(学习笔记)
CTFshow,信息搜集:web9
Niuke real problem programming - day15
EMQX 5.0 发布:单集群支持 1 亿 MQTT 连接的开源物联网消息服务器
Summary on adding content of background dynamic template builder usage
Spatiotemporal deformable convolution for compressed video quality enhancement (STDF)
EfficientNet模型的完整细节
CTFshow,信息搜集:web14