经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
spring mvc 参数绑定
来源:cnblogs  作者:jdkman  时间:2018/11/13 9:48:12  对本文有异议

基础类型

原始类型:id必须要传,否则报错。

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(int id) {}

包装类型:id可以不传,后台接受到null。

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(Integer id) {}

list&set

简单类型

前台

form表单

  1. <form action="${ctx}/test/test" method="post">
  2.     <input type="text" name="ids">
  3.     <input type="text" name="ids">
  4.     <input type="text" name="ids">
  5.     <input type="submit">
  6. </form>

ajax

  1. var data = [];
  2. data.push(1);
  3. data.push(2);
  4. data.push(3);
  5. $.ajax({
  6.     url: ctx + "/test/test",
  7.     traditional:true,//必要
  8.     data: {ids: data},
  9.     success: function (result) {
  10.         alert(result);
  11.     }
  12. })

后台

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(@RequestParam List<Integer>ids) {}

复杂类型

list<User>users:(略)同json格式对象

数组

前台

form表单

  1. <form action="${ctx}/test/test" method="post">
  2.     <input type="text" name="ids">
  3.     <input type="text" name="ids">
  4.     <input type="text" name="ids">
  5.     <input type="submit">
  6. </form>

ajax

  1. var data = [];
  2. data.push(1);
  3. data.push(2);
  4. data.push(3);
  5. $.ajax({
  6.     url: ctx + "/test/test",
  7.     traditional:true,//必要
  8.     data: {ids: data},
  9.     success: function (result) {
  10.         alert(result);
  11.     }
  12. })

后台

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(Integer[]ids) {
  4. }

map

前台

form

  1. <form action="${ctx}/test/test" method="post">
  2.     <input type="text" name="name">
  3.     <input type="text" name="sex">
  4.     <input type="submit">
  5. </form>

ajax

  1. var data = {name:"zhangsan",sex:"man"};
  2. $.ajax({
  3.     url: ctx + "/test/test",
  4.     data:data,
  5.     success: function (result) {
  6.         alert(result);
  7.     }
  8. });

后台

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(@RequestParam Map<String,String> params) {}

pojo简单属性

前台

form

  1. <form action="${ctx}/test/test" method="post">
  2.     <input type="text" name="name">
  3.     <input type="text" name="sex">
  4.     <input type="submit">
  5. </form>

ajax

  1. var data = {name:"zhangsan",sex:"man"};
  2. $.ajax({
  3.     url: ctx + "/test/test",
  4.     data:data,
  5.     success: function (result) {
  6.         alert(result);
  7.     }
  8. });

后台

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(User user) {}
  1. public class User{
  2.     private String name;
  3.     private String sex;
  4.     //get and set ...
  5. }

pojo包含list

前台

form

  1. <form action="${ctx}/test/test" method="post">
  2.     <input type="text" name="userName" value="zhangsan">
  3.     <input type="text" name="sex" value="123">
  4.     <input type="text" name="posts[0].code" value="232"/>
  5.     <input type="text" name="posts[0].name" value="ad"/>
  6.     <input type="text" name="posts[1].code" value="ad"/>
  7.     <input type="text" name="posts[1].name" value="232"/>
  8.     <input type="submit">
  9. </form>

ajax

  1. var user={userName:"zhangsan",password:"123"};
  2. user['posts[0].name']="ada";
  3. user['posts[0].code']="ada";
  4. user['posts[1].name']="ad";
  5. user['posts[1].code']="ad2323a";
  6. $.ajax({
  7.     url: ctx + "/test/test",
  8.     type:"post",
  9.     contentType: "application/x-www-form-urlencoded",
  10.     data:user,
  11.     success: function (result) {
  12.         alert(result);
  13.     }
  14. });

后台

  1. public class User{
  2.     private String name;
  3.     private String sex;
  4.     private List<Post> posts;
  5.     //get and set ...
  6. }
  1. public class Post {
  2.     private String code;
  3.     private String name;
  4.     //get and set ...
  5. }
  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public ResponseData test(User user) {}

date类型

使用注解方式

绑定单个方法

对于传递参数为Date类型,可以在参数前添加@DateTimeFormat注解。如下:

  1. @RequestMapping("/test")
  2. public void test(@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date date){}

如果传递过来的是对象,可以在对象属性上添加注解。

  1. @RequestMapping("/test")
  2. public void test(Person person){}
  3.  
  4. Public class Person{
  5.     @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
  6.     Private Date date;
  7.     Private String name;
  8. }
绑定整个controller的所有方法:
  1. @Controller
  2. public class FormController {
  3.  
  4.     @InitBinder
  5.     public void initBinder(WebDataBinder binder) {
  6.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  7.         dateFormat.setLenient(false);
  8.         binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
  9.     }
  10. }
  1. @Controller
  2. public class FormController {
  3.    @InitBinder
  4.     protected void initBinder(WebDataBinder binder) {
  5.         binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
  6.     }
  7. }

使用PropertyEditor方式

使用ConversionService方式

参考:

https://www.2cto.com/kf/201501/374062.html

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-initbinder

枚举类型

mvc配置文件添加:

  1.  <!--枚举类型转化器-->
  2.     <bean id="formattingConversionService"
  3.           class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  4.         <property name="converters">
  5.             <set>
  6.                 <bean class="org.springframework.core.convert.support.StringToEnumConverterFactory"/>
  7.             </set>
  8.         </property>
  9.     </bean>

参考:

Spring Boot绑定枚举类型参数

Spring MVC 自动为对象注入枚举类型

json格式对象

后台

  1. @RequestMapping(value = "introductionData.do", method = {RequestMethod.POST})
  2. @ResponseBody
  3. public RestResult introductionData(@RequestBody SignData signData) {
  4. }
  1. public class SignData {
  2.     private ApplicationInformation applicationInformation;
  3.     private ApplyUserInformation applyUserInformation;
  4.     private StudentInformation studentInformation;
  5.     private List<VolunteerItem> volunteerItems;
  6.     private ResidencePermit residencePermit;
  7.     private List<Family> families;
  8.     //get and set ...
  9. }

前台

  1. var data = {}
  2. var applyUserInformation = {
  3.     "applyName": APPLYNAME,
  4.     "applyCardType": "0",
  5.     "applyCardID": APPLYIDCARD,
  6.     "applyMobile": APPLYMOBILE
  7. };
  8. var applicationInformation = {
  9.     "live_address": nowaddress,
  10.     "addressJZArea": addressJZArea,
  11.     "schoolLevel": schoolLevel,
  12.     "schoolType": schoolType,
  13.     "applyName": APPLYNAME,
  14.     "contacts": contacts,
  15.     "contactNumber": contactNumber
  16. };
  17. var studentInformation = {
  18.     "cardType": cardType,
  19.     "cardID": cardID,
  20.     "studentName": studentName,
  21.     "studentType": studentType,
  22.     "studentType1": studentSpecialCase,
  23.     "isDisability": "0",
  24.     "studentCategory": "0",
  25.     "birthday":birthday,
  26.     "graduationschool":SchoolName,
  27.     "graduationclass":classNameinfo,
  28.     "applyName": APPLYNAME
  29. };
  30. data["applyUserInformation"] = applyUserInformation;
  31. data["applicationInformation"] = applicationInformation;
  32. data["studentInformation"] = studentInformation;
  33.  
  34. $.ajax({
  35.     url: ctx + '/overseasData.do',
  36.     type: "post",
  37.     data: JSON.stringify(data),
  38.     contentType: "application/json;charset=utf-8",
  39.     success: function (result) {}
  40. })

参考:https://blog.csdn.net/qq_29663071/article/details/68922043

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号