參數綁定
參數綁定過程:從客戶端請求key/value數據,經過參數綁定,將數據綁定到Controller方法的形參上
springmvc中,接收頁面提交的數據是通過方法的形參來接收的,而不是在Controller類定義成員變量接收
處理器適配器調用springmvc提供的參數綁定組件將key/value數據轉成Controller方法形參
參數綁定組件:springmvc早期版本使用PropertyEditor(只能將字符串轉換成java對象),後期使用convert(進行任意類型轉換)
springmvc提供了很多convert(轉換器),在特殊情況下需要自定義convert,如對日期數據綁定
默認支持的綁定類型:
HttpServletRequest,HttpServletResponse,HttpSession,ModelMap/Model(model是一個接口,modelMap是一個實現類),簡單類型
Model/ModelMap作用:將model數據填充到request域
簡單類型綁定
1.代碼:
@RequestMapping("/query.action")
public ModelAndView query(Integer id) throws Exception{
url:http://localhost:8080/springmvc/query.action?id=5
此方法請求數據的key需要與Controller方法形參的名稱一致。
2.通過@RequestParam註解對簡單類型綁定
//@RequestParam指定request傳入參數名與形參進行綁定
//通過required屬性設值參數是否必須要傳入
//defaultValue設置默認值,若參數沒有傳入使用默認值綁定形參
@RequestMapping("/query.action")
public ModelAndView query(@RequestParam(value="id",required=false,defaultValue="4" ) Integer i,@RequestParam(value="name") String username) throws Exception{
pojo參數綁定
@RequestMapping("/query.action")
public ModelAndView query( Integer id, Items items) throws Exception{
請求參數會自動綁定到與請求參數key相同的pojo形參屬性名稱上,pojo綁定和簡單類型綁定互不影響
包裝類型pojo參數綁定
在頁面傳入請求參數的時候使用 “自定義屬性.屬性名”,會自動綁定到包裝類型的自定義參數上。
如:包裝類型User中有Custom屬性 ,請求參數名Custom.name,將會綁定到User的Custom屬性中
validation校驗
需要導入的jar包:
hibernate-validator-5.0.1.Final.jar
jboss-logging-3.1.0.CR2.jar
validation-api-1.1.0.Final.jar
classmate-0.8.0.jar
注意:hibernate-validator5.0以上版本不兼容validation-api-1.0版本,會出現ClassNotFound錯誤提示
校驗器配置:
<!-- 配置校驗器 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 注入hibernate校驗器 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
<!-- 校驗錯誤信息配置文件,若不指定默認使用Classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 資源文件名 -->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- 配置文件編碼格式 -->
<property name="fileEncodings" value="utf-8"></property>
<!-- 配置資源文件內容緩存時間,單位秒 -->
<property name="cacheSeconds" value="120"></property>
</bean>
Controller類:
@RequestMapping("/query.action")
//在需要校驗的pojo前加@Validated,在pojo後加BindingResult bindingResult接收校驗出錯信息
//@Validated和BingdingResult配對出現
public ModelAndView query( Integer id, Date date, @Validated Items items2, BindingResult bindingResult) throws Exception{
//打印錯誤信息
if(bindingResult.hasErrors()) {
List<ObjectError> allError = bindingResult.getAllErrors();
for(ObjectError error : allError) {
System.out.println(error.getDefaultMessage());
}
}
需要校驗的屬性:
public class Items {
@Size(min=1, max=3, message="{Items.name.length.errow}")
private String name;
@NotNull(message="{Items.id.isNull.errow}")
private int id;
錯誤信息CustomValidationMessages.properties文件:
Items.name.length.errow=請輸入1至4個字符
Items.id.isNull.errow=id不能爲空
分組校驗
需求:在pojo中定義校驗規則,而pojo是被多個Controller共用,當不同的Controller方法對同一個pojo進行校驗,但是每個Controller需要不同的校驗
解決辦法:定義多個校驗分組(一個接口),每個Contoller方法實現不同的校驗分組
public interface ValidGroup1 {}
public interface ValidGroup2 {}
在校驗規則中添加分組,一個屬性可定義多個分組
public class Items {
@Size(min=1, max=3, message="{Items.name.length.errow}",groups={ValidGroup1.class})
@NotNull(message="{Items.name.isNull.error}",groups={ValidGroup1.class})
private String name;
@NotNull(message="{Items.id.isNull.errow}",groups={ValidGroup2.class})
private int id;
在Controller方法中指定分組校驗
@RequestMapping("/query.action")
//value={ValidGroup1.class}指定只用這個分組的校驗
public ModelAndView query( Integer id, @Validated(value={ValidGroup1.class}) Items items2, BindingResult bindingResult) throws Exception{
if(bindingResult.hasErrors()) {
List<ObjectError> allError = bindingResult.getAllErrors();
for(ObjectError error : allError) {
System.out.println(error.getDefaultMessage());
}
}
數據回顯
提交後若出現錯誤將填寫的信息回顯給請求頁面
1.spring默認對pojo數據進行回顯
pojo數據傳入Controller方法後,springmvc會自動將pojo數據放入request域,key等於pojo類名(首字母小寫)
2.使用@ModelAttribute指定pojo回顯到頁面在request域中的key
@RequestMapping("/query.action")
//@ModelAttribute可以指定pojo回顯頁面在request域中的key
public ModelAndView query( Integer id, Date date, @ModelAttribute("items") @Validated(value={ValidGroup1.class}) Items items2, BindingResult bindingResult) throws Exception{
3.@ModelAttribute還可以將方法的返回值傳到頁面
在方法上面添加@ModelAttribute標籤可以指定方法返回值在request域的key
4.可以使用簡單方法model.addAttribute將數據添加到request域,而不用使用@MoelAttribute
public ModelAndView query( Model model,Integer id, @ModelAttribute("items") @Validated(value={ValidGroup1.class}) Items items2, BindingResult bindingResult) throws Exception{
model.addAttribute("items",items2);
5.對於簡單類型的數據回顯只能使用Model