Springmvc和Mybatis(RequestMapping及参数绑定)

本文详细介绍了Spring MVC框架中的参数绑定机制,包括默认支持的类型、简单类型绑定、POJO对象绑定及解决POST请求中文乱码的方法。同时,还探讨了如何通过自定义参数绑定实现日期类型的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参数绑定
  • 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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值