SpringMVC参数绑定
1、默认获取参数方式
这种方式是通过servletrequest获取指定的参数:
/**
* springmvc中默认支持的类型,可以加也可以不加
* @param req
* @param rep
* @param model
* @param session
* @return
*/
@RequestMapping("/itemEdit")
public String itemEdit(HttpServletRequest req,HttpServletResponse rep,Model model) {
Integer id = Integer.parseInt(req.getParameter("id"));
Items items=itemsService.findItemsById(id);
// Model其实就是使用request传递参数,只是对request进行了扩展
model.addAttribute("item", items);
// 如果返回的是一个简单的字符串,SpringMvc就会认为这是一个页面
return "editItem";
}
2、使用基本数据类型接收参数(包括String类型)
input或者url中参数名称必须和Controller中形参名称一致:
页面:
<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>
Controller:
@RequestMapping("/updateitem")
public String updateItem(Integer id ,String name ,Float price,String detail) {
Items items = new Items();
items.setId(id);
items.setName(name);
items.setPrice(price);
items.setDetail(detail);
items.setCreatetime(new Date());
itemsService.updateItems(items);
return "success";
}
}
问题:这种方式存在中文乱码问题
a、post提交方式,可以在web.xml中配置过滤器
<!-- 解决post乱码问题 -->
<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>
b、get提交解决中文乱码
第一种方式:在tomcat的conf目录下配置编码格式
<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编码
3、pojo类型接收参数
// 接受pojo类型、要求页面个的属性名称必须和接受参数的pojo类型参数属性名一致
@RequestMapping("/updateitem")
// public String updateItem(Integer id ,String name ,Float price,String detail) {
public String updateItem(Items items) {
// Items items = new Items();
// items.setId(id);
// items.setName(name);
// items.setPrice(price);
// items.setDetail(detail);
items.setCreatetime(new Date());
itemsService.updateItems(items);
return "success";
}
4、接收VO(用于高级查询)
使用高级查询的时候传入参数:如果COntroller中接收的是VO,那么input中的name必须是属性名.属性名.属性名.....
页面:
<form action="${pageContext.request.contextPath }/queryitem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>商品名称:<input type="text" name="item.name" /></td>
<td>商品价格:<input type="text" name="item.price" /></td>
<td><input type="submit" value="查询"/></td>
VO:
import cn.lier.pojo.Items;
public class QueryVO {
// 商品对象
private Items item;
// 用户对象
// 订单对象
// ....
public Items getItem() {
return item;
}
public void setItem(Items item) {
this.item = item;
}
}
Controller:
// <!-- 如果Controller中 接收的是vo,那么Input中name必须是vo中的属性名.属性名.属性名... -->
@RequestMapping("/queryitem")
public String serach(QueryVO vo) {
System.out.println(vo);
return "";
}
5、日期转换器
Springmvc无法自动的将日期字符串转换成日期类型,它会报错,所以需要申明一个日期转换器:
创建一个全局日期转换器,将这个转化器加载到注解驱动上,如果不放在这,那么需要手动配置适配器的时候装配上这个转换器:
全局日期转化字符串转日期类型:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* s-source源
* t-target目标
* @author lxj
*/
public class CustomGlobleStrTODateConverter implements Converter<String, Date> {
@Override
public Date convert(String str) {
try {
Date date =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
return date;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
SpringMVC.xml文件配置
1、定义全局日期转换器:
<!-- 配置自定义转换器一定要将自定义的转化器配置到注解驱动上面 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 可以定义多个转化器 -->
<bean class="cn.lier.convert.CustomGlobleStrTODateConverter"></bean>
</set>
</property>
</bean>
2、在注解驱动中配置转换器:
<!-- 注解驱动自动的帮我们找到最新的处理器映射器和处理器适配器 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
3、了解下手动配置转换器:
<!--转换器配置-->
<beanid="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<propertyname="converters">
<set>
<bean class="cn.itcast.springmvc.convert.DateConverter"/>
</set>
</property>
</bean>
<!--自定义webBinder-->
<beanid="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<propertyname="conversionService"ref="conversionService"/>
</bean>
<!--注解适配器-->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<propertyname="webBindingInitializer"ref="customBinder"></property>
</bean>
<!--注解处理器映射器-->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
6、数组参数
用途:一般是在批量操作使用,如批量删除,修改。
页面:
<tr>
<!-- checkbox的name属性名必须和vo数组的属性名一致 -->
<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>
VO:
public class QueryVO {
// 商品对象
private Items item;
// 批量删除
private Integer[] ids;
// 用户对象
// 订单对象
// ....
public Items getItem() {
return item;
}
}
COntroller:
@RequestMapping("delAll")
public String delAll(QueryVO vo) {
// 如果是批量删除,一堆复选框的,只有复选框被选中才能提交js校验
System.out.println(vo);
return "";
}
批量修改:扩展VO
页面:
<c:forEach items="${itemlist}" var="item" varStatus="status">
<tr>
<!--批量修改:可以用List<pojo>来接受,页面上的Input的name属性值=vo的属性集合名称+[list的下标]+list的泛型的属性名称 -->
<td><input type="checkbox" name="ids" value="${item.id}"/>
<input type="hidden" name="itemsList[${status.index}].id" value="${item.id}"/></td>
<td><input type="text" name="itemsList[${status.index}].name" value="${item.name }"/></td>
<td><input type="text" name="itemsList[${status.index}].price" value="${item.price }"/></td>
<td><input type="text" name="itemsList[${status.index}].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
<td><input type="text" name="itemsList[${status.index}].detail" value="${item.detail }"/></td>
<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
vo:
public class QueryVO {
// 商品对象
private Items item;
// 批量删除
private Integer[] ids;
// 用户对象
// 订单对象
// ....
private List<Items> itemsList;
public List<Items> getItemsList() {
return itemsList;
}
public void setItemsList(List<Items> itemsList) {
this.itemsList = itemsList;
}
public Items getItem() {
return item;
}
public void setItem(Items item) {
this.item = item;
}
public Integer[] getIds() {
return ids;
}
public void setIds(Integer[] ids) {
this.ids = ids;
}
}
Controller:
@RequestMapping("updateAll")
public String updateAll(QueryVO vo) {
System.out.println(vo);
return "";
}