SpringMvc 学习 (四) 参数绑定

参数绑定就是从前端页面传递数据到后台程序

本文分四部分
1.简单类型的参数绑定
2.对象类型的参数绑定
3.对象类型的包装类的参数绑定
4.自定义参数绑定

绑定简单类型

当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。
这样,从Request取参数的方法就可以进一步简化。
页面
传递商品id号到后台

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>查询商品列表</title>
    </head>
<body> 
<form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
    <td>商品名称</td>
    <td>商品价格</td>
    <td>生产日期</td>
    <td>商品描述</td>
    <td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
    <td>${item.name }</td>
    <td>${item.price }</td>
    <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
    <td>${item.detail }</td>

    <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>
</body>

</html>

只需要在对应处理方法上加个形参接受即可,注意:必须和前端页面传递的数据名一致

    @RequestMapping(value="/itemEdit.action")
    public ModelAndView toEdit ( Integer id ,  Model model )
    {

        Items items = itemService.selectItemById(id) ;

        ModelAndView mav = new ModelAndView () ;
        mav.addObject("item", items) ;
        mav.setViewName("editItem");

        return mav ;
    }

支持的数据类型
参数类型推荐使用包装数据类型,因为基础数据类型不可以为null
整形:Integer、int
字符串:String
单精度:Float、float
双精度:Double、double
布尔型:Boolean、boolean
说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0
请求url:
http://localhost:8080/xxx.action?id=2&status=false
处理器方法:
public String editItem(Model model,Integer id,Boolean status)

@RequestParam 适用于接受参数名与页面传递数据名不一致的情况
使用@RequestParam常用于处理简单类型的绑定。
value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数 区中的名字为itemId的参数的值将传入
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错
TTP Status 400 - Required Integer parameter ‘XXXX’ is not present
defaultValue:默认值,表示如果请求中没有同名参数时的默认值
定义如下:

@RequestMapping("/itemEdit")
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer number,
       ModelMap modelMap) {
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);
    // 把商品数据放在模型中
    modelMap.addAttribute("item", item);
    return "itemEdit";
}

传递对象类型

使用pojo/bean 接受表单数据
如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接受数据,也可以使用pojo接收数据。
要求:pojo对象中的属性名和表单中input的name属性一致。
这里写图片描述

编写pojo对象
这里写图片描述

@RequestMapping("/updateItem")
public String updateItem(Item item) {
    // 调用服务更新商品
    this.itemService.updateItemById(item);
    // 返回逻辑视图
     ModelAndView mav = new ModelAndView () ;
    mav.setViewName("index");

    return mav;

}

解决乱码问题
提交发现,保存成功,但是保存的是乱码
在web.xml中加入:

  <!-- 解决post乱码问题 -->
    <filter>
       <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <!-- 设置编码参是UTF8 -->
       <init-param>
           <param-name>encoding</param-name>
           <param-value>UTF-8</param-value>
       </init-param>
    </filter>
    <filter-mapping>
       <filter-name>encoding</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

以上可以解决post请求乱码问题。

对于get请求中文参数出现乱码解决方法有两个:
修改tomcat配置文件添加编码与工程编码一致,如下:

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

另外一种方法对参数进行重新编码:

String userName = new
String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

对象包装类参数绑定

包装对象定义如下:

public class QueryVo {
    private Item item;
set/get。。。
}

页面定义如下图:
比如要向QueryVo对象的item属性传递id值 name要改为item.id
这里写图片描述

接受

   @RequestMapping(value="/updateitem.action")
   public ModelAndView Update ( QueryVo queryVo )
   {
      queryVo.getItems().setCreatetime(new Date());
      itemService.Update(queryVo.getItems());

      ModelAndView mav = new ModelAndView () ;
      mav.setViewName("index");

      return mav;

   }

自定义参数绑定

比如传递的数据包含日期类型,由于日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。一般使用<mvc:annotation-driven/>注解驱动加载处理器适配器,可以在此标签上进行配置。

页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title>

</head>
<body> 
    <!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
    <!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->
    <form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post">
        <input type="hidden" name="items.id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名称</td>
                <td><input type="text" name="items.name" value="${item.name }" /></td>
            </tr>
            <tr>
                <td>商品价格</td>
                <td><input type="text" name="items.price" value="${item.price }" /></td>
            </tr>

            <tr>
                <td>商品生产日期</td>
                <td><input type="text" name="items.createtime"
                    value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
            </tr>
            <tr>
                <td>商品简介</td>
                <td><textarea rows="3" cols="30" name="items.detail">${item.detail }</textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交" />
                </td>
            </tr>
        </table>

    </form>
</body>

</html>

自定义converter

package com.Google.conversion;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;

/**
 * 转换日期类型的数据
 * s 页面传递过来的数据
 * t 转化后的类型
 * @author Administrator
 *
 */
public class DateConversion implements Converter<String, Date> {

    public Date convert(String source) {

        try
        {
            if ( source != null )
            {
                 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 Date date =  df.parse(source);
                 return date ;
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        return null;
    }

}

配置converter有两种方式一个使用<mvc:annotation-driven/>注解驱动加载处理器适配器
一个不使用 (推荐使用第一个)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <!-- 注解驱动 -->
   <mvc:annotation-driven conversion-service="con" />

   <!-- 配置Conveter转换器 转换工厂(日期. 去空格) -->
   <bean id="con" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
      <!-- 配置多个转换器 -->
      <property name="converters">
         <list>
             <bean class="com.Google.conversion.DateConversion"></bean>
         </list>
      </property>
   </bean>


</beans>

第二种方式如下

<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
   <property name="webBindingInitializer" ref="customBinder"></property>
</bean>
<!-- 自定义webBinder -->
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
   <property name="conversionService" ref="conversionService" />
</bean>
<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
   <property name="converters">
      <set>
          <bean class="cn.itcast.springmvc.convert.DateConverter" />
      </set>
   </property>
</bean>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值