一、ajax跨域调用restful webservice
1)jsonp的方式。略
2)配置拦截器,设置允许那些origin可以发起跨域请求,具体代码:
public class TestInterceptor extends AbstractPhaseInterceptor<Message> {
public TestInterceptor() {
super(Phase.RECEIVE);
}
public TestInterceptor(String phase) {
super(phase);
}
@Override
public void handleMessage(Message message) throws Fault {
if (message.getDestination() != null) {
System.out.println(message.getId() + "#" + message.getDestination().getMessageObserver());
}
if (message.getExchange() != null) {
System.out.println(message.getExchange().getInMessage() + "#" + message.getExchange().getInFaultMessage());
System.out.println(message.getExchange().getOutMessage() + "#" + message.getExchange().getOutFaultMessage());
}
HttpServletRequest request = (HttpServletRequest) message.get(
AbstractHTTPDestination.HTTP_REQUEST);//这句可以获取到request
HttpServletResponse response = (HttpServletResponse) message.get(
AbstractHTTPDestination.HTTP_RESPONSE);//这句可以获取到request
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
}
}
- Access-Control-Allow-Origin 为允许哪些Origin发起跨域请求. 这里设置为"*"表示允许所有。
- Access-Control-Allow-Methods 为允许请求的方法.
- Access-Control-Max-Age 表明在多少秒内,不需要再发送预检验请求,可以缓存该结果
- Access-Control-Allow-Headers 表明它允许跨域请求包含content-type头,这里设置的x-requested-with ,表示ajax请求
然后在把这个拦截器加入到配置文件里面
<bean id="testServiceInterceptor" class="com.fpi.prd.test.util.TestInterceptor" />
<bean id="service" class="com.fpi.prd.test.service.Impl.UserRestFulServiceImpl" />
<jaxrs:server id="testServiceContainer" address="/test">
<jaxrs:serviceBeans>
<ref bean="service" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
</jaxrs:providers>
<jaxrs:inInterceptors>
<ref bean="testServiceInterceptor" />
</jaxrs:inInterceptors>
<jaxrs:extensionMappings>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</jaxrs:extensionMappings>
<jaxrs:languageMappings>
<entry key="en" value="en-gb"/>
</jaxrs:languageMappings>
</jaxrs:server>
二、请求webservice时候,返回的数据出现中文乱码问题,我们同样可以在拦截器里面配置
response.setCharacterEncoding("UTF-8");
转载自:https://blog.csdn.net/qll3609120/article/details/84740510