java-解决跨域问题

今天刚在项目中解决了跨域,记录下javascript

首先了解下相关知识html

$.ajax    jQuery的异步请求前端

    

jsonp :指定跨域异步请求时,后台接收参数名称,默认为callback
dataType:请求数据类型 -- 经常使用json,text,html 跨域请求时使用jsonp
jsonpCallback:指定使用jsonp时返回结果会调用哪一个方法来执行

后台相关知识java

contentType :普通json调用时,使用 application/jsonjquery

                      :跨域调用时由于返回结果后jQuery还会调用函数,因此使用 application/javascriptweb

 

大概解决流程ajax

前端:spring

/**
 * Created by on 2017/5/6.
 */
define(['jquery', 'config'], function ($, config, module) {
    //跨域回调
    function jsonpCallback(res) {
        return res;
    }

    return {
        send: function (url, data, successFn, params) {
            var req = {
                url: config.serverUrl + url,
                data: data || {},
                dataType: "json",
                success: function (res) {
                    jsonpCallback(res); //回调函数处理
                    //执行状态判断
                    if (res.respCode == '0000') {
                        successFn(res);
                    } else {
                        alert(res.respDesc);
                    }
                },
                error: function (xhr, status) {
                    //显示错误提示
                    alert("网络错误");
                }
            }

            if (typeof(params) === 'undefined') {
                params = {};
            }

            if (!params.async) {
                req.async = true;
            }
            if (!params.contentType) {
                req.contentType = undefined;
            }
            if (params.isUpload) {
                req.url = config.uploadUrl + url;
            }
            if (!params.method) {
                req.method = 'POST';
            }

            if (params.dataType) {
                req.dataType = params.dataType;
            }

            var options = {
                user_token: config.appContext.user_token
            }

            req.data = $.extend(options, req.data);

            this.doRequest(req);

        },
        doRequest: function (params) {
            $.ajax({
                url: params.url,
                async: params.async,
                data: params.data,
                timeout: 10000,
                dataType: params.dataType,
                jsonpCallback: "jsonpCallback", //指定回调函数
                contentType: params.contentType || 'application/x-www-form-urlencoded',
                success: params.success || null,
                error: params.error || null
            });
        }
    }
});

后台处理代码json

package org.roundchat.client.common.pipeline;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.home.common.model.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.alibaba.citrus.service.pipeline.PipelineContext;
import com.alibaba.citrus.service.pipeline.Valve;
import com.alibaba.citrus.util.StringEscapeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;


public class JsonpCallBackPipeline implements Valve{

	private static final String DEFAULT_CONTENT_TYPE = "application/json";
	private static final String DEFAULT_JAVASCRIPT_CONTENT_TYPE = "application/javascript";
	
	private String contentType;
	private String callbackContentType;
	
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
	
	public void invoke(PipelineContext pipelineContext) throws Exception {
		ResponseData respData = (ResponseData) pipelineContext.getAttribute("result");
		
		PrintWriter out = response.getWriter();
		response.setContentType(DEFAULT_CONTENT_TYPE);
		String callback = request.getParameter("callback");
		callback = StringEscapeUtil.escapeHtml(callback);
		
		if(!StringUtils.isEmpty(callback)) {
			response.setContentType(DEFAULT_JAVASCRIPT_CONTENT_TYPE);
			out.print(callback + "(" + backContent + ");");
		} else {
			out.print(backContent);
		}
	}

	public String getContentType() {
		return contentType == null ? DEFAULT_CONTENT_TYPE : contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getCallbackContentType() {
		return callbackContentType == null ? DEFAULT_JAVASCRIPT_CONTENT_TYPE : callbackContentType ;
	}

	public void setCallbackContentType(String callbackContentType) {
		this.callbackContentType = callbackContentType;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}


}

 

后台使用的是webx 其余框架同理。跨域

相关文章
相关标签/搜索