SpringMVC:参数绑定

参数绑定

处理器适配器在执行Handler之前需要把http请求的key/value数据绑定到Handler方法形参数上。

springmvc中,接收页面提交的数据是通过方法形参来接收,而不是在controller类定义成员变量接收!

默认支持的类型

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。

1、HttpServletRequest:通过request对象获取请求信息

2、HttpServletResponse:通过response处理响应信息

3、HttpSession:通过session对象得到session中存放的对象

4、Model/ModelMap:ModelMap是Model接口的实现类,通过Model或ModelMap向页面传递数据,将model数据填充到request域。如下:

//调用service查询商品信息
Items item = itemService.findItemById(id);
model.addAttribute("item", item);

页面通过${item.XXXX}获取item对象的属性值。

使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。

简单数据类型:整型、字符串、单精度/双精度、布尔型

通过@RequestParam对简单类型的参数进行绑定:

如果不使用@RequestParam,要求request传入参数名称和controller方法的形参名称一致,方可绑定成功。 

如果使用@RequestParam,不用限制request传入参数名称和controller方法的形参名称一致。 

value:参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名字为item_id的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,没有传入参数,报下边错误:

可以使用defaultvalue设置默认值,即使required=true也可以不传参数值。

pojo

1、简单pojo

将pojo对象中的属性名与传递进来的属性名对应,如果传进来的参数名称和对象中的属性名称一致则将参数值设置在pojo对象中:

页面定义如下:

<input type="text" name="name"/>
<input type="text" name="price"/>
Contrller方法定义如下:

@RequestMapping("/editItemSubmit")
public String editItemSubmit(Items items)throws Exception{
    System.out.println(items);

请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。

2、包装pojo

如果采用类似struts中对象.属性的方式命名,需要将pojo对象作为一个包装对象的属性,action中以该包装对象作为形参。

包装对象定义如下:

Public class QueryVo {
    private Items items; 
}
页面定义:

<input type="text" name="items.name" />
<input type="text" name="items.price" />
注意:items和包装pojo中的属性一致即可。
Controller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
    System.out.println(queryVo.getItems());

post乱码

在web.xml添加post乱码filter 

<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>

get乱码

1、修改tomcat配置文件添加编码与工程编码一致,如下:

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

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

String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8"); //ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

自定义参数绑定

对于controller形参中pojo对象,如果属性中有日期类型,需要自定义参数绑定。

将请求日期数据串传成日期类型,要转换的日期类型和pojo中日期属性的类型保持一致。

所以自定义参数绑定将日期串转成java.util.Date类型,需要向处理器适配器中注入自定义的参数绑定组件。

//自定义日期参数转换类
public class CustomDateConverter implements Converter<String,Date>{
	@Override
	public Date convert(String source) {	
		//实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)		
		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;
	}
}
<!-- springmvc.xml配置 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 自定义参数绑定 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <!-- 转换器 -->
    <property name="converters">
        <list>
            <!-- 日期类型转换 -->
            <bean class="org.haiwen.controller.converter.CustomDateConverter"/>
        </list>
    </property>
</bean>

集合类

1、字符串数组

页面选中多个checkbox向controller方法传递:

<input type="checkbox" name="item_id" value="001"/>
<input type="checkbox" name="item_id" value="002"/>
<input type="checkbox" name="item_id" value="002"/>
传递到controller方法中的格式是:001,002,003
Controller方法中可以用String[]接收,定义如下:

public String deleteitem(String[] item_id)throws Exception{
    System.out.println(item_id);
}

2、List

List中存放对象,并将定义的List放在包装类中,action使用包装对象接收。 

public class QueryVo { 
    //包装类中定义List对象,并添加get/set方法如下:
}
页面定义如下:

<tr>
   <td><input type="text" name=" itemsList[0].id" value="${item.id}"/></td>
   <td><input type="text" name=" itemsList[0].name" value="${item.name }"/></td>
   <td><input type="text" name=" itemsList[0].price" value="${item.price}"/></td>
</tr>
<tr>
   <td><input type="text" name=" itemsList[1].id" value="${item.id}"/></td>
   <td><input type="text" name=" itemsList[1].name" value="${item.name }"/></td>
   <td><input type="text" name=" itemsList[1].price" value="${item.price}"/></td>
</tr>
上边的静态代码改为动态jsp代码如下:

<c:forEach items="${itemsList }" var="item" varStatus="s">
    <tr>
        <td><input type="text" name="itemsList[${s.index }].name" value="${item.name }"/></td>
        <td><input type="text" name="itemsList[${s.index }].price" value="${item.price }"/></td>
        .....
    </tr>
</c:forEach>
Contrller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
    System.out.println(queryVo.getItemList());
}

3、Map

在包装类中定义Map对象,并添加get/set方法,action使用包装对象接收。

public class QueryVo {
private Map<String, Object> itemInfo = new HashMap<String, Object>();
    //get/set方法...
}
页面定义如下:

<tr>
    <td>学生信息:</td>
        <td>
        姓名:<inputtype="text"name="itemInfo['name']"/>
        价格:<inputtype="text"name="itemInfo['price']"/>
        ...
    </td>
</tr>
Contrller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
    System.out.println(queryVo.getStudentinfo());
}
发布了202 篇原创文章 · 获赞 37 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/lovecuidong/article/details/103632357
今日推荐