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> {@Overridepublic 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,003Controller方法中可以用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;
错误消息文件CustomValidationMessagesitem.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 })

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

  1. 深入理解Spring MVC Controller返回String类型导致中文乱码的问题。

    代码 在Controller层写下如下的测试代码: @GetMappingpublic String test() {return "这是一个中文句子";} 调试 在return返 ...

  2. Spring MVC Controller中返回json数据中文乱码处理

    问题 在使用spring MVC Controller的过程中,发现返回到客户端的的中文出现乱码.后台Java代码: @RequestMapping(value = "/upload&quo ...

  3. [转载]Asp.net MVC中Controller返回值类型

    Asp.net MVC中Controller返回值类型 在mvc中所有的controller类都必须使用"Controller"后缀来命名 并且对Action也有一定的要求: 必须 ...

  4. java注解返回不同消息,Spring MVC Controller中的一个读入和返回都是JSON的方法如何获取javax.validation注解的异常信息...

    Spring MVC Controller中的一个读入和返回都是JSON的方法怎么获取javax.validation注解的错误信息? 本帖最后由 LonelyCoder2012 于 2014-03- ...

  5. Python函数01/函数的初识/函数的定义/函数调用/函数的返回值/函数的参数

    Python函数01/函数的初识/函数的定义/函数调用/函数的返回值/函数的参数 内容大纲 1.函数的初识 2.函数的定义 3.函数的调用 4.函数的返回值 5.函数的参数 1.函数初识 # def ...

  6. 关于ExecuteNonQuery执行存储过程的返回值 、、实例讲解存储过程的返回值与传出参数、、、C#获取存储过程的 Return返回值和Output输出参数值...

    关于ExecuteNonQuery执行存储过程的返回值 用到过ExecuteNonQuery()函数的朋友们在开发的时候肯定这么用过. if(cmd.ExecuteNonQuery("xxx ...

  7. 函数二的变量作用域,多函数执行,返回值,函数参数,拆包,引用

    函数二 一.变量作用域 1.局部变量是函数内部变量,在函数临时保存数据,函数调用完则销毁,在函数外访问即报错 2.全局变量函数内外都可访问,当不同函数都要用到某一变量时,则可使用全局变量 def fu ...

  8. Spring MVC Controller 要点

    2019独角兽企业重金招聘Python工程师标准>>> 今天看到一篇讲解 Spring MVC Controller 的文章,比较详细,顺道翻译下. 在 Spring MVC 中,我 ...

  9. spring mvc controller间跳转 重定向 传参

    spring mvc controller间跳转 重定向 传参 1. 需求背景     需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形 ...

最新文章

  1. [祝]微软山西DotNet俱乐部(高校行系列)山西大学公益讲座
  2. 群聊:项目级的错误处理
  3. 前馈pid系数_SPMSM控制——基于模型的电流前馈控制及思考
  4. java servicefactory_Java DirectoryServiceFactory.getDirectoryService方法代碼示例
  5. asp.net web常用控件FileUpload(文件上传控件)
  6. Win32下 Qt与Lua交互使用(二):在Lua脚本中使用Qt类
  7. 老男孩和门户网站学生聊天整理
  8. TypeSDK免费手游多渠道SDK接入方案
  9. mfc三视图和斜等测图实现_编程实现TCP协议数据传输
  10. 荣新广源B班20121207作业
  11. 怎么报名mysql证书_报考oraclemysql认证考试的流程有哪些
  12. Ubuntu编译并安装voip服务器软件Asterisk
  13. 斐讯K2_V22.5.9.163刷华硕固件--详细教程
  14. MATLAB读取10bit的raw格式图片代码
  15. 互联网思维心得体会1500字_互联网思维学习心得体会
  16. 不同iPhone屏幕尺寸
  17. 前后端鉴权方案,一文打尽!
  18. HDU 2015 偶数求和
  19. MySQL-视图-触发器-事务-存储过程-函数-流程控制-索引与慢查询优化-06
  20. [转载]軟件測試方法

热门文章

  1. Gridview隐藏列和隐藏列的取值问题
  2. zookeeper启动失败
  3. 诗与远方:无题(八十)- 吸烟而作
  4. SpringMVC自学日志07(整合Mybatic)
  5. Git 日常开发常用命令
  6. Docker保存修改后的镜像
  7. EasyUI Numberbox 数字框(限制仅输入数字)
  8. python父亲节礼物_父亲节程序员硬核示爱:你能看懂几条
  9. JavaScript(一)——变量,数据类型及转换、运算符和逻辑结构
  10. python办公自动化博客_最全总结 | 聊聊 Python 办公自动化之 Word(下)