日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

SpringMVC之@InitBinder注解詳解

作者:Jothan Zhong 更新時間: 2024-01-15 編程語言
說明與作用

springmvc并不是能對所有類型的參數(shù)進(jìn)行綁定的,如果對日期Date類型參數(shù)進(jìn)行綁定,就會報(bào)錯IllegalStateException錯誤。所以需要注冊一些類型綁定器用于對參數(shù)進(jìn)行綁定。InitBinder注解就有這個作用。

@Controller
public class InitBinderController {

    @RequestMapping("/testInitBinder")
    private String testInitBinder(Date date){
        System.out.println("date = " + date);
        return "RequsetInitBindDemo";
    }
}

在這里插入圖片描述
不能把String類型轉(zhuǎn)換為Date類型報(bào)錯。

此時就需要一個日期類型轉(zhuǎn)換器。

@InitBinder
    public void dateTypeBinder(WebDataBinder webDataBinder){
        //往數(shù)據(jù)綁定器中添加一個DateFormatter日期轉(zhuǎn)化器。
        webDataBinder.addCustomFormatter(new DateFormatter("yyyy-mm-dd"));

    }

在這里插入圖片描述
在這里插入圖片描述
日期類型轉(zhuǎn)換成功了。

InitBinder注解:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InitBinder {

	//指定參數(shù)名,這個不知控制器方法上形參的參數(shù)名,而是請求參數(shù)名,可以指定多個。指定后只有這些參數(shù)需要用到該轉(zhuǎn)換器。如果不指定,默認(rèn)所有。
	String[] value() default {};

}

并且使用InitBinder 注冊的綁定器只有在當(dāng)前Controller中才有效,不會作用于其他Controller。

在其他controller中定義一個接收請求的方法。

在這里插入圖片描述
在這里插入圖片描述
請求失敗。

使用@ControllerAdvice定義全局綁定器

可以使用@ControllerAdvice定義全局綁定器。ControllerAdvice的使用可以看文章

@ControllerAdvice
public class InitBinderAdviseController {

    @InitBinder
    public void dateTypeBinder(WebDataBinder webDataBinder){
        //往數(shù)據(jù)綁定器中添加一個DateFormatter日期轉(zhuǎn)化器。
        webDataBinder.addCustomFormatter(new DateFormatter("yyyy-mm-dd"));

    }
}

結(jié)果:
在這里插入圖片描述
在這里插入圖片描述
不同controller的方法都能作用到。

使用其他格式轉(zhuǎn)化器

我們可以自定義格式轉(zhuǎn)化器,實(shí)現(xiàn)Formatter接口就可。還可以添加驗(yàn)證器等等。

public class StringFormatter implements Formatter<String> {
    private static final String PREFIX = "convertString == ";

    @Override
    public String parse(String text, Locale locale) throws ParseException {
    	//所以String類型參數(shù)都加上一個前綴。
        String result = PREFIX + text;
        return result;
    }

    @Override
    public String print(String object, Locale locale) {
        return object;
    }
}

添加
在這里插入圖片描述

測試:

@RequestMapping("/testInitBinder2")
    private String testInitBinder1(String name){
        System.out.println("name = " + name);
        return "RequsetInitBindDemo";
    }

結(jié)果:
在這里插入圖片描述
在這里插入圖片描述
前綴有了。

原文鏈接:https://blog.csdn.net/qq_43985303/article/details/129520718

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新