目录
项目准备
项目背景:商品加载页面与修改页面
添加itemEdit.jsp:
<%@ 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>
<span>${ msg }</span>
<!-- 上传图片是需要指定属性 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="id" value="${item.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${item.name }" /></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${item.price }" /></td>
</tr>
<tr>
<td>商品简介</td>
<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
一、SpringMVC默认支持的参数类型
需求:点击修改商品时,打开商品编辑页面,展示商品信息
1.ItemService接口
/**
* 跟据ID查询商品信息
* @param id
* @return
*/
Item getItemById(Integer id);
2.ItemServiceImpl实现类
@Override
public Item getItemById(Integer id) {
return itemMapper.selectByPrimaryKey(id);
}
3.ItemController
页面点击修改按钮,发送请求
需要从请求的参数中把请求的id取出来。id包含在Request对象中,可以从Request对象中取id。
想获得Request对象只需在controller方法的形参中添加一个参数即可,springmvc框架会自动把Request对象传递给方法。
/**
* 跟据ID查询商品信息,跳转修改商品页面
* 演示默认支持的参数传递
* Model/ModelMap返回数据模型
* @param request
* @param response
* @param session
* @return
*/
@RequestMapping("itemEdit")
public String itemEdit(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
//request获取参数
String idStr = request.getParameter("id");
//其他对象输出
System.out.println("response:" + response);
System.out.println("session:" + session);
// 查询商品信息
Item item = itemService.getItemById(new Integer(idStr));
//model返回数据模型
ModelAndView mav = new ModelAndView();
//把商品数据放在模型中
mav.addObject("item", item);
//设置逻辑视图
mav.setViewName("itemList");
return mav;
}
4.其他默认支持的参数类型
- HTTPServletRequest:通过request对象获取请求信息
- HTTPServletResponse:通过response对象处理响应信息
- HTTPSession:通过session对象得到session中存放的对象
5.Model/ModelMap
除了ModelAndView以外,还可以使用Model来向页面传递数据,Model是一个接口,在参数里直接声明Model即可。
如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。
不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。
- 例如查询商品信息:
/**
* 跟据ID查询商品信息,跳转修改商品页面
* 演示默认支持的参数传递
* Model/ModelMap返回数据模型
* @param request
* @return
*/
@RequestMapping("itemEdit")
public String itemEdit(Model model,HttpServletRequest request) {
String idStr = request.getParameter("id");
// 查询商品信息
Item item = itemService.getItemById(new Integer(idStr));
//model返回数据模型
model.addAttribute("item", item);
return "itemEdit";
}
- 例如修改商品信息:
@RequestMapping("updateItem")
public String updateItem(Item item,Model model){
itemService.updateItem(item);
model.addAttribute("item", item);
model.addAttribute("msg", "修改商品信息成功");
return "itemEdit";
}
ModelMap是Model接口的实现类,也可以通过ModelMap向页面传递数据,使用Model和ModelMap的效果一样,如果直接使用Model,springMVC会实例化ModelMap。
/**
* 跟据ID查询商品信息,跳转修改商品页面
* 演示默认支持的参数传递
* Model/ModelMap返回数据模型
* @param request
* @return
*/
@RequestMapping("itemEdit")
public String itemEdit(ModelMap model,HttpServletRequest request) {
String idStr = request.getParameter("id");
// 查询商品信息
Item item = itemService.getItemById(new Integer(idStr));
//model返回数据模型
model.addAttribute("item", item);
return "itemEdit";
}
二、SpringMVC简单参数绑定
当请求的参数名称和处理器形参名称一致时,会将请求参数与形参进行绑定,这样,从Request取参数的方法可以进一步简化。
@RequestMapping("itemEdit")
public String itemEdit(Model model,int id) {
// 查询商品信息
Item item = this.itemService.getItemById(id);
//model返回数据模型
model.addAttribute("item", item);
return "itemEdit";
}
1.支持的数据类型
- 整形: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)
2.@RequestParam
常用于简单参数类型的绑定
- value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数区中的名字为Id的参数的值将传入
- required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错 TTP Status 400 - Required Integer parameter 'XXX' is not present.
- defaultValue:默认值,表示如果请求中没有同名参数时的默认值
/**
* 演示简单参数传递
* 跳转修改商品信息页面
* @RequestParam用法:入参名字与方法名参数名不一致时使用{
* value:传入的参数名,required:是否必填,defaultValue:默认值
* }
*
*/
@RequestMapping("itemEdit")
public ModelAndView itemEdit(@RequestParam(value="id",required=true,defaultValue="1")Integer ids){
ModelAndView mav = new ModelAndView();
//查询商品信息
Item item = itemServices.getItemById(ids);
//设置商品数据返回页面
mav.addObject("item", item);
//设置视图名称
mav.setViewName("itemEdit");
return mav;
}
三、绑定普通pojo类型
需求:将页面修改后的商品信息保存到数据库中
需求分析:
- 请求的url:/updateitem.action
- 参数:表单中的数据
- 响应内容:更新成功过页面
使用pojo接收表单数据:如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接收数据,也可以使用pojo接收数据
注:pojo对象中的属性名和表单中input的name属性一致
1.页面定义如下:
<form id="itemForm" action="${pageContext.request.contextPath }/updateItem.action" method="post">
<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${item.name }" /></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${item.price }" /></td>
</tr>
<tr>
<td>商品简介</td>
<td><textarea rows="3" cols="30" name="detail">${item.detail}</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
2.pojo类如下:
public class Item {
private Integer id;
private String name;
private Float price;
private String detail;
private String pic;
private Date createtime;
get/set
}
请求的参数名称和pojo属性名称一致,会自动将请求参数赋值给pojo属性。
3.ItemService接口
/**
* 修改商品信息
* @param item
*/
void updateItem(Item item);
4.ItemServiceImpl实现类
@Override
public void updateItem(Item item) {
itemMapper.updateByPrimaryKeySelective(item);
}
5.controller
/**
* 修改商品
* 演示pojo参数绑定
* @param item
* @return
*/
@RequestMapping("updateItem")
public String updateItem(Item item,Model model){
itemService.updateItem(item);
model.addAttribute("item", item);
model.addAttribute("msg", "修改商品信息成功");
return "itemEdit";
}
6.解决post乱码问题
在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>
7.解决get乱码问题
- 方法一:修改tomcat配置文件添加编码与工程一致:
- 方法二:对参数进行重新编码
ISO8895-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码。
四、绑定包装的pojo类型
需求:使用包装的pojo接收商品信息的查询条件
1.包装对象定义如下:
/**
* 包装的pojo传递
* @author Steven
*
*/
public class QueryVo {
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
2.页面定义:
<tr>
<td>商品名称:<input type="text" name="item.name"></td>
<td>商品价格:<input type="text" name="item.price"></td>
</tr>
3.controller代码:
@RequestMapping("queryItem")
public String queryItem(QueryVo vo,Model model){
if(vo.getItem() != null){
System.out.println(vo.getItem());
}
//模拟搜索商品
List<Item> itemList = itemService.getItemList();
model.addAttribute("itemList", itemList);
return "itemList";
}
五、自定义参数绑定
需求:在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式
需求分析:
由于日期数据有很多种格式。springmvc没办法把字符串转换成日期类型,所以需要自定义参数绑定。
前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。
一般使用<mvc:annotation-driven/>注解驱动加载处理器适配器,可以在此标签上进行配置。
1.修改jsp页面
itemEdit.jsp:
<tr>
<td>商品日期</td>
<td><input type="text" name="createtime"
value="<fmt:formatDate value="${item.price }" pattern="yyyy-MM-dd-HH:mm:ss" /></td>
</tr>
2.自定义Converter
/*
* Converter<S, T>
* S:source 需要转换的源的类型
* T:target 需要转换的目标类型
*/
public class DateConverter implements Converter<String, Date>{
@Override
public Date convert(String source) {
try {
//把字符串转换为日期类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
//如果转换异常则返回空
return null;
}
}
3.配置Converter
- 方式一:
<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
<mvc:annotation-driven conversion-service="conversionService" />
<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.rosinante.springmvc.util.DateConverter"></bean>
</set>
</property>
</bean>
- 方式二:
<!-- 注解适配器 -->
<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="com.rosinante.springmvc.util.DateConverter"></bean>
</set>
</property>
</bean>
注:此方法需要独立配置处理器映射器、适配器,不再使用<mvc:annotation-driven/>。