Spring Boot 中,表单数据传值方式
2,542 total views, 3 views today
之前总结过 Spring Boot 前端页面传 Json 数据至 Controller 的例子。《spring-boot 中,json 数据传值方式》
在很多场合下,有可能并不需要是按照 Json 数据传递值的。而是以 application/x-www-form-urlencoded 格式,或者 url 中拼接查询字符串的方式传递数据。
Spring Boot 处理这种传值,通过@RequestParam 注解实现,如果传入参数命名和函数参数命名一致的情况下,@RequestParam 还可以省略。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
jQuery(function ($) { $('#btnSave').on('click', function () { var report = {}; report.username = $.trim($('#txt-username').val()); report.content =$('#txt-content').val(); var option = { url: 'report/save', type: 'POST', dataType: 'json', contentType: 'application/x-www-form-urlencoded',//默认就是这种格式 data: report //默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处 //理转化成一个查询字符串, //以配合默认内容类型 "application/x-www-form-urlencoded"。 }; $.ajax(option); }); }); |
1 2 3 4 5 6 |
@RequestMapping("/report/save") @ResponseBody public Map<String, String> saveReport( @RequestParam(value="username") String username, @RequestParam(value="content") String content) { Map<String, String> map = new HashMap<>(); return map; } |
代码解释:
- jquery 代码中,contentType,表示传递给服务器的数据类型,默认是’application/x-www-form-urlencoded’。data,赋值为 report,但是默认会被转变成 key1=value1&key2=value2 的这样的字符串。此处也可以直接赋值字符串,例如 data:’username=zhangsan&content=abcde’。
- controller 代码中,@RequestParam 可以省略,因为传递的参数 username,和方法中的参数名是一致的。
- 如果参数是通过查询字符串传递,Controller 也是可以用这种方式。这种方式的优点是,参数清晰,可直接猜测到每个参数的意义。
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3r5wbsmwwuasc
原创文章,转载请注明出处!http://www.javathings.top/spring-boot中,表单数据传值方式/