1 默认支持的参数类型

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

1.1 HttpServletRequest

    通过request对象获取请求信息

1.2 HttpServletResponse

    通过response处理响应信息

1.3 HttpSession

   通过session对象得到session中存放的对象

1.4 示例

   以“根据id查询商品”为例,页面的请求为http://localhost:8080/SpringMVCProject/itemEdit.action?id=1,要得到request请求的id为1的商品,可以通过HttpServletRequest对象获得

1.4.1 springmvc.xml配置

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

    <!-- 配置controller扫描包 -->
    <context:component-scan base-package="com.itykd"/>
    <!-- 配置注解驱动 -->
    <mvc:annotation-driven />
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

1.4.2 Controller

@RequestMapping("itemEdit")
	public ModelAndView queryItemById(HttpServletRequest request) {
		//从request中获得关于商品信息的id
		String strId = request.getParameter("id");
		//把字符串转成整型
		Integer id = Integer.parseInt(strId);
		//根据id查询商品信息
		Items item = itemsService.queryItemById(id);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("item",item);
		modelAndView.setViewName("editItem");
		return modelAndView;
	}

2 ModelAndView、Model、ModelMap

2.1 Model

ModelAndView以外,还可以使用Model来向页面传递数据,Model是一个接口,在参数里直接声明model即可

@RequestMapping("itemEdit")
public String queryItemById(HttpServletRequest request, Model model) {
	// 从request中获取请求参数
	String strId = request.getParameter("id");
	Integer id = Integer.valueOf(strId);

	// 根据id查询商品数据
	Items item = itemsService.queryItemById(id);

	// 把商品数据放在模型中
	model.addAttribute("item", item);

	return "itemEdit";
}

2.2 ModelMap

    ModelMap是Model接口的实现类,使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap
下面通过ModelMap向页面传递数据

@RequestMapping("itemEdit")
public String queryItemById(HttpServletRequest request, ModelMap model) {
	// 从request中获取请求参数
	String strId = request.getParameter("id");
	Integer id = Integer.valueOf(strId);

	// 根据id查询商品数据
	Items item = itemsService.queryItemById(id);

	// 把商品数据放在模型中
	model.addAttribute("item", item);

	return "itemEdit";
}

3 绑定简单参数类型

名称一致时会将请求参数与形参进行绑定。这样,request取参数的方法就可以进一步简化。

@RequestMapping("itemEdit")
public String queryItemById(Integer id, ModelMap model) {

	// 根据id查询商品数据
	Items item = itemsService.queryItemById(id);

	// 把商品数据放在模型中
	model.addAttribute("item", item);

	return "itemEdit";
}

3.1 支持的数据类型

参数类型推荐使用包装数据类型,因为基础数据类型不可以为null

说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0
请求url:http://localhost:8080/xxx.action?id=2&status=false
处理器方法:public String editItem(Model model,Integer id,Boolean status)

 3.2 @RequestParam

  • 使用@RequestParam常用于处理简单类型的绑定
  • value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数    区中的名字为itemId的参数的值将传入
  • required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报TTP Status 400 - Required Integer parameter 'XXXX' is not present错误
@RequestMapping("/itemEdit")
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,
		ModelMap modelMap) {
	// 根据id查询商品数据
	Item item = this.itemService.queryItemById(id);

	// 把商品数据放在模型中
	modelMap.addAttribute("item", item);

	return "itemEdit";
}

4 绑定包装pojo

可以使用简单类型接受数据,也可以使用pojo接收数据

4.1 示例

  •     以将页面修改后的商品信息保存到数据库中(使用pojo接收参数)
  •     请求的url:/updateItem.action
  •     参数:表单中的数据。
  •     响应内容:更新成功页面

4.2  jsp页面

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

springmvc参数解析原理 springmvc 参数_springmvc参数解析原理

4.3 POJO类

package com.itykd.domain;
import java.util.Date;
public class Items {
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    private Date createtime;
    private String detail;
    //省略get、set方法
}

4.4 Controller类

@Controller
public class ItemsController {
	@Autowired
	private ItemsService itemsService;
        @RequestMapping("/updateItem")
        public String updateItem(Item item) {
	// 调用服务更新商品
	this.itemService.updateItemById(item);
	// 返回逻辑视图
	return "success";
    }    
}

5 绑定数组

可以绑定商品的id,然后再在数据库中查询并删除对应记录)。

5.1 修改pojo类

这里以包装的pojo类为例,添加一个Integer[] ids属性

package com.itykd.domain;
import java.util.List;
public class QueryVo {	
	private Items items;	
	private Integer[]ids;
    //省略get、set方法
}

5.2 修改jsp页面

:<td><input type="checkbox" name="ids" value="${item.id}"/></td>
    name的ids要和包装的pojo类的属性对应

<form action="${pageContext.request.contextPath }/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>商品id<input type="text" name="item.id" /></td>
<td>商品名称<input type="text" name="item.name" /></td>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
	<td>选择</td>
	<td>商品名称</td>
	<td>商品价格</td>
	<td>生产日期</td>
	<td>商品描述</td>
	<td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
	<td><input type="checkbox" name="ids" value="${item.id}"/></td>
	<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>

5.3 对应的Controller类的方法

这里采用了两种参数接收方法:①pojo的属性接收;②数组的直接接收

@RequestMapping("queryItem")
public String queryItem(QueryVo queryVo, Integer[] ids) {

	System.out.println(queryVo.getItem().getId());
	System.out.println(queryVo.getItem().getName());

	System.out.println(queryVo.getIds().length);
	System.out.println(ids.length);

	return "success";
}

6 绑定List

     比如:一次性进行多个商品的修改就要用到List参数

6.1 POJO类

   在POJO类添加一个private List<Items> itemList属性

public class QueryVo {	
	private Items items;	
	private Integer[]ids;	
	private List<Items>itemList;
}

6.2 修改JSP页面

name属性必须是list属性名+下标+元素属性
varStatus属性常用参数总结下:

  • ${current} 当前这次迭代的(集合中的)项
  • ${status.first}   判断当前项是否为集合中的第一项,返回值为true或false
  • ${status.last}    判断当前项是否为集合中的最后一项
  • ${status.index}   输出行号,从0开始。
  • ${status.count}   输出行号,从1开始。
  • ${status.后一项,返回值为true或false
  • begin、end、step分别表示:起始序号,结束序号,跳跃步伐。
<c:forEach items="${itemList }" var="item" varStatus="s">
<tr>
    <td><input type="checkbox" name="ids" value="${item.id} }"/></td>
    <td><input type="hidden" name="itemList[${s.index }].id" value="${item.id }"/></td>
    <td><input type="text" name="itemList[${s.index }].name" value="${item.name }"/></td>
    <td><input type="text" name="itemList[${s.index }].price" value="${item.price }"/></td>
    <td><input type="text" name="itemList[${s.index}].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
    <td><input type="text" name="itemList[${s.index }].detail" value="${item.detail }"/></td>
    <td><a href="${pageContext.request.contextPath }/item/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>

7 自定义参数绑定

比如日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定;

7.1 自定义Convecter类

package com.itykd.converter;

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

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

//Convecter<S,T>
//S:source,需要转换的源得了诶性
//T:target:需要转换的目标类型
public class DateConverter implements Converter<String,Date>{

	@Override
	public Date convert(String source) {
		try {
			if(source!=null) {
				//把字符串转换为日期类型
				DateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
				Date date = format.parse(source);
				return date;
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}
		//转换异常返回空
		return null;
	}

}

7.2  在springmvc.xml中配置Convecter

7.2.1 方法一(推荐)

配置注解驱动,并在注解驱动后加入conversion-service属性

<!-- 配置注解驱动 (加上了转换器)-->
    <mvc:annotation-driven conversion-service="conversionService"/>

然后配置convecter

<!-- 转换器的配置(方式1) -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.itykd.converter.DateConverter"/>       
            </set>
        </property>
    </bean>

7.2.2 方法二

该方法没有使用注解驱动的形式,因此需要自己手动配置处理器映射器和处理器适配器

<!-- 转换器的配置(方式2) -->
    <!-- 该方式需要独立配置处理器映射器和处理器适配器,不再使用注解驱动的方式 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="webBindingInitialzer" ref="customBinder"/>
    </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="com.itykd.converter.DateConverter"/>
            </set>
        </property>
    </bean>

运行程序,即可通过修改指定格式的日期,更新数据库