springMVC之@InitBinder与 @ModelAttribute的用法

news/2024/7/6 3:01:54

转载自: https://blog.csdn.net/wang0907/article/details/108357696

简言之@InitBinder就是应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器。
@ModelAttribute就是给当前controller类下的所有请求方法添加数据。

@ControllerAdvice
public class MyControllerAdvice {
 
    /**
     * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {}
 
    /**
     * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

@ModelAttribute:在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取,如下:

@RequestMapping("/home")
public String home(ModelMap modelMap) {
    System.out.println(modelMap.get("author"));
}
 
//或者 通过@ModelAttribute获取
 
@RequestMapping("/home")
public String home(@ModelAttribute("author") String author) {
    System.out.println(author);
}

下面开始@InitBinder 详解

1: 注册属性编辑器

我们在接收参数的时候,对于基础的数据类型,比如接收string,int等类型,springmvc是可以直接处理的,但是对于其他复杂的对象类型,有时候是无法处理的,这时候就需要属性编辑器来进行处理(源数据为string),过程一般就是String->属性编辑器->目标类型。spring为我们提供了一些默认的属性编辑器,如org.springframework.beans.propertyeditors.CustomDateEditor就是其中一个,我们也可以通过继承java.beans.PropertyEditorSuppotr来根据具体的业务来定义自己的属性编辑器。

1.1: 使用系统默认提供的属性编辑器

  • 定义controller并使用@InitBinder注册属性编辑器
    这里注册的属性编辑器为org.springframework.beans.propertybeans.CustomDateEditor,作用是根据提供的java.text.SimpleDateFormat将输入的字符串数据转换为java.util.Date类型的数据,核心源码如下:
org.springframework.beans.propertyeditors.CustomDateEditor#setAsText
 public void setAsText(@Nullable String text) throws IllegalArgumentException {
		...
		else {
			try {
			    // 使用用户提供的java.text.SimpeDateFormat来将目标字符串格式化为java.util.Date类型,并通过SetValue方法设置最终值
				setValue(this.dateFormat.parse(text));
			}
			...
		}
	}

接下来定义类:

@RequestMapping("/myInitBinder0954")
@Controller
public class MyInitBinderController {
	/*
	注册将字符串转换为Date的属性编辑器,该编辑器仅仅对当前controller有效
	 */
	@InitBinder
	public void initBinderXXX(WebDataBinder binder) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		binder.registerCustomEditor(Date.class, dateEditor);
	}
	// http://localhost:8080/myInitBinder0954/test?date=2020-09-03%2010:17:17会使用在
	// dongshi.controller.initbinder.MyInitBinderController.initBinderXXX注册的属性编辑器转换为,
	// Date类型的
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	@ResponseBody
	public String testFormatData(Date date) {
		Map<String, Object> map = new HashMap<>();
		map.put("date", date);
		return map.toString();
	}
}

 
  • 访问测试
    在这里插入图片描述
    看到返回了Date的toString的结果,就是说明成功了。

1.2: 使用自定义的属性编辑器

假设我们的需求是这样的,调用方传过来的值是一个_竖线分割的字符串,但是处理的过程使用的是通过_号分割得到的一个String[],我们当然可以在接口内部去处理,但是我们作为专业的屌丝程序员,哈哈哈,还是要用专业一些的手段,这里就可以定义一个将竖线分割的多个字符串转换为String[]的自定义属性编辑器来实现。

  • 自定义属性编辑器
    通过继承java.beans.PropertyEditorSupport类并重写其setAdText(String text)方法完成,最后调用setValue(Object Value)方法完成转换后的值的设置。
public class StringToListPropertyEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		String[] resultArr = null;
		if (!StringUtils.isEmpty(text)) {
			resultArr = text.split("_");
		}
		setValue(resultArr);
	}
}
  • 使用
@RequestMapping("/myStringToList")
@Controller
public class StringToListController {
	@InitBinder
	public void myStringToListBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(String[].class, new StringToListPropertyEditor());
	}
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	@ResponseBody
	public String myStringToListTest(String[] strToListArr, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		String result = "_分割字符串转String[]不成功!";
		if (strToListArr != null && strToListArr.length > 0) {
			result = Arrays.asList(strToListArr).toString();
		}
		return result;
	}
}
  • 访问测试
    在这里插入图片描述

2: 处理带有前缀的form字段

比如这样的场景,在People,Address两个类中都有name字段,但是我们需要在一个表单中录入People和Address的信息,然后在接口中直接通过People,Address两个对象来接收页面的表单数据,但是两个name是无法区分的,一般的做法就是指定一个前缀,然后通过@InitBinder通过调用org.springframework.web.bind.WebDataBindersetFieldDefaultPrefix(@Nullable String fieldDefaultPrefix)方法,然后在接口中使用注解public @interface ModelAttribute设置要接收的参数的前缀,就可以区分并接收对应的参数了。

2.1: 定义用到的实体

  • Person
public class People {
	private String name;
	private String age;
	// getter setter toString
}
  • Address
public class Address {
	private String name;
    private String city;
    // getter setter toString
}

2.2: 定义测试使用的表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/myInitBinder0954/test0942" method="post" enctype="multipart/form-data">
    <input type="text" name="people.name" placeholder="人名"><br><br>
    <input type="text" name="people.age" placeholder="人年龄"><br><br>
    <input type="text" name="address.name" placeholder="地址名称"><br><br>
    <input type="text" name="address.city" placeholder="地址所在城市"><br><br>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

2.3: 定义接口

@RequestMapping("/myInitBinder0954")
@Controller
public class MyInitBinderController {
	@InitBinder(value = "people")
	public void initBinderSetDefaultPreifixPeople(WebDataBinder dataBinder) {
		dataBinder.setFieldDefaultPrefix("people.");
	}
	@InitBinder(value = "address")
	public void initBinderSetDefaultPreifixAddress(WebDataBinder dataBinder) {
		dataBinder.setFieldDefaultPrefix("address.");
	}
	@RequestMapping(value = "/test0942", method = RequestMethod.POST)
	@ResponseBody
	public String test0942(@ModelAttribute("people") People people, @ModelAttribute("address") Address address) {
		StringBuffer sb = new StringBuffer();
		sb.append(people.toString());
		sb.append("---");
		sb.append(address.toString());
		return sb.toString();
	}
}

2.4: 访问测试

  • 录入表带数据
    在这里插入图片描述
  • 访问返回结果
    在这里入图片描述

3:注册校验器

3.1:定义测试实体

package dongshi.controller.initbinder;
public class User {
	private String userName;
    // getter setter toString
}

3.2:自定义校验器

直接实现org.springframework.validation.Validator,该接口只有两个方法,一个是校验是否支持校验的support(Class<?> clazz)方法,一个是进行具体校验的validate(Object target, Errors errors)方法,源码如下:

public interface Validator {
	boolean supports(Class<?> clazz);
	void validate(Object target, Errors errors);
}

定义一个校验器:

@Component
public class UserValidator implements Validator {
	@Override
	public boolean supports(Class<?> clazz) {
		// 只支持User类型对象的校验
		return User.class.equals(clazz);
	}
	@Override
	public void validate(Object target, Errors errors) {
		User user = (User) target;
		String userName = user.getUserName();
		if (StringUtils.isEmpty(userName) || userName.length() < 8) {
			errors.rejectValue("userName", "valid.userNameLen",
					new Object[] { "minLength", 8 }, "用户名不能少于{1}位");
		}
	}
}

该校验器校验用户录入的userName长度是否大于8,并给出响应的错误信息,错误信息直接设置到errors中,最终会设置到org.springframework.validation.BindingReuslt,在接口中直接定义该对象则会自动注入对象值,从而可以获取到对应的错误信息。

3.3:定义控制器

@Controller
@RequestMapping("/valid")
public class ValidatorController {
	@Autowired
	private UserValidator userValidator;
	@InitBinder
	private void initBinder(WebDataBinder binder) {
		binder.addValidators(userValidator);
	}
	@RequestMapping(value = { "/index", "" }, method = { RequestMethod.GET })
	public String index(ModelMap m) throws Exception {
		m.addAttribute("user", new User());
		return "initbinder/user.jsp";
	}
	@RequestMapping(value = { "/signup" }, method = { RequestMethod.POST })
	public String signup(@Validated User user, BindingResult br, RedirectAttributes ra) throws Exception {
		// 携带用户录入的信息方便回显
		ra.addFlashAttribute("user", user);
		return "initbinder/user.jsp";
	}
}

 

http://www.niftyadmin.cn/n/3003987.html

相关文章

python创建类实例方法_Python 如何通过类方法创建实例方法?

下面是 Python 3.x language reference 中的一段话&#xff0c;大意是理解的&#xff0c;不过写不出一个这样的示例&#xff0c;求大神给个与这段话一致的示例&#xff1a;When an instance method object is derived from a class method object, the “class instance” stor…

JVM虚拟机(二):堆、栈、方法区概念区别

Java 堆 Java堆是和Java应用程序关系最密切的内存空间&#xff0c;几乎所有的对象都放在其中&#xff0c;并且Java堆完全是自动化管理&#xff0c;通过垃圾收集机制&#xff0c;垃圾对象会自动清理&#xff0c;不需自己去释放。 根据垃圾回收机制的不同&#xff0c;Java堆有可能…

各路由协议的协议号_2020春节档,各路高手巅峰对决?鹿死谁手

《宠爱》12月31日上映&#xff0c;元旦期间连续两天票房破亿&#xff0c;电影的热度是近期新上映的电影中最高的一部。《宠爱》在豆瓣开画评分仅6.3&#xff0c;所以说档期选的好&#xff0c;容易出爆款&#xff1b;那么大年初一的上映的各路高手将迎来巅峰对决&#xff0c;那么…

http响应报文,如果响应的内容比较大,客户端怎么样判断接收完了呢?

1. http协议有正文大小说明的content-length2. 或者分块传输chunked的话 读到0\r\n\r\n 就是读完了 ----------------------------------------------------------------------------------------------- http响应内容比较大的话&#xff0c;会分成多个tcp segment 发送&am…

ni软件可以卸载吗_你的软件真的全部卸载干净了吗?最高效软件卸载工具推荐...

▌ 前言我们在电脑上运行 .exe 软件安装包时&#xff0c;安装程序会生成一些程序文件、后台服务和注册表项等&#xff0c;用以支持软件的正常运行。但是&#xff0c;在卸载软件时&#xff0c;很多软件的卸载程序并不能完全清除安装文件&#xff0c;经常卸载不干净&#xff0c;残…

springboot全局的异常拦截处理

1 全局异常处理与HttpServletResponse响应 RestControllerAdvice是帮助我们把信息转成json格式返回 ResponseBody是将方法中的字符串转成json格式同一返回&#xff0c;一般该方法返回值为Object 1.1 使用RestControllerAdvice搭配ExceptionHandler&#xff08;推荐&#xff0…

菜鸡互啄队—— 团队合作

团队GitHub地址&#xff1a;https://github.com/BigBugWriters/pit 队名&#xff1a; 菜鸡互啄 队员学号&#xff1a; 姓名学号梁华超&#xff08;队长&#xff09;3116005144沈春霖3116005153杨钊雄3116005160林健城3116005145林奇凯3116005146林贤杰3116005147拟作的团队项目…

Springboot使用Aop拦截器记录方法运行总时长

写了一个方法&#xff0c;感觉逻辑又臭又长&#xff0c;想知道该方法的执行时间&#xff0c;于是写了一个拦截器&#xff0c;获取service中的每个方法的执行时间&#xff0c;查看其响应时长。 第一部分与第二部分转载自大佬的博客&#xff1a;https://blog.csdn.net/mu_wind/a…