【转载】ajax向SpringMVC Controller传参,并且Controller返回map的方法。
转自:https://blog.****.net/qq_34273888/article/details/81624998
ajax向SpringMVC Controller传参,并且Controller返回map的方法
最近写项目的时候用到了SpringMVC框架,在页面中ajax和Controller互相传值的过程中,遇到了很多问题,在此记录一下。
前端jsp。
后台Controller
运行结果
最近写项目的时候用到了SpringMVC框架,在页面中ajax和Controller互相传值的过程中,遇到了很多问题,在此记录一下。
前端jsp。
注意:我这种方法不管是ajax向Contorller传值,还是Controller像ajax传值,传递的实际上都是json对象,而非json字符串,所以变量名不用加双引号
代码:
function uploadElectricFenceInfo() {
var electricFenceName = $("#fence_name_input").val();
var centerLon = $("#center_lon_input").val();
var centerLat = $("#center_lat_input").val();
var radius = $("#radius_input").val();
var userName = "小明";
var paramList={
ElectronicFenceName:electricFenceName,
centerLong:centerLon,
centerLat:centerLat,
radius:radius,
username:userName
};
//alert(electricFenceName+"\n"+centerLon+"\n"+centerLat+"\n"+userName);
jQuery.ajax({
async:true,//异步加载
timeout:1000,
data:paramList,
type:"POST",
//contentType:"application/json",这句不能加,加了后台会接收不到值。
url:"/addElectricFence",
dataType:'json',
success:function (data) {
alert("success"+" "+data.resultString+"\n"
+"radius"+" "+data.radius+"\n"+
"username"+" "+data.username);
},
error:function (data) {
alert("data:" +data);
}
});
}
//确认按钮的点击时间,判断输入是否为空
$(document).ready(function(){
$("#info_ensure").click(function () {
if ($("#radius_input").val()==""||$("#center_lon_input").val()==""||
$("#center_lat_input").val()==""){
alert("请先绘制围栏");
}else if($("#fence_name_input").val()==""){
alert("请设置围栏名");
}
else {
uploadElectricFenceInfo();
}
});
});
可以看到,我这里的paramList里面是直接变量名加变量值的,没有双引号;
contentType:"application/json"这句一定不能加,加了之后,后台就无法接收到值;
得到Controller传回的map后,将其中的变量在弹出框中显示;
后台Controller
要想在Controller中返回map,需要jackson-core、ackson-databind和jackson-annotations这3个jar包,版本最好新一点。
还需要在Spring里面配置一个bean
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
p:ignoreDefaultModelOnRedirect="true">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
做完这些后,就可以写Controller的代码了
@RequestMapping(value = "/addElectricFence",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> addElectricFence(HttpServletRequest request){
String resultString; //记录成功或失败的字符串
System.out.println("围栏名:"+request.getParameter("ElectronicFenceName"));
System.out.println("圆心经度:"+request.getParameter("centerLong"));
System.out.println("圆心纬度:"+request.getParameter("centerLat"));
System.out.println("半径:"+request.getParameter("radius"));
System.out.println("用户名:"+request.getParameter("username"));
//调用zookeeper的服务
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("xml/spring/zookeeper.xml");
ICar icar = (ICar)context.getBean("carImpl");
Boolean resultBoolean = icar.addElectronicFence(
request.getParameter("ElectronicFenceName"),//围栏名
Double.parseDouble(request.getParameter("centerLong")),//圆心经度
Double.parseDouble(request.getParameter("centerLat")),//圆心纬度
Double.parseDouble(request.getParameter("radius")),//半径
request.getParameter("username")//用户名
);
if(resultBoolean){
resultString = "success";
}else {
resultString = "failed";
}
Map<String,Object> map = new HashMap<String, Object>();
map.put("radius",request.getParameter("radius"));
map.put("resultString",resultString);
map.put("username",request.getParameter("username"));
return map;
}
}
@ResponeseBody注解一定要写,否则不能返回map
运行结果
ajax中设置contentType: “application/json”的作用
添加 contentType:“application/json“之后,向后台发送数据的格式必须为json字符串
$.ajax({ type: "post", url: "mobile/notice/addMessageInfo.jspx", contentType: "application/json", data:"{'name':'zhangsan','age':'15'}", dataType: "json", success: function(data) { console.log(data); }, error: function(msg) { console.log(msg) } })
不添加 contentType:“application/json“的时候可以向后台发送json对象形式
$.ajax({ type: "post", url: "mobile/notice/addMessageInfo.jspx", data:{name:'zhangsan',age:'15'}, dataType: "json", success: function(data) { console.log(data); }, error: function(msg) { console.log(msg) } })
另外,当向后台传递复杂json的时候,同样需要添加 contentType:“application/json“,然后将数据转化为字符串
var data = { uploadarray: uploadarray, messageInfo: { messageTitle: messageTitle, messageContent: messageContent, publisher: publisher }, userId: userId } $.ajax({ type: 'post', url: "mobile/notice/addMessageInfo.jspx", contentType: 'application/json', data: JSON.stringify(data), dataType: "json", success: function(data) { console.log(data); }, error: function(msg) { console.log(msg) } })