1. 程式人生 > >Springmvc和Mybatis(RequestMapping及引數繫結)

Springmvc和Mybatis(RequestMapping及引數繫結)

引數繫結

  • spring引數繫結過程

從客戶端請求key/value資料,經過引數繫結。將key/value的資料繫結到controller方法的形參上
springmvc中,接收頁面提交的資料是通過方法形參來接收,而不是定義成員變數來接收
- 引數繫結預設支援的型別

直接在controller方法形參上定義下邊的型別,就可以使用這些物件,在引數繫結的
過程中,如果遇到下邊型別直接進行繫結

HttpServletRequest
    HttpServletResponse
    HttpSession
    ModelMap
    將模型資料填充到request
簡單型別:

通過RequestParam對簡單引數進行繫結,如果不使用,要求request和controller方法的形參名一致才能繫結成功

Integer id
itemsService.updateItems(id, itemsCustom);
  • 如果使用註解,不用限制
public String editItems(Model model,@RequestParam(value="id",required = true)Integer items_id) throws Exception{
  • 繫結pojo

頁面中input的name和controller的pojo形參中的屬性名一致,將頁面中的資料繫結到pojo,頁面的定義,pojo屬性名定義一致
- 注意:post亂碼問題:

在web.xml中新增亂碼過濾器

<!-- 亂碼過濾器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
<param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
自定義引數繫結實現日期

對於controller形參中pojo物件,如果屬性中有日期型別,需要自定義引數繫結,將請求的日期的資料串轉成日期型別,要轉換的日期型別和pojo中日期屬性的型別保持一致,自定義引數繫結轉換成util

需要向處理器介面卡中注入自定義的引數繫結元件

 <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
        <bean id ="conversionService" class ="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <bean class = "com.shagou.ssm.controller.converter.CustomDateConvertor"/>
                </list>
            </property>
        </bean>
public class CustomDateConvertor implements Converter<String,Date>{

    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //轉成直接返回
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //轉換失敗返回null
        return null;
    }

}