GVKun编程网logo

如何通过Spring MVC和多种响应类型支持JSONP(spring mvc响应的两种方式)

35

如果您对如何通过SpringMVC和多种响应类型支持JSONP感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于如何通过SpringMVC和多种响应类型支持JSONP的详细内容

如果您对如何通过Spring MVC和多种响应类型支持JSONP感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于如何通过Spring MVC和多种响应类型支持JSONP的详细内容,我们还将为您解答spring mvc响应的两种方式的相关问题,并且为您提供关于JSON – Spring MVC:如何将json数据发布到spring MVC控制器、Jsonp+spring mvc、JSON加Spring MVC 3.2错误415(不支持的媒体类型)、Mvc4 WebApi 支持jsonp的有价值信息。

本文目录一览:

如何通过Spring MVC和多种响应类型支持JSONP(spring mvc响应的两种方式)

如何通过Spring MVC和多种响应类型支持JSONP(spring mvc响应的两种方式)

我在控制器中有一个方法,该方法将根据要求返回HTML或JSON。这是这种方法的精简示例,以我在此问题中发现的有关如何执行此操作的信息为模型:

@RequestMapping(value="callback")public ModelAndView callback(@RequestParam("c") String c) {    Map response = new HashMap<String, String>();    response.put("foo", "bar");    return new ModelAndView("fake", "data", new JSONPObject(c, response));}

我将JSONPObject放入模型中是因为必须这样做,以便能够从请求HTML时呈现的视图中获取它。但是,当我使用回调渲染JSON时,这会带来问题:

curl ''http://localhost:8080/notes/callback.json?c=call''{"data"call(:{"foo":"bar"})}

如您所见,因为我将数据放入模型的“数据”插槽中,所以当将模型呈现为JSON时,会有多余的包装。我正在寻找的是呈现的JSON(技术上为JSONP),如下所示:

call({"data":{"foo":"bar"}})

谁能看到一种方法来到达我要去的地方,而不会破坏返回在渲染过程中访问JSONPObject的视图的功能?

答案1

小编典典

我想通了。呈现JSON时,Spring根据我的配置使用MappingJacksonJsonView。该视图具有告诉其在地图中找到单个项目并在渲染之前将其提取的属性。设置该属性后,现在可以使用了。

    <property name="defaultViews">        <list>            <bean>                <property name="extractValueFromSingleKeyModel" value="true" />            </bean>        </list>    </property>

JSON – Spring MVC:如何将json数据发布到spring MVC控制器

JSON – Spring MVC:如何将json数据发布到spring MVC控制器

我在将jsp数据从jsp发布到控制器时遇到问题.我每次尝试都会收到ajax错误错误请求.我是JSON的新手,我真的不知道我做错了什么.我搜索并尝试了一些我可以在这个网站找到的样本,但我仍然有问题.

在我的控制器中:

@RequestMapping (method = RequestMethod.POST,headers ={"Accept=application/json"},value = "/form")
public String postJournalEntry (@RequestParam ("json") String json,Model model) {
    System.out.println(json);
    return "successfullySaved";
}

在我的jsp中:

$("#btnPostGlEntry").click(function () {
    var glEntries = '{"glEntries":[{"generalLedgerId":"1"},{"accountId":"4"},{"amount":"344.44"},{"description":"Test Entry"},{"debit":"Yes"}]}';
    $.ajax({
        type: "POST",contentType: "application/json",dataType: "json",url: contextpath + "/generalLedger/journalEntries/form",data : JSON.stringify(glEntries),success: function(data) {
            alert("Success!!!");
        },error: function (jqXHR,textStatus,errorThrown) {
            alert(jqXHR + " : " + textStatus + " : " + errorThrown);
        }
    });
});

注意:我甚至不确定我的控制器中的功能是否正确.我认为我的控制器和我的ajax是错误的.请帮忙.

最佳答案
如果你想将你的JSON反序列化到某个类中,那么你必须定义这样的方法(并且不要忘记添加jsonConverter,如前面的答案):

.... method(@RequestBody MyClass data){ ... }

但是,如果您希望您的方法接受JSON作为String而不是这样做:

.... method(@RequestBody String json){ ... }

所以,基本上,如果你发布JSON,这意味着JSON不是一个参数,它是请求的主体.最后你必须使用@RequestBody注释,而不是@RequestParam.

你可以在这里找到Spring Mvc和JSON的精彩视频教程:sites.google.com/site/upida4j/example

Jsonp+spring mvc

Jsonp+spring mvc

1.@ControllerAdvice public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice { public JsonpAdvice() { super("callback"); } }

  1. jackson 相关包 三个

3.http://xxxx.xxx.xxx?callback=callback

JSON加Spring MVC 3.2错误415(不支持的媒体类型)

JSON加Spring MVC 3.2错误415(不支持的媒体类型)

我做错什么了?我尝试使用Spring
mvc和JSON。当我尝试调试我的代码时,我正在寻找javascript有效但不能正常工作的控制器。在浏览器中,我收到错误415不支持的媒体类型。

脚本:

$(document).ready(function() {
  $('#newSmartphoneForm').submit(function(event) {

      var producer = $('#producer').val();
      var model = $('#model').val();
      var price = $('#price').val();
      var json = { "producer" : producer,"model" : model,"price": price};

    $.ajax({
        url: $("#newSmartphoneForm").attr( "action"),data: JSON.stringify(json),type: "POST",beforeSend: function(xhr) {
            xhr.setRequestHeader("Accept","application/json");
            xhr.setRequestHeader("Content-Type","application/json");
        },success: function(smartphone) {
            var respContent = "";

            respContent += "<span>Smartphone was    created: [";
            respContent += smartphone.producer + " : ";
            respContent += smartphone.model + " : " ;
            respContent += smartphone.price + "]</span>";

            $("#sPhoneFromResponse").html(respContent);         
        }
    });

    event.preventDefault();
  });

});

控制器:

   @RequestMapping(value="/create",method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
    return smartphoneService.create(smartphone);
}

Mvc4 WebApi 支持jsonp

Mvc4 WebApi 支持jsonp



JsonpMediaTypeFormatter.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http.Formatting;
using System.IO;

using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net;

namespace BitAuto.PeopleLib.Api.Formatters
{
    public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
    {
        private string callbackQueryParameter;

        public JsonpMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(DefaultMediaType);
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

            MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp",DefaultMediaType));
        }

        public string CallbackQueryParameter
        {
            get { return callbackQueryParameter ?? "callback"; }
            set { callbackQueryParameter = value; }
        }

        public override Task WritetoStreamAsync(Type type,object value,Stream stream,HttpContent content,TransportContext transportContext)
        {
            string callback;

            if (IsJsonpRequest(out callback))
            {
                return Task.Factory.StartNew(()=>{
                    var writer = new StreamWriter(stream);
                    writer.Write(callback + "(");
                    writer.Flush();
                    base.WritetoStreamAsync(type,value,stream,content,transportContext).Wait();
                    writer.Write(")");
                    writer.Flush();
                });
            }
            else
            {
                return base.WritetoStreamAsync(type,transportContext);
            }
        }


        private bool IsJsonpRequest(out string callback)
        {
            callback = null;

            if (HttpContext.Current.Request.HttpMethod != "GET")
                return false;

            callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];

            return !string.IsNullOrEmpty(callback);
        }
    }
}



Global.asax

var config = GlobalConfiguration.Configuration;
config.Formatters.Insert(0,new JsonpMediaTypeFormatter());

前台访问

  function getAll() {
        $.ajax({
            url: "http://localhost:37980/api/people/List",type: 'GET',dataType: "jsonp",success: function (data) {
                var s = "";
                $.each(data,function (i,val) {
                    s += val.Name;
                });

                $("#modes").html(s);

            }
        }).fail(
             function (xhr,textStatus,err) {
                 alert('Error: ' + err);
             });
    }
 
dataType:用jsonp

今天的关于如何通过Spring MVC和多种响应类型支持JSONPspring mvc响应的两种方式的分享已经结束,谢谢您的关注,如果想了解更多关于JSON – Spring MVC:如何将json数据发布到spring MVC控制器、Jsonp+spring mvc、JSON加Spring MVC 3.2错误415(不支持的媒体类型)、Mvc4 WebApi 支持jsonp的相关知识,请在本站进行查询。

本文标签: