原理:http://madong.net.cn/index.php/2012/12/368/

调用端:

$.getJSON("http://192.168.220.85:8001/esb/autocredit/test?callback=?",function(data){
alert(data);
});

服务端:(基于spring mvc  @RestController 或 @ResponseBody注解)

更改源码:ServletInvocableHandlerMethod.java

主要添加:

---------------------------------------------

String parameter = webRequest.getParameter("callback");
if (parameter != null) {
returnValue = parameter + "(" + returnValue.toString() + ")";
}

---------------------------------------------

/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.web.servlet.mvc.method.annotation;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

import org.springframework.http.HttpStatus;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite;
import org.springframework.web.method.support.InvocableHandlerMethod;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.View;
import org.springframework.web.util.NestedServletException;

/**
* Extends {@link InvocableHandlerMethod} with the ability to handle return
* values through a registered {@link HandlerMethodReturnValueHandler} and also
* supports setting the response status based on a method-level
* {@code @ResponseStatus} annotation.
*
* <p>
* A {@code null} return value (including void) may be interpreted as the end of
* request processing in combination with a {@code @ResponseStatus} annotation,
* a not-modified check condition (see
* {@link ServletWebRequest#checkNotModified(long)}), or a method argument that
* provides access to the response stream.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public class ServletInvocableHandlerMethod extends InvocableHandlerMethod {

private HttpStatus responseStatus;

private String responseReason;

private HandlerMethodReturnValueHandlerComposite returnValueHandlers;

/**
* Creates an instance from the given handler and method.
*/
public ServletInvocableHandlerMethod(Object handler, Method method) {
super(handler, method);
initResponseStatus();
}

/**
* Create an instance from a {@code HandlerMethod}.
*/
public ServletInvocableHandlerMethod(HandlerMethod handlerMethod) {
super(handlerMethod);
initResponseStatus();
}

private void initResponseStatus() {
ResponseStatus annot = getMethodAnnotation(ResponseStatus.class);
if (annot != null) {
this.responseStatus = annot.value();
this.responseReason = annot.reason();
}
}

/**
* Register {@link HandlerMethodReturnValueHandler} instances to use to
* handle return values.
*/
public void setHandlerMethodReturnValueHandlers(HandlerMethodReturnValueHandlerComposite returnValueHandlers) {
this.returnValueHandlers = returnValueHandlers;
}

/**
* Invokes the method and handles the return value through a registered
* {@link HandlerMethodReturnValueHandler}.
*
* @param webRequest
* the current request
* @param mavContainer
* the ModelAndViewContainer for this request
* @param providedArgs
* "given" arguments matched by type, not resolved
*/
public final void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {

Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);

// 为实现跨域请求 添加实现 add by x
String parameter = webRequest.getParameter("callback");
if (parameter != null) {
returnValue = parameter + "(" + returnValue.toString() + ")";
}
// 为实现跨域请求 添加实现 add by x

setResponseStatus(webRequest);

if (returnValue == null) {
if (isRequestNotModified(webRequest) || hasResponseStatus() || mavContainer.isRequestHandled()) {
mavContainer.setRequestHandled(true);
return;
}
} else if (StringUtils.hasText(this.responseReason)) {
mavContainer.setRequestHandled(true);
return;
}

mavContainer.setRequestHandled(false);

try {
this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
} catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex);
}
throw ex;
}
}

/**
* Set the response status according to the {@link ResponseStatus}
* annotation.
*/
private void setResponseStatus(ServletWebRequest webRequest) throws IOException {
if (this.responseStatus == null) {
return;
}

if (StringUtils.hasText(this.responseReason)) {
webRequest.getResponse().sendError(this.responseStatus.value(), this.responseReason);
} else {
webRequest.getResponse().setStatus(this.responseStatus.value());
}

// to be picked up by the RedirectView
webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, this.responseStatus);
}

/**
* Does the given request qualify as "not modified"?
*
* @see ServletWebRequest#checkNotModified(long)
* @see ServletWebRequest#checkNotModified(String)
*/
private boolean isRequestNotModified(ServletWebRequest webRequest) {
return webRequest.isNotModified();
}

/**
* Does this method have the response status instruction?
*/
private boolean hasResponseStatus() {
return responseStatus != null;
}

private String getReturnValueHandlingErrorMessage(String message, Object returnValue) {
StringBuilder sb = new StringBuilder(message);
if (returnValue != null) {
sb.append(" [type=" + returnValue.getClass().getName() + "] ");
}
sb.append("[value=" + returnValue + "]");
return getDetailedErrorMessage(sb.toString());
}

/**
* Create a ServletInvocableHandlerMethod that will return the given value
* from an async operation instead of invoking the controller method again.
* The async result value is then either processed as if the controller
* method returned it or an exception is raised if the async result value
* itself is an Exception.
*/
ServletInvocableHandlerMethod wrapConcurrentResult(final Object result) {

return new CallableHandlerMethod(new Callable<Object>() {

@Override
public Object call() throws Exception {
if (result instanceof Exception) {
throw (Exception) result;
} else if (result instanceof Throwable) {
throw new NestedServletException("Async processing failed", (Throwable) result);
}
return result;
}
});
}

/**
* A sub-class of {@link HandlerMethod} that invokes the given
* {@link Callable} instead of the target controller method. This is useful
* for resuming processing with the result of an async operation. The goal
* is to process the value returned from the Callable as if it was returned
* by the target controller method, i.e. taking into consideration both
* method and type-level controller annotations (e.g. {@code @ResponseBody},
* {@code @ResponseStatus}, etc).
*/
private class CallableHandlerMethod extends ServletInvocableHandlerMethod {

public CallableHandlerMethod(Callable<?> callable) {
super(callable, ClassUtils.getMethod(callable.getClass(), "call"));
this.setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
}

/**
* Bridge to type-level annotations of the target controller method.
*/
@Override
public Class<?> getBeanType() {
return ServletInvocableHandlerMethod.this.getBeanType();
}

/**
* Bridge to method-level annotations of the target controller method.
*/
@Override
public <A extends Annotation> A getMethodAnnotation(Class<A> annotationType) {
return ServletInvocableHandlerMethod.this.getMethodAnnotation(annotationType);
}
}

}

实现跨域请求jsonp方式的更多相关文章

  1. 浏览器同源策略,跨域请求jsonp

    浏览器的同源策略 浏览器安全的基石是"同源政策"(same-origin policy) 含义: 1995年,同源政策由 Netscape 公司引入浏览器.目前,所有浏览器都实行这 ...

  2. AJAX 跨域请求 - JSONP获取JSON数据

    Asynchronous JavaScript and XML (Ajax ) 是驱动新一代 Web 站点(流行术语为 Web 2.0 站点)的关键技术.Ajax 允许在不干扰 Web 应用程序的显示 ...

  3. jquery跨域请求jsonp

    服务端PHP代码  header('Content-Type:application/json; charset=utf-8'); $arr = array('a'=>1, 'b'=>2, ...

  4. 跨域请求 & jsonp

    0 什么是跨域请求 在一个域名下请求另外一个域名下的资源,就是跨域请求.example 1:比如:我当前的域名是http://che.pingan.com.我现在要去请求http://www.cnbl ...

  5. 关于laravel框架的跨域请求/jsonp请求的理解

    最近刚接触laravel框架,首先要写一个跨域的单点登录.被跨域的问题卡了两三天,主要是因为对跨域这快不了解,就在刚才有点茅塞顿开的感觉,我做一下大概整理,主要给一些刚接触摸不着头脑的看,哪里写得不对 ...

  6. 【转】AJAX 跨域请求 - JSONP获取JSON数据

    来源:http://justcoding.iteye.com/blog/1366102/ Asynchronous JavaScript and XML (Ajax ) 是驱动新一代 Web 站点(流 ...

  7. ajax跨域请求のJSONP

    简单说了一下,JSON是一种基于文本的数据交换方式,或者叫做数据描述格式. JSON的优点: 1.基于纯文本,跨平台传递极其简单: 2.Javascript原生支持,后台语言几乎全部支持: 3.轻量级 ...

  8. Ajax的跨域请求——JSONP的使用

    一.什么叫跨域 域当然是别的服务器 (说白点就是去别服务器上取东西) 只要协议.域名.端口有任何一个不同,都被当作是不同的域. 总而言之,同源策略规定,浏览器的ajax只能访问跟它的HTML页面同源( ...

  9. 循序渐进Python3(十一) --6--  Ajax 实现跨域请求 jsonp 和 cors

    Ajax操作如何实现跨域请求?       Ajax (XMLHttpRequest)请求受到同源策略的限制.       Ajax通过XMLHttpRequest能够与远程的服务器进行信息交互,另外 ...

随机推荐

  1. 初探Stage3D(三) 深入研究透视投影矩阵

    关于本文 本文主要讲解从数学的角度如何推导出Stage3D中用到的两个投影矩阵 perspectiveLH public function perspectiveLH(width:Number,hei ...

  2. 解决HP打印机错误:Couldn't open fifo

    我的是因为选错了打印机协议,一开始选成了“互联网打印协议 - IPP”. 解决方案:删除原有打印机配置,重新选择协议为“HP Jetdirect-Socket”即可.

  3. Apache2.4中开通HTTP基本认证

    Apache2.4中开通HTTP基本认证,需要在Apache的配置文件中增加如下代码 WSGIPassAuthorization On 否则则无法认证

  4. node.js中log4js的使用

    以前用过forever进程守护的日志记录到指定文件,但是只能保存到一个文件中不能分片,这样到只日志文件越来越大, forever start -s -l ./forever.log app.js -l ...

  5. LocalBroadcastManager 使用小解

    最近在开发平板项目,完全是fragmentactivity+fragment的结构.看起来似乎简单,但是和以前不同的是,业务逻辑非常复杂,多处的非常规跳转,fragment之间的数据交换,一处更新多处 ...

  6. 小兔伴伴家庭动物园AR智能早教产品上市

    2016年6月,经过乐卓大家庭所有人的共同努力,公司旗下首款新品——小兔伴伴之<家庭动物园>3D智能学习卡正式面世. 每个孩子都应该在合适的时间去体验丰富的声音.色彩和动作,<家庭动 ...

  7. IOS实现中间凸起圆形TabBar

    中间凸起的圆形TabBar曾经比较流行,类似于闲鱼之类的APP就使用了中间凸起TabBar,这两天自己动手实现了一个,效果图如下: 大致原理:重写UITabBar和UITabBarController ...

  8. C 语言函数参数只能传指针,不能传数组

    今天被要求编写一个C/C++冒泡算法的程序,心想这还不是手到擒来的事儿,虽然最近都是用Javascript程序,很少写C/C++程序,但是好歹也用过那么多年的C语言: 首先想的是怎么让自己的代码看上去 ...

  9. 十二、EnterpriseFrameWork框架核心类库之与EntLib结合

    从本章开始对框架的讲叙开始进入核心类库的讲解,前面都是对框架外在功能讲解,让人有个整体的概念,知道包含哪些功能与对系统开发有什么帮助.以后多章都是讲解核心类库的,讲解的方式基本按照代码的目录结构,这样 ...

  10. Unit Of Work--工作单元(二)

    回顾 上一篇我们根据工作单元的原理基于ADO.NET进行了简单的实现,但是当项目需求发生变化的时候,比如需要引入ORM框架又要兼容当前ADO.NET实现的方式时,先前的实现就无法满足这个需求了. 话就 ...