SpringMVC和Mybatis(三)pojo参数绑定、服务端校验、分组校验、数据回显

包装类型pojo参数绑定
商品查询controller方法中实现商品查询条件传入
第一种:在形参中添加HttpServletRequest request参数,通过request接收查询条件参数。
第二种:在形参中添加包装类型的pojo来接收查询参数。
分析:页面传入参数复杂
所以使用包装类型pojo


修改ItemsController.java
@Controller
@RequestMapping("/items")
public class ItemsController {
//注入service
@Autowired
private ItemsService itemsService;
//商品查询列表
//一般建议将url和方法名写成一样,方便queryItems和url进行映射,一个方法对应一个url
@RequestMapping("/queryItems")
public ModelAndView queryItems(ItemsQueryVo itemsQueryVo)throws Exception{
//调用service查找数据库,查询商品,这里先使用静态模拟
List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);


修改页面增加查询的input
itemsList.jsp
<body>
  <form action="${pageContext.request.contextPath }/items/queryItems.action" 


method="post">
  查询条件:
  <table width="100%" border=1>
  <tr>
  <td>
  商品名称:<input name="itemsCustom.name" />
  </td>
  <td><input type="submit" value="查询" /></td>
  </tr>
  </table>


在提交修改页面,也要增加包装类型的pojo,也就是说所有非简单类型的pojo,都需要多重包装,防止items


的name和user的name名称一致,无法传递参数。
ItemsCustomVo.java extends ItemsCustom.java
提交修改页面由ItemsCustom 改成ItemsCustomVo
页面使用ItemsCustom.name


集合类型绑定
批量删除、批量修改
数组绑定:批量删除
controller层:
重要:将页面选择(多选)的商品id,传到controller方法的形参,方法形参使用数组接收页面请求的多个


商品id。
修改itemsList.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
contentType="text/html; charset=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">
<html>
  <head>
    
    <title>check list</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


<script type="text/javascript">
function deleteItems(){
//提交form
document.itemsForm.action="${pageContext.request.contextPath 


}/items/deleteItems.action";
document.itemsForm.submit();
}
function queryItems(){
//提交form
document.itemsForm.action="${pageContext.request.contextPath 


}/items/queryItems.action";
document.itemsForm.submit();
}
</script>
  </head>
  
  <body>
  <form name="itemsForm" action="${pageContext.request.contextPath 


}/items/queryItems.action" method="post">
  查询条件:
  <table width="100%" border=1>
  <tr>
  <td>
  商品名称:<input name="itemsCustom.name" />
  </td>
  <td><input type="button" value="查询" οnclick="queryItems()"/>
  <input type="button" value="批量删除" οnclick="deleteItems()"/>
  </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="${itemsList }" var="item">
  <tr>
  <td><input type="checkbox" name="items_id" 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 }/items/editItems.action?id=


${item.id}">修改</a></td>
  </tr>
  </c:forEach>
  </table>
  </form>
  </body>
</html>


ItemsController.java
//批量删除
@RequestMapping("/deleteItems")
public String deleteItems(Model model,Integer[] items_id)throws Exception{
//service层的代码
return "success";
}


list绑定
将提交的数据绑定到list<pojo>中,比如:批量修改。
controller层:
1.进入批量商品的页面
2.批量修改商品提交
使用List来接收页面的数据,通过包装pojo接收。


ItemsQueryVo.java加set和get方法
public class ItemsQueryVo {
//商品信息包装进入
private Items items;


//为了系统可以扩展性,对商品信息定义扩展类
private ItemsCustom itemsCustom;

//批量商品信息
private List<ItemsCustom> itemsList;




ItemsController.java
//批量修改商品,将商品查询,在页面中批量编辑
//商品查询列表
//一般建议将url和方法名写成一样,方便queryItems和url进行映射,一个方法对应一个


url
@RequestMapping("/editItemsQuery")
public ModelAndView editItemsQuery(ItemsQueryVo itemsQueryVo)throws Exception{


List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);


ModelAndView modelAndView = new ModelAndView();


modelAndView.addObject("itemsList",itemsList);


modelAndView.setViewName("items/editItemsQuery");
return modelAndView;
}

//批量修改商品提交
@RequestMapping("/editItemsAllSubmit")
public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo)throws Exception{
//service层数据
return "success";
}


页面editItemsQuery.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
contentType="text/html; charset=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">
<html>
  <head>
    
    <title>check list</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


<script type="text/javascript">
function editItemsAllSubmit(){
//提交form
document.itemsForm.action="${pageContext.request.contextPath 


}/items/editItemsAllSubmit.action";
document.itemsForm.submit();
}
function queryItems(){
//提交form
document.itemsForm.action="${pageContext.request.contextPath 


}/items/queryItems.action";
document.itemsForm.submit();
}
</script>
  </head>
  
  <body>
  <form name="itemsForm" action="${pageContext.request.contextPath 


}/items/queryItems.action" method="post">
  查询条件:
  <table width="100%" border=1>
  <tr>
  <td>
  商品名称:<input name="itemsCustom.name" />
  </td>
  <td><input type="button" value="查询" οnclick="queryItems()"/>
  <input type="button" value="批量修改提交" οnclick="editItemsAllSubmit()"/>
  </td>
  </tr>
  </table>
  商品列表:
  <table width="100%" border=1>
  <tr>
  <td>商品名称</td>
  <td>商品价格</td>
  <td>生产日期</td>
  <td>商品描述</td>
  <td>操作</td>
  </tr>
  <c:forEach items="${itemsList }" var="item" varStatus="status">
  <tr>
  <td><input name="itemsList[${status.index }].name" value="${item.name }" 


/></td>
  <td><input name="itemsList[${status.index }].price" value="${item.price }" 


/></td>
  <td><input name="itemsList[${status.index }].createtime" value="<fmt:formatDate 


value="${item.createtime }" pattern="yyyy-MM-dd HH:mm:ss" />" /></td>
  <td><input name="itemsList[${status.index }].detail" value="${item.detail }" 


/></td>
  </tr>
  </c:forEach>
  </table>
  </form>
  </body>
</html>


<td><input name="itemsList[${status.index }].name" value="${item.name }" /></td>
name对应包装pojo中的list类型.属性名  ${status.index }下标从0开始   value默认对应前台页面查询到


的name


Map绑定
在包装类中定义Map对象,并添加get和set方法,action使用包装对象接收。
包装类中定义Map对象:
Public class QueryVo{
private Map<String, Object> itemInfo = new HashMap<String, Object>();
//get和set方法
}


页面定义
<tr>
<td>信息:</td>
<td>
姓名:<input type="text" name="itemInfo['name']" />
价格:<input type="text" name="itemInfo['price']" />
</td>
</tr>


controller:
public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
//service 层
System.out.println(queryVo.getStudentinfo());
}


===============================================================================================


========
服务端校验
项目中,最多的使用前端校验。对于安全要求高,在服务端校验。
控制层controller:校验页面请求的参数的合法性。对于手机、远程调用等其他平台来说,统一校验。
业务层service(主要):关键业务参数,仅限service接口的参数。
持久层dao:一般不校验。
springmvc校验使用hibernate的校验框架validation
思路:页面请求参数,请求到controller方法中,使用validation进行校验。出错,展示。
校验商品名称长度和生产日期非空


加入jar包
validation-api-1.0.0.GA.jar
jboss-logging-3.1.0.CR2.jar
hibernate-validator-4.3.0.Final.jar


配置校验器
springmvc.xml
<!-- 校验器 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- hibernate校验器 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 指定校验使用资源文件,如果不能确定则使用默认classpath下的


ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件 -->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="utf-8" />
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120" />
</bean>
</beans>


config创建CustomValidationMessages.properties


校验器注入到处理器适配器
springmvc.xml
<mvc:annotation-driven conversion-service="conversionService" 
validator="validator" ></mvc:annotation-driven>


配置方式2
<!-- 自定义webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
<!--注解适配器-->
<bean 


class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customerBinder">
</property>
</bean>




CustomValidationMessages.properties
#\u6DFB\u52A0\u6821\u9A8C\u9519\u8BEF\u63D0\u4EA4\u4FE1\u606F


items.name.length.error=\u8BF7\u8F93\u51651\u523030\u4E2A\u5B57\u7B26\u7684\u5546\u54C1\u540D


\u79F0
items.createtime.isNull.error=\u751F\u4EA7\u65E5\u671F\u4E0D\u80FD\u4E3A\u7A7A


在pojo添加校验规则
import javax.validation.constraints.NotNull;

import javax.validation.constraints.Size;

Items.java

public class Items {
    private Integer id;


    //校验名称在1到10字符中间
    @Size(min=1,max=10,message="{items.name.length.error}")
    private String name;


    private Float price;


    private String pic;


    @NotNull(message="{items.createtime.isNull.error}")
    private Date createtime;


ItemsController.java
//商品信息修改提交
//在要校验的参数前面添加注解,在参数后面添加参数来接收校验信息,是配对出现(一前一后)
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id,
@Validated ItemsCustom itemsCustom,BindingResult bindingResult)throws 


Exception{


//获取校验信息
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", allErrors);
}


itemsService.updateItems(id, itemsCustom);


return "items/editItems";
// return "forward:queryItems.action";
}


editItems.jsp
<body>
  <!-- 显示错误信息 -->
  <c:if test="${allErrors!=null }">
  <c:forEach items="${allErrors }" var="error">
  ${error.defaultMessage }<br />
  </c:forEach>
  </c:if>
=============================================================================
分组校验
定义多个校验分组(java接口),分组中定义哪些规则
每个controller方法使用不同校验分组。
在controller的包内再创建validation包再创建ValidGroup1.java
ValidGroup1.java
public interface ValidGroup1 {
//此分组校验商品名称长度
}
//不需要定义任何方法,对不同校验规则进行分组


在po包内找到validation的class,并添加注释内容group
Items.java
public class Items {
    private Integer id;


    //校验名称在1到30字符中间
    @Size(min=1,max=10,message="{items.name.length.error}",groups={ValidGroup1.class})
    private String name;


在商品修改提交的controller内同样增加注释内容value属性
//商品信息修改提交
//在要校验的参数前面添加注解,在参数后面添加参数来接收校验信息,是配对出现(一前一后)
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id,
@Validated(value={ValidGroup1.class}) ItemsCustom 


itemsCustom,BindingResult bindingResult)throws Exception{
========================================================================================
数据回显
pojo数据回显,springmvc自动带pojo数据回显,pojo数据已经放到request域内,key等于pojo类型(首字母


小写)
如果前台界面,没有用pojo类型定义key,就只能使用注解进行数据回显。修改前台页面的${itemsCustom.name}修改为${items.name},也就是没有用pojo类型定义key
@ModelAttribute可以指定pojo回显到页面,在request中的key
//商品信息修改提交
//在要校验的参数前面添加注解,在参数后面添加参数来接收校验信息,是配对出现(一前一后)
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id,
@ModelAttribute("items")@Validated(value={ValidGroup1.class}) 


ItemsCustom itemsCustom,BindingResult bindingResult)throws Exception{


@ModelAttribute还可以将方法的返回值传到页面
在商品查询的列表页面,通过商品类型查询商品信息。
在ItemsController.java
public class ItemsController {
//注入service
@Autowired
private ItemsService itemsService;

//商品的分类
@ModelAttribute("itemtypes")
public Map<String, String> getItemType(){
Map<String, String> itemTypes = new HashMap<String, String>();
itemTypes.put("101", "数码");
itemTypes.put("102", "母婴");
return itemTypes;
}
数码和母婴为静态数据,应该从数据库内查到。




itemsList.jsp
<td>
  商品名称:<input name="itemsCustom.name" />
  商品类型:
  <select name="itemtypes">
  <c:forEach items="${itemtypes }" var="itemtype">
  <option value="${itemtype.key }">${itemtype.value }</option>
  </c:forEach>
  </select>
 
  </td>
  <td><input type="button" value="查询" οnclick="queryItems()"/>
  <input type="button" value="批量删除" οnclick="deleteItems()"/>
  </td>




使用简单类型使用model进行回显,可以不用@ModelAttribute
model.addAttribute("allErrors", allErrors);
model.addAttribute("itemsCustom", itemsCustom);
return "items/editItems";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值