之前总结过 Spring Boot 前端页面传 Json 数据至 Controller 的例子。《spring-boot 中,json 数据传值方式》
在很多场合下,有可能并不需要是按照 Json 数据传递值的。而是以 application/x-www-form-urlencoded 格式,或者 url 中拼接查询字符串的方式传递数据。
Spring Boot 处理这种传值,通过@RequestParam 注解实现,如果传入参数命名和函数参数命名一致的情况下,@RequestParam 还可以省略。
前端代码
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);
});
});
Controller代码
@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;
}
代码解释:
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3r5wbsmwwuasc