English 中文(简体)
与JSONP有关的问题
原标题:Issue with JSONP
最佳回答

我发现许多人混淆了JSONP和JSON。 因此,我同意我的看法是正确的:

Java

@RequestMapping(method = RequestMethod.GET, value = "ad")
public void getAd(HttpServletRequest request, HttpServletResponse response){
   ServletOutputStream out;
   try {
      out = response.getOutputStream();
      response.setContentType("text/javascript; charset=utf-8");
      out.println(request.getParameter("callback")+" ( { html :  <strong>Hello World!</strong>  } )");
      out.close();
   } catch (IOException e) {
      e.printStackTrace();
   }
}

Java

var jsonp_url = "http://localhost:8080/AppName/ad?callback=?";
$.getJSON(jsonp_url, function(data) {
   $( #example-widget-container ).html(data.html);
});
问题回答

页: 1 除适当的JSON fomat和打电话({ html:hello world })外 不是json格式

proper json format is { html : hello world }

难道你不想打上<代码>return“{html: hello world }”;?

如果你回来,就不收听。 引言

$.get("http://localhost:8080/test/ad", function(data) {
   alert(data.html);
},  jsonp );

所谓的功能是什么? 如果你回到“召唤”(i html : hello world });那么,在你的 j中,警示不会提醒“Hellow world”。 你们需要具备数据,即管理电话功能

This is actually quite easy using Spring 3.0 and above. In looking at the examples above however I am confused as to why you are treating the spring controller like a plain servlet and printing directly to the response stream. This should be avoided. You would be much better off using just returning a POJO representing your JSON array and let a JSON parser create the response.

The first task is to get Spring to return JSON. This is easily handled by adding @ResponseBody to your controller, telling the controller to serialize the POJO to the client. If you have Jackson in your classpath this will automatically be sent as JSON using the MappingJacksonHttpMessageConverter which is enabled with mvc:annotation-driven.

But JSON isn t enough. You want JSON-P, assuming that the client wants to use the JSON in a cross domain scenario. This can be accomplished in a number of different ways. You could implement a servlet filter using Spring s DelegatingFilterProxy. The filter can determine if JSON-P is being requested and you can tune the response accordingly.

So for my uses I prefer to extend the Spring 3.0 (+) MappingJacksonJsonView instead of a filter and check if the request param contained a key of "callback". If I want JSON or JSONP I can simply add a second servlet mapping to *.jsonp and send either JSON or JSONP based on the presence of the callback parameter.

该守则是:

在你的控制人员中规定如下:

@RequestMapping(value="/ad", method=RequestMethod.GET)
public ModelMap getAvailabilityModel(@RequestParam(required = false) String callback) {
    ModelMap modelMap = new ModelMap();
    modelMap.addAttribute("html", "<strong>Hello World!</strong>");
    return modelMap;
}   

回归模式 地图或甚至《安第斯山季刊》使我能够根据“保护状”地图做不同的事情。

这里的习俗是,要处理初等人物的延伸(只是为了简便而排除某些压倒性):

public class MappingJacksonJsonpView extends MappingJacksonJsonView {

@Override 
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

if("GET".equals(request.getMethod().toUpperCase())) {

    Map<String, String[]> params = request.getParameterMap();

    if(params.containsKey("callback")) {
    String callbackName = params.get("callback")[0];
    response.getOutputStream().write(new String(callbackName + "(").getBytes());
    log.info("GETTER Found for a .jsonp method, callback name is : " + callbackName);
    super.render(model, request, response);
    response.getOutputStream().write(new String(");").getBytes());
    response.setContentType("application/javascript");
    }

    else {
    super.render(model, request, response);
    }
}

else {
    super.render(model, request, response);
}
  }
 }

如果将请求编为*.jsonp,我把“召回”作为我假定的JSON-P的关键参数列入请求参数,我把警示信息放在答复上游。 我将允许Jackson JSON加工商处理在所有情况下将POJO改为适当的JSON的具体细节。 我在我的控制员中,我只是回去了一张POJO或一个模型Map;在答复中,我没有穿过我自己的JSON。 或者,我本可以采用一种模式,对返回类型的看法。 这样就可以妥善处理*.do诉*json的请求。 利用火药,确保你在应急负责人、JSON的申请/json以及JSON-P的申请/javascript中找到适当的媒体。

Here is the output for JSON-P, with a GET on http://localhost:8080/jsonpex/ad.jsonp?callback=xyz (Note the wrapper with the xyz, for JQuery use ?)

xyz({"html":"<strong>Hello World!</strong>"});

If you leave off the Request Parameter it will simply return JSON: http://localhost:8080/jsonpex/ad.jsonp

{"html":"<strong>Hello World!</strong>"}

Finally, make sure you wire up the new view correctly:

<!-- Add our new View to the Application Context -->
<beans:bean  class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <beans:property name="order" value="1" />
    <beans:property name="favorPathExtension" value="true"/>
    <beans:property name="mediaTypes">
        <beans:map>
            <beans:entry key="json" value="application/json"/>
            <beans:entry key="jsonp" value="application/javascript"/>
        </beans:map>
    </beans:property>
    <beans:property name="defaultViews">
        <beans:list>
            <beans:bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
            <beans:bean class="com.yourpackagename.spring.web.servlet.view.jsonp.MappingJacksonJsonpView"/>
        </beans:list>
    </beans:property>
</beans:bean>

两点都指出,我将避免退回所有额外的超文本,并尽可能减少我所能做的事情,把工作的核心放在所交数据之上。 我进行了许多研究,并尝试了许多办法;以上一点对我来说是最好的。 我提出以下备选办法和补充读物,因为它们是导致我最终解决的办法(我可以悲伤地记住这些办法,或者我会给予更多的信贷):

and for a filter solution:

http://jpgmr.wordpress.com/ 201007/28/tutorial-imping-a-servlet-filter-for-jsonp-quest--quest--ert- with-ins-delegatingterproxy/

临 时





相关问题
array dependency injection in spring?

is there a way to use dependency injection to inject all available implementations of a specific interface in spring? This is kind of the same thing as asked here for .NET. Though my aim is to use @...

Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Grails Packaging and Naming Conventions

Packaging Controllers, Services,etc. i.e. - com.company.controllers - com.company.services Is this a good practice or should be avoided by all means?? Another worth mentioning problem I encountered ...

How can I determine Objects in application context?

I am trying to write a portlet for Liferay (using Tomcat and Spring) and need to use a database via Persistence API/Hibernate. I am using some configuration XMLs (applicationContext.xml, etc.) and ...

How to prevent JPA from rolling back transaction?

Methods invoked: 1. Struts Action 2. Service class method (annotated by @Transactional) 3. Xfire webservice call Everything including struts (DelegatingActionProxy) and transactions is configured ...

热门标签