温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在springmvc中使用controller如何实现返回值

发布时间:2020-11-18 16:30:28 来源:亿速云 阅读:157 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关在springmvc中使用controller如何实现返回值,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

使用@RequestBody 

比如代码如下:

@RequestMapping(value="/ceshijson",produces="application/json;charset=UTF-8")
@ResponseBody
public String ceshijson(@RequestBody String channelId) throws IOException{

 return channelId;

如果代码为上面这种情况时,前台发送json时,应该这样写(写法有很多,能用就行)

function channel(){
   //先获取选中的值
   var channelId = $("#channelId option:selected").val();
   //来判断发送的链接
   if(channelId ==2){


   $.ajax({
     url:"ceshijson",
     type:"post",
     dataType:'json',
     contentType:'application/json;charset=utf-8',
     data:JSON.stringify({'channelId':channelId}),
     success:function(data){
      alert(data.channelId);
     },
     error:function(XMLHttpRequest, textStatus, errorThrown){ 
     alert("Error") 
     alert(XMLHttpRequest.status); 
     alert(XMLHttpRequest.readyState); 
     alert(textStatus); 
     }
   });
   }
  }

这里需要特别注意:上篇也强调过,使用了@RequestBody时,它要求String channelId接收到数据为json字符串。也就是要是data写成这样: data:{‘channelId':channelId},就是错误的。因为这是json对象形式。

要是你不想使用JSON.stringify()这个函数,那就自己手动字符串拼接:

data:'{"channelId":'+channelId+'}'

这里还要注意channelId是双引号,不能写成单引号,因为这是json语法规则。你改成单引号,也就是

**错误写法

data:"{'channelId':"+channelId+"}"

这种形式,虽然可以传给后台,但是后台传回来的会出现undefined。也就是key必须要用双引号包围。

不使用@RequestBody

 @RequestMapping(value="/ceshijson",produces="application/json;charset=UTF-8")
 @ResponseBody
 public String ceshijson(String channelId) throws IOException{
  Map<String,Object> map = new HashMap<String,Object>();
   map.put("channelId", channelId);
   ObjectMapper mapper = new ObjectMapper();
   channelId = mapper.writeValueAsString(map);
  return channelId;
 }

前台代码

$.ajax({
   url:"ceshijson",
   type:"post",
   dataType:'json',
   //contentType:'application/json;charset=utf-8',
   data:"channelId="+channelId,
   success:function(data){
    alert(data);
   },
   error:function(XMLHttpRequest, textStatus, errorThrown){ 
     alert("Error") 
     alert(XMLHttpRequest.status); 
     alert(XMLHttpRequest.readyState); 
     alert(textStatus); 
    }
});

这种方式利用ObjectMapper中的writeValueAsString将Java对象转换为json字符串。

关于在springmvc中使用controller如何实现返回值就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI