请求参数预处理
@ControllerAdvice结合@InitBinder还能实现请求参数预处理,即将表单中的数据绑定到实体类上时进行一些额外处理。
例如有两个实体类Book和Author,代码如下:
book.java
package com.shrimpking.pojo;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 18:03
*/
public class Book
{
private String name;
private String author;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
@Override
public String toString()
{
return "Book{" + "name='" + name + '\'' + ", author='" + author + '\'' + '}';
}
}
Author.java
package com.shrimpking.pojo;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 18:03
*/
public class Author
{
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "Author{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
在Controller上需要接收两个实体类的数据,Controller中的方法定义如下:
首先给Controller中方法的参数添加@ModelAttribute注解,
BookController.java
package com.shrimpking.controller;
import com.shrimpking.pojo.Author;
import com.shrimpking.pojo.Book;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 18:04
*/
@RestController
public class BookController
{
//http://localhost:8099/book?b.name=图书名&b.author=作者&a.name=新作者&a.age=99
@GetMapping("/book")
public String book(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author)
{
return book.toString() + author.toString();
}
}
然后配置@ControllerAdvice,代码如下:
GlobalConfig.java
package com.shrimpking.config;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 18:07
*/
@ControllerAdvice
public class GlobalConfig
{
@InitBinder("b")
public void init(WebDataBinder binder)
{
binder.setFieldDefaultPrefix("b.");
}
@InitBinder("a")
public void init2(WebDataBinder binder)
{
binder.setFieldDefaultPrefix("a.");
}
}
代码解释:
• 在GlobalConfig类中创建两个方法,第一个@InitBinder("b")表示该方法是处理@ModelAttribute("b")对应的参数的,第二个@InitBinder("a")表示该方法是处理@ModelAttribute("a")对应的参数的。
• 在每个方法中给相应的Field设置一个前缀,然后在浏览器中请求
http://localhost:8099/book?b.name=图书名&b.author=作者&a.name=新作者&a.age=99
,即可成功地区分出name属性。
• 在WebDataBinder对象中,还可以设置允许的字段、禁止的字段、必填字段以及验证器等。