Springmvc和mybatis整合(三):参数绑定:过程,默认支持类型,简单类型,pojo绑定;整体实例;解决日期类型问题以及中文提交乱码问题;Springmvc和struts2区别

参数绑定

1.spring参数绑定过程
从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到Controller方法形参上.
注意:springmvc中,接收页面提交的数据是通过方法形参来接收。而不是在Controller类定义成员变更接收

参数绑定过程:
	1.客户端请求(key/value)
	2.处理器适配器调用springmvc提供参数绑定组件将key/value数据转成Controller方法的形参
		参数绑定组件:在springmvc早期版本使用PropertyEditor(只能将字符串转换成java对象)后期使用converter(进行任意类型的转换)springmvc提供了很多converter(转换器)在特殊情况下需要自定义converter对日期数据绑定需要自定义converter
	3.Controller方法(形参)
2.默认支持类型
直接在Controller方法形参上定义下边类型的对象,就可以使用这些对象。在参数绑定过程中。如果遇到下边类型直接进行绑定
1.HttpServletRequest:通过Request对象获取请求信息
2.HttpServletResponse:通过Response处理响应信息
3.HttpSession:通过Session对象得到Session中存放的对象
4.Model/ModelMap:model是一个接口,modelMap是一个接口实现
	作用:将model数据填充到Request域
3.简单类型
通过@RequestParam对简单类型的参数进行绑定
如果不使用@RequestParam,要求Request传入参数名称和Controller方法的形参名称一致,方可绑定成功
如果使用@RequestParam,不用限制Request传入参数名称和Controller方法的形参名称一致
通过required属性指定参数是否必须要传入,如果设置为true,没有传入参数,会报错误
eg:通过参数进行传入ItemsController.java中
@RequestMapping(value = "/editItems", method = {RequestMethod.POST,RequestMethod.GET})
//@RequestParam指定传入参数和形参进行绑定 required必须传入
public String editItems(Model model,@RequestParam(value = "id",required = true) Integer items_id) throws Exception{
	//调用service查询商品信息
	ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
	
	//相当于modelandview。addobject方法
	model.addAttribute("itemsCustom",itemsCustom);
	
	return "items/editItems";
}
4.pojo绑定
页面中input的name和Controller的pojo形参中的属性名一致,将页面数据绑定到pojo
	eg:
	1.页面定义:editItems.jsp
		<table width="100%" border="1">
		<tr>
			<td>商品信息</td>
			<td><input type="text" name="name" value="${itemsCustom.name}"/></td>
		</tr>
		<tr>
			<td>商品价格</td>
			<td><input type="text" name="price" value="${itemsCustom.price}"/></td>
		</tr>
	2.Controller的pojo形参的定义
	public class Items {
			private Integer id;

		private String name;
整体程序:

容器配置参照Spring与Mybatis整合(一)
1.Dao层(逆向工程生成实体类,mapper接口,mapper映射)
2.Service层

接口:
public interface ItemsService {
	
	//查询商品列表
	public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;

	//根据id查询商品信息
	//id:商品的id
	public ItemsCustom findItemsById(Integer id) throws Exception;
	
	//修改商品信息
	//id:修改商品的id
	//itemsCustom:修改的商品信息
	public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception;
}
实现类:
public class ItemsServiceImpl implements ItemsService {
	
	@Autowired
	private ItemsMapperCustom itemsMapperCustom;
	
	@Autowired
	private ItemsMapper itemsMapper;

	@Override
	public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
		// TODO Auto-generated method stub
		return itemsMapperCustom.findItemsList(itemsQueryVo);
	}

	@Override
	public ItemsCustom findItemsById(Integer id) throws Exception {
		// TODO Auto-generated method stub
		Items items = itemsMapper.selectByPrimaryKey(id);
		//中间会进行一些业务上的处理 返回ItemsCustom
		ItemsCustom itemsCustom = new ItemsCustom();
		//将Items属性值拷贝到ItemsCustom中 使用BeanUtils
		BeanUtils.copyProperties(items, itemsCustom);
		return itemsCustom;
	}

	@Override
	public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
		// TODO Auto-generated method stub
		//添加业务校验,对参数进行校验
		//校验id不能为空
		itemsCustom.setId(id);
		
		//更新商品信息
		itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
		
	}
}

3.Controller层

@Controller
//为了对url进行分类管理,可以在这里定义根路径,最终访问url是根路径+子路径
//比如:商品列表:/items/queryItems.action
@RequestMapping("/items")
public class ItemsController {
	@Autowired
	private ItemsService itemsService;
	
	//访问路径/items/queryItems.action
	@RequestMapping("/queryItems.action")
	public ModelAndView queryItems() throws Exception{
		
		System.out.println("items controller....");
		List<ItemsCustom> itemsList = itemsService.findItemsList(null);
		
		ModelAndView mv = new ModelAndView();
		
		mv.addObject("itemsList",itemsList);
		
		mv.setViewName("items/itemsList");
		
		return mv;
	}
	
//	@RequestMapping(value = "/editItems", method = {RequestMethod.POST,RequestMethod.GET})
//	public String editItems(Model model) throws Exception{
//		//调用service查询商品信息
//		ItemsCustom itemsCustom = itemsService.findItemsById(1);
//		
//		//相当于modelandview。addobject方法
//		model.addAttribute("itemsCustom",itemsCustom);
//		
//		return "items/editItems";
//	}
	
	@RequestMapping(value = "/editItems", method = {RequestMethod.POST,RequestMethod.GET})
	//@RequestParam指定传入参数和形参进行绑定 required必须传入
	public String editItems(Model model,@RequestParam(value = "id",required = true) Integer items_id) throws Exception{
		//调用service查询商品信息
		ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
		
		//相当于modelandview。addobject方法
		model.addAttribute("itemsCustom",itemsCustom);
		
		return "items/editItems";
	}
	
	@RequestMapping(value = "/editItemsSubmit")
	public String editItemsSubmit(Integer id,ItemsCustom itemsCustom) throws Exception{
		//调用Service商品更新
		itemsService.updateItems(id, itemsCustom);
		
		return "redirect:queryItems.action";
	}
}

4.视图解析

主页:
</head>
<body>
	<!-- 5.视图解析 -->
商品列表
<table width="100%" border="1">
	<tr>
		<td>商品名称</td>
		<td>商品价格</td>
		<td>生产日期</td>
		<td>商品描述</td>
		<td>操作</td>
	</tr>
	<c:forEach items="${itemsList}" var="item">
		<tr>
			<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}/items/editItems.action?id=${item.id}">修改</a></td>
			</tr>
		</c:forEach>
	</table>
	</body>
	修改页:
	<head>
	<meta charset="UTF-8">
	<title>修改商品信息</title>
	</head>
	<body>
		<form id="itemForm" action="${pageContext.request.contextPath}/items/editItemsSubmit.action" method="post">
			<input type="hidden" name="id" value="${itemsCustom.id}"/>
			修改商品信息
			<!-- 属性名name会绑定到Controller要与pojo属性名一致 -->
			<table width="100%" border="1">
				<tr>
					<td>商品信息</td>
					<td><input type="text" name="name" value="${itemsCustom.name}"/></td>
				</tr>
				<tr>
					<td>商品价格</td>
					<td><input type="text" name="price" value="${itemsCustom.price}"/></td>
				</tr>
				<tr>
					<td>商品生产日期</td>
					<td><input type="text" name="createtime" value='<fmt:formatDate value="${itemsCustom.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>'/></td>
				</tr> 
				<tr>
					<td>商品简介</td>
					<td>
						<textarea rows="3" cols="30" name="detail">${itemsCustom.detail}</textarea>
					</td>
				</tr>
				<tr>
					<td colspan="2" align="center">
						<input type="submit" value="提交">
					</td>
				</tr>
			</table>
		</form>
	</body>

以上程序问题

1.日期会遇到类型不匹配
2.中文提交会遇到乱码问题

基于以上问题

5.自定义参数绑定实现日期类型绑定
对于Controller形参中pojo对象,如果属性中有日期类型,需要自定义参数绑定。
将请求日期数据串传成日期类型,要转化的日期类型和pojo中日期属性的类型保持一致

eg:日期问题
1.先确定日期类型Date(Util)
2.配置日期转换器(Converter)

public class CustomDateConverter implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		// TODO Auto-generated method stub
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			return sdf.parse(source);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

如果转换格式不为yyyy-MM-dd HH:mm:ss:可以配置if判断写多种转换格式
2.在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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:component-scan base-package="cn.hp.ssm.controller"></context:component-scan>
	
	<!-- 将自定义绑定参数的Bean与mvc进行关联conversion-service="conversionService" 进行对应-->
	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 自定义参数绑定 -->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<!-- 转换器 -->
		<property name="converters">
			<list>
				<!-- 日期类型转换 -->
				<bean class="cn.hp.ssm.controller.converter.CustomDateConverter"></bean>
			</list>
		</property>
	</bean>
</beans>

eg:乱码问题
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>

以上可以解决post请求乱码问题

对于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")
Springmvc和struts2区别
1.springmvc基于方法开发的,struts2基于类开发的
springmvc将url和Controller方法映射,映射成功后springmvc生成一个Handler对象,对象中只包括了一个method.方法执行结束,形参数据销毁.
springmvc的Controller开发类似Service开发
2.springmvc可以进行单例开发(因为Controller 参数都在方法里),并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例
3.经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值