Spring Mvc Controller返回值、参数绑定、参数校验 (高级二)

1,Controller 返回值

  1. 返回moduleAndView
  2. 返回 String
  3. 返回void

2,Controller 参数绑定

       客户端请求携带的key/value 键值对 绑定到 Controller方法的形参上。

      1,默认支持的参数类型

          HttpServletRequest、HttpServletResponse、HttpSession、Model、ModelMap

          Model 将参数绑定到request域中。

     2,简单类型参数绑定

         @RequestParam 

          在不使用时,前端发送的参数key名应和Controller的方法名中参数名一致。

          当使用后,前端发送和后端接收参数名可以不一样,通过@RequestParam(value=”sendParamKey”) String reseveparamKey中        @RequestParam 中也可以指定一下属性:

        value指定前端发送的参数名,绑定到reseveparamKey中。

       required 属性限定改参数是否为必传传递;

       defaultValue 属性表示参数默认值。

    3,PoJo类绑定

        前提 :传递的参数key名应和pojo类的属性名一致。

    4,自定义参数绑定

举例:前台传递的 “1990/9/9 9:9:9” 绑定到后台的Pojo类的Date类型属性上

第一步:编写类实现 Converter<S,T>接口

public class CustomDateConverter implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return simpleDateFormat.parse(source);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

第二步:配置注册转换组件

<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
<!-- conversionService -->
<bean id="conversionService"
	class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<!-- 转换器 -->
	<property name="converters">
		<list>
		    <bean class="com.xiaohui.converter.CustomDateConverter"/>
		</list>
	</property>
</bean>

5,Pojo 包装类型参数

前台传递参数 classb.attr1=111 后台方法接收参数 classa;Classb 为classa的 属性类型;为了解决有时候请求中两个不同对象所含属性名相同,如果前台传参值说明属性名则系统不能区分传递给哪个对象的属性,故可以使用在进行一次包装。

6,数组绑定(包装类型接收)

页面定义如下:
页面选中多个checkbox向controller方法传递
<input type="checkbox" name="item_id" value="001"/>
<input type="checkbox" name="item_id" value="002"/>
<input type="checkbox" name="item_id" value="002"/>


传递到controller方法中的格式是:001,002,003

Controller方法中可以用String[]接收,定义如下:
public String deleteitem(String[] item_id)throws Exception{
		System.out.println(item_id);
}

 

7,List 参数绑定(包装类型接收)

List中存放对象,并将定义的List放在包装类中,action使用包装对象接收。

List中对象:
成绩对象
Public class QueryVo {
Private List<Items> itemList;//商品列表

  //get/set方法..
}

 

页面定义如下:


<tr>
    <td><input type="text" name=" itemsList[0].id" value="${item.id}"/></td>
    <td><input type="text" name=" itemsList[0].name" value="${item.name }"/></td>
    <td><input type="text" name=" itemsList[0].price" value="${item.price}"/></td>
</tr>
<tr>
    <td><input type="text" name=" itemsList[1].id" value="${item.id}"/></td>
    <td><input type="text" name=" itemsList[1].name" value="${item.name }"/></td>
    <td><input type="text" name=" itemsList[1].price" value="${item.price}"/></td>
</tr>

上边的静态代码改为动态jsp代码如下:
<c:forEach items="${itemsList }" var="item" varStatus="s">
<tr>
	<td><input type="text" name="itemsList[${s.index }].name" value="${item.name }"/> </td>
	<td><input type="text" name="itemsList[${s.index }].price" value="${item.price }"/></td>
	.....
	.....
</tr>
</c:forEach>

Contrller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
System.out.println(queryVo.getItemList());
}

8,其他参数类型绑定 Map

页面定义如下:

<tr>
<td>学生信息:</td>
<td>
姓名:<inputtype="text"name="itemInfo['name']"/>
年龄:<inputtype="text"name="itemInfo['price']"/>
.. .. ..
</td>
</tr>

Contrller方法定义如下:

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

3,参数校验

 

第一步:导入校验的相关依赖包

第二步:配置校验器

<!-- 校验器 -->
<bean id="validator"
		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
		<!-- 校验器-->
		<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>

第三步:请求方法上添加参数校验

注意:添加@Validated表示在对items参数绑定时进行校验,校验信息写入BindingResult中,在要校验的pojo后边添加BingdingResult, 一个BindingResult对应一个pojo,且BingdingResult放在pojo的后边。

// 商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(@Validated @ModelAttribute("item") Items items,BindingResult result,@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model) throws Exception {
	//如果存在校验错误则转到商品修改页面
	if (result.hasErrors()) {
		List<ObjectError> errors = result.getAllErrors();
		for(ObjectError objectError:errors){
		   System.out.println(objectError.getCode());
		   System.out.println(objectError.getDefaultMessage());
                }
	}
	return "item/editItem";
}

校验器注入到处理器适配器中

 

<mvc:annotation-driven conversion-servive="conversionService" validator="validator"> 
</mvc:annotation-driven>

在pojo中添加校验规则

public class Items {
    private Integer id;
    @Size(min=1,max=30,message="{item.name.length.error}")
    private String name;
    
    @NotEmpty(message="{pic.is.null}")
    private String pic;
错误消息文件CustomValidationMessages

item.name.length.error=商品名称在1到30个字符之间
pic.is.null=请上传图片

分组校验

如果两处校验使用同一个Items类则可以设定校验分组,通过分组校验可以对每处的校验个性化。

需求:商品修改提交只校验商品名称长度

分组就是一个标识,这里定义一个接口:

public interface ValidGroup1 {
}
public interface ValidGroup2 {
}

指定分组校验

public class Items {
    private Integer id;
//这里指定分组ValidGroup1,此@Size校验只适用ValidGroup1校验
    @Size(min=1,max=30,message="{item.name.length.error}",groups={ValidGroup1.class})
    private String name;
// 商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(@Validated(value={ValidGroup1.class}) @ModelAttribute("item") 
Items items,BindingResult result,@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model)throws Exception {

在@Validated中添加value={ValidGroup1.class}表示商品修改使用了ValidGroup1分组校验规则,也可以指定多个分组中间用逗号分隔,

@Validated(value={ValidGroup1.classValidGroup2.class })

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值