当前位置:网站首页>@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 )
边栏推荐
- JSON parsing instance (QT including source code)
- Lidar knowledge drops
- 华为云数据库DDS产品深度赋能
- 广州开发区让地理标志产品助力乡村振兴
- 寺岗电子称修改IP简易步骤
- 时空可变形卷积用于压缩视频质量增强(STDF)
- leetcode:648. 单词替换【字典树板子 + 寻找若干前缀中的最短符合前缀】
- Apache multiple component vulnerability disclosure (cve-2022-32533/cve-2022-33980/cve-2021-37839)
- Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist
- 大厂做开源的五大痛点
猜你喜欢
Navigation — 这么好用的导航框架你确定不来看看?
Zhiting doesn't use home assistant to connect Xiaomi smart home to homekit
"July 2022" Wukong editor update record
MySQL installation configuration 2021 in Windows Environment
Introduction and use of Kitti dataset
Internal sort - insert sort
Discussion on CPU and chiplet Technology
C 6.0 language specification approved
潘多拉 IOT 开发板学习(HAL 库)—— 实验12 RTC实时时钟实验(学习笔记)
Niuke real problem programming - Day9
随机推荐
Find your own value
15、文本编辑工具VIM使用
CTFshow,信息搜集:web14
Bill Gates posted his resume 48 years ago: "it's not as good-looking as yours."
Summary on adding content of background dynamic template builder usage
Notes HCIA
Navigation — 这么好用的导航框架你确定不来看看?
JSON解析实例(Qt含源码)
Cocoscreator operates spine for animation fusion
Novel Slot Detection: A Benchmark for Discovering Unknown Slot Types in the Dialogue System
Data Lake (IX): Iceberg features and data types
MicTR01 Tester 振弦采集模塊開發套件使用說明
Internal sort - insert sort
Apache多个组件漏洞公开(CVE-2022-32533/CVE-2022-33980/CVE-2021-37839)
Instructions d'utilisation de la trousse de développement du module d'acquisition d'accord du testeur mictr01
Attribute keywords ondelete, private, readonly, required
MicTR01 Tester 振弦采集模块开发套件使用说明
#yyds干货盘点# 解决名企真题:交叉线
Decrypt the three dimensional design of the game
CTFshow,信息搜集:web4