参数绑定,Controller返回值,@RequestMapping
个人博客:www.xiaobeigua.icu
参数绑定
默认支持的参数类型
1、HttpServletRequest,HttpServletResponse,HttpSession
页面点击修改按钮,发起请求: http://localhost:8080/itemEdit.action?id=1 ,需要从请求的参数中把请求的id取出来。Id包含在Request对象中。可以从Request对象中取id。获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。
@RequestMapping(value = "/itemEdit.action")
public ModelAndView toEdit(HttpServletRequest request) {
String id = request.getParameter("id");
return null;
}
除了可以在方法中添加HttpServletRequest形参之外,还可以添加其他的默认支持的参数类型,处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。
HttpServletRequest:通过request对象获取请求信息
HttpServletResponse:通过response处理响应信息
HttpSession:通过session对象得到session中存放的对象
.
.
2、Model
除了ModelAndView以外,还可以使用Model来向页面传递数据,Model是一个接口,在参数里直接声明model即可。
如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。
不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。
.
代码实现:
/**
* 根据id查询商品,使用Model
*
* @param request
* @param model
* @return
*/
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, Model model) {
// 从request中获取请求参数
String strId = request.getParameter("id");
Integer id = Integer.valueOf(strId);
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);
// 把结果传递给页面
// ModelAndView modelAndView = new ModelAndView();
// 把商品数据放在模型中
// modelAndView.addObject("item", item);
// 设置逻辑视图
// modelAndView.setViewName("itemEdit");
// 把商品数据放在模型中
model.addAttribute("item", item);
return "itemEdit";
}
3、ModelMap
ModelMap是Model接口的实现类,也可以通过ModelMap向页面传递数据。使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。
代码实现:
/**
* 根据id查询商品,使用ModelMap
*
* @param request
* @param model
* @return
*/
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, ModelMap model) {
// 从request中获取请求参数
String strId = request.getParameter("id");
Integer id = Integer.valueOf(strId);
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);
// 把结果传递给页面
// ModelAndView modelAndView = new ModelAndView();
// 把商品数据放在模型中
// modelAndView.addObject("item", item);
// 设置逻辑视图
// modelAndView.setViewName("itemEdit");
// 把商品数据放在模型中
model.addAttribute("item", item);
return "itemEdit";
}
绑定简单类型
当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。这样,从Request取参数的方法就可以进一步简化。
/
**
* 根据id查询商品,绑定简单数据类型
*
* @param id
* @param model
* @return
*/
@RequestMapping("/itemEdit")
public String queryItemById(int id, ModelMap model) {
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);
// 把商品数据放在模型中
model.addAttribute("item", item);
return "itemEdit";
}
参数类型推荐使用包装数据类型,因为基础数据类型不可以为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 id,
ModelMap modelMap) {
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);
// 把商品数据放在模型中
modelMap.addAttribute("item", item);
return "itemEdit";
}
绑定pojo类型
如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接受数据,也可以使用pojo接收数据。要求:pojo对象中的属性名和表单中input的name属性一致。
.
.
示例:
页面定义如下图:
pojo如下图:
请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。
注意:提交的表单中不要有日期类型的数据,否则会报400错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。
.
.
解决post乱码问题:
提交发现,保存成功,但是保存的是乱码,在web.xml中加入:
<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编码
绑定包装pojo
包装对象定义如下:
public class QueryVo {
private Item item;
set/get。。。
}
页面定义如下图:
.
处理如下:
// 绑定包装数据类型
@RequestMapping("/queryItem")
public String queryItem(QueryVo queryVo) {
System.out.println(queryVo.getItem().getId());
System.out.println(queryVo.getItem().getName());
return "success";
}
自定义参数绑定
由于日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。
前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。
一般使用<mvc:annotation-driven/>
注解驱动加载处理器适配器,可以在此标签上进行配置。
如下图修改itemEdit.jsp页面,显示时间
自定义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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 如果转换异常则返回空
return null;
}
}
配置Converter
我们同时可以配置多个的转换器。
<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.itcast.springmvc.converter.DateConverter" />
</set>
</property>
</bean>
配置方式2(了解)
<!--注解适配器 -->
<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>
注意:此方法需要独立配置处理器映射器、适配器,不再使用mvc:annotation-driven/
高级参数绑定
绑定数组
表单如下:
商品id | 商品名称 |
<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
选择 | 商品名称 | 商品价格 | 生产日期 | 商品描述 | 操作 |
${item.name } | ${item.price } | ${item.detail } |
页面选中多个checkbox向controller方法传递,本身属于一个form表单,提交url是queryItem.action
Controller方法中可以用String[]接收,或者pojo的String[]属性接收。两种方式任选其一即可。定义QueryVo,如下图:
.
ItemController修改queryItem方法:
/**
* 包装类型 绑定数组类型,可以使用两种方式,pojo的属性接收,和直接接收
*
*
@param queryVo
* @return
*/
@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";
}
将表单的数据绑定到List
定义pojo,List中存放对象,并将定义的List放在包装类QueryVo中,使用包装pojo对象接收,如下图:
前端页面应该显示的html代码,如下图:
分析发现:name属性必须是list属性名+下标+元素属性。Jsp做如下改造:
<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 }"/>
<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 }/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
${current} 当前这次迭代的(集合中的)项
${status.first} 判断当前项是否为集合中的第一项,返回值为true或false
${status.last} 判断当前项是否为集合中的最
varStatus属性常用参数总结下:
${status.index} 输出行号,从0开始。
${status.count} 输出行号,从1开始。
${status.后一项,返回值为true或false
begin、end、step分别表示:起始序号,结束序号,跳跃步伐。
.
.
测试效果如下图:
注意:接收List类型的数据必须是pojo的属性,如果方法的形参为ArrayList类型无法正确接收到数据。
。
。
。
@RequestMapping
通过@RequestMapping注解可以定义不同的处理器映射规则。
URL路径映射
@RequestMapping(value=“item”)或@RequestMapping("/item"),value的值是数组,可以将多个url映射到同一个方法
/**
* 查询商品列表
* @return
*/
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() {
// 查询商品数据
List<Item> list = this.itemService.queryItemList();
// 创建ModelAndView,设置逻辑视图名
ModelAndView mv = new ModelAndView("itemList");
// 把商品数据放到模型中
mv.addObject("itemList", list);
return mv;
}
添加在类上面
在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头。可以使用此方法对url进行分类管理 如下图:
此时需要进入queryItemList()方法的请求url为:http://127.0.0.1:8080/springmvc-web2/item/itemList.action或者http://127.0.0.1:8080/springmvc-web2/item/itemListAll.action
请求方法限定
除了可以对url进行设置,还可以限定请求进来的方法
限定GET方法:@RequestMapping(method = RequestMethod.GET),此时如果通过POST访问则**报错:**HTTP Status 405 - Request method ‘POST’ not supported。
限定POST方法:@RequestMapping(method = RequestMethod.POST),如果通过GET访问则报错:HTTP Status 405 - Request method ‘GET’ not supported
GET和POST都可以:@RequestMapping(method {RequestMethod.GET,RequestMethod.POST})
。
.
.
.
Controller方法返回值
返回ModelAndView
controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。
返回void
在Controller方法形参上可以定义request和response,使用request或response指定响应结果:
1、使用request转发页面,如下:
request.getRequestDispatcher("页面路径").forward(request, response)
request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
2、可以通过response页面重定向:
response.sendRedirect("url")
response.sendRedirect("/springmvc-web2/itemEdit.action");
3、可以通过response指定响应结果,例如响应json数据如下:
response.getWriter().print("{\"abc\":123}");
/**
* 返回void测试
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("queryItem")
public void queryItem(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 1 使用request进行转发
// request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,
// response);
// 2 使用response进行重定向到编辑页面
// response.sendRedirect("/springmvc-web2/itemEdit.action");
// 3 使用response直接显示
response.getWriter().print("{\"abc\":123}");
}
返回字符串
controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
//指定逻辑视图名,经过视图解析器解析为jsp物理路径:/WEB-INF/jsp/itemList.jsp
return “itemList”;
Redirect重定向
Contrller方法返回字符串可以重定向到一个url地址,如下商品修改提交后重定向到商品编辑页面。
/**
* 更新商品
*
* @param item
* @return
*/
@RequestMapping("updateItem")
public String updateItemById(Item item) {
// 更新商品
this.itemService.updateItemById(item);
// 修改商品成功后,重定向到商品编辑页面
// 重定向后浏览器地址栏变更为重定向的地址,
// 重定向相当于执行了新的request和response,所以之前的请求参数都会丢失
// 如果要指定请求参数,需要在重定向的url后面添加 ?itemId=1 这样的请求参数
return "redirect:/itemEdit.action?itemId=" + item.getId();
}
.
forward转发
Controller方法执行后继续执行另一个Controller方法。如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。
/**
* 更新商品
*
* @param item
* @return
*/
@RequestMapping("updateItem")
public String updateItemById(Item item) {
// 更新商品
this.itemService.updateItemById(item);
// 修改商品成功后,重定向到商品编辑页面
// 重定向后浏览器地址栏变更为重定向的地址,
// 重定向相当于执行了新的request和response,所以之前的请求参数都会丢失
// 如果要指定请求参数,需要在重定向的url后面添加 ?itemId=1 这样的请求参数
// return "redirect:/itemEdit.action?itemId=" + item.getId();
// 修改商品成功后,继续执行另一个方法
// 使用转发的方式实现。转发后浏览器地址栏还是原来的请求地址,
// 转发并没有执行新的request和response,所以之前的请求参数都存在
return "forward:/itemEdit.action";
}
//结果转发到editItem.action,request可以带过去
return "forward: /itemEdit.action";