当前位置:网站首页>@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 )
边栏推荐
- Discussion on CPU and chiplet Technology
- Instructions d'utilisation de la trousse de développement du module d'acquisition d'accord du testeur mictr01
- CTFshow,信息搜集:web1
- Niuke real problem programming - Day12
- 潘多拉 IOT 开发板学习(HAL 库)—— 实验12 RTC实时时钟实验(学习笔记)
- FFmpeg----图片处理
- Leetcode one question per day (636. exclusive time of functions)
- Pytorch model trains practical skills and breaks through the bottleneck of speed
- How bad can a programmer be? Nima, they are all talents
- 「2022年7月」WuKong编辑器更版记录
猜你喜欢

PyTorch模型训练实战技巧,突破速度瓶颈

Bill Gates posted his resume 48 years ago: "it's not as good-looking as yours."
![[Yugong series] go teaching course 005 variables in July 2022](/img/66/4265a06a98412bd2c88d8281caf06e.png)
[Yugong series] go teaching course 005 variables in July 2022

Computer win7 system desktop icon is too large, how to turn it down

潘多拉 IOT 开发板学习(HAL 库)—— 实验12 RTC实时时钟实验(学习笔记)

CTFshow,信息搜集:web3

CTFshow,信息搜集:web5

Webrtc audio anti weak network technology (Part 1)

Discussion on CPU and chiplet Technology

⼀个对象从加载到JVM,再到被GC清除,都经历了什么过程?
随机推荐
Concurrency Control & NoSQL and new database
时空可变形卷积用于压缩视频质量增强(STDF)
CTFshow,信息搜集:web4
ES日志报错赏析-- allow delete
Apache多个组件漏洞公开(CVE-2022-32533/CVE-2022-33980/CVE-2021-37839)
Ascend 910 realizes tensorflow1.15 to realize the Minist handwritten digit recognition of lenet network
Discussion on CPU and chiplet Technology
Several ways of JS jump link
[today in history] July 7: release of C; Chrome OS came out; "Legend of swordsman" issued
Ffmpeg --- image processing
Nllb-200: meta open source new model, which can translate 200 languages
ES日志报错赏析-maximum shards open
Niuke real problem programming - Day12
2022云顾问技术系列之高可用专场分享会
Summary on adding content of background dynamic template builder usage
2022 cloud consulting technology series high availability special sharing meeting
KITTI数据集简介与使用
How to enable radius two factor / two factor (2fa) identity authentication for Anheng fortress machine
What is cloud primordial? This time, I can finally understand!
PG basics -- Logical Structure Management (locking mechanism -- table lock)