(0)使用注解方式,这个可能有些框架可以,有些不行,在要访问的方法前面加上此注解即可:
@CrossOrigin
(1)使用 Access-Control-Allow-Origin 设置请求响应头,简洁有效。
(后台)被请求的方法,设置请求响应头:
response.setHeader("Access-Control-Allow-Origin","*"); //response 来自 HttpServletResponse
(前端)前端js的ajax中,数据类型使用json,不能使用 “jsonp” //自己一开始就是写成 jsonp,结果半天不起作用
dataType : "json",
【当然最好的方法是写一个过滤器,不要在每个被请求的方法里面都添加这句,如果写过滤器的话,doFilter() 方法中参数 response 类型为 ServletResponse,需要强转成 HttpServletResponse 类型,才可以设置 setHeader() 请求头】
(2)使用 httpClient 做后台中转,避开前端跨域问题。
1、创建 httpClient 工具类(可以直接复制使用,修改一下包名路径即可)
package 自己包名路径;import java.io.IOException;import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSONObject;public class HttpClientUtils {private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录private static RequestConfig requestConfig = null;static {// 设置请求和传输超时时间requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();}/*** post请求传输json参数* * @param url* url地址* @param json* 参数* @return*/public static JSONObject httpPost(String url, JSONObject jsonParam) {// post请求返回结果CloseableHttpClient httpClient = HttpClients.createDefault();JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);// 设置请求和传输超时时间 httpPost.setConfig(requestConfig);try {if (null != jsonParam) {// 解决中文乱码问题StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/json");httpPost.setEntity(entity);}CloseableHttpResponse result = httpClient.execute(httpPost);// 请求发送成功,并得到响应if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String str = "";try {// 读取服务器返回过来的json字符串数据str = EntityUtils.toString(result.getEntity(), "utf-8");// 把json字符串转换成json对象jsonResult = JSONObject.parseObject(str);} catch (Exception e) {logger.error("post请求提交失败:" + url, e);}}} catch (IOException e) {logger.error("post请求提交失败:" + url, e);} finally {httpPost.releaseConnection();}return jsonResult;}/*** post请求传输String参数 例如:name=Jack&sex=1&type=2* Content-type:application/x-www-form-urlencoded* * @param url* url地址* @param strParam* 参数* @return*/public static JSONObject httpPost(String url, String strParam) {// post请求返回结果CloseableHttpClient httpClient = HttpClients.createDefault();JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);httpPost.setConfig(requestConfig);try {if (null != strParam) {// 解决中文乱码问题StringEntity entity = new StringEntity(strParam, "utf-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/x-www-form-urlencoded");httpPost.setEntity(entity);}CloseableHttpResponse result = httpClient.execute(httpPost);// 请求发送成功,并得到响应if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String str = "";try {// 读取服务器返回过来的json字符串数据str = EntityUtils.toString(result.getEntity(), "utf-8");// 把json字符串转换成json对象jsonResult = JSONObject.parseObject(str);} catch (Exception e) {logger.error("post请求提交失败:" + url, e);}}} catch (IOException e) {logger.error("post请求提交失败:" + url, e);} finally {httpPost.releaseConnection();}return jsonResult;}/*** 发送get请求* * @param url* 路径* @return*/public static JSONObject httpGet(String url) {// get请求返回结果JSONObject jsonResult = null;CloseableHttpClient client = HttpClients.createDefault();// 发送get请求HttpGet request = new HttpGet(url);request.setConfig(requestConfig);try {CloseableHttpResponse response = client.execute(request);// 请求发送成功,并得到响应if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 读取服务器返回过来的json字符串数据HttpEntity entity = response.getEntity();String strResult = EntityUtils.toString(entity, "utf-8");// 把json字符串转换成json对象jsonResult = JSONObject.parseObject(strResult);} else {logger.error("get请求提交失败:" + url);}} catch (IOException e) {logger.error("get请求提交失败:" + url, e);} finally {request.releaseConnection();}return jsonResult;} }
2、在A项目下新建中转类,添加中转方法(其实就是一个controller类,注意注解使用 @RestController ,使用 @Controller 会取不到数据)
package 自己包名路径;import java.util.HashMap; import java.util.Map;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSONObject; import com.chang.util.HttpClientUtils;@RestController public class Azhong {
//中转方法@RequestMapping("/forwardB")public Map<String,Object> forwardB() {System.out.println("进来A的中转站了");JSONObject jb = HttpClientUtils.httpGet("要访问的B项目的方法的路径");
//下面是自己具体的业务处理,这里只是demo测试Map<String, Object> map = new HashMap<String, Object>();map.put("retCode", jb.get("retCode").toString());map.put("retMsg", jb.get("retMsg").toString());
return map;} }
3、前端 ajax 的 url : "http://A项目路径/forwardB", 数据类型 dataType : "json"
url : "http://A项目路径/forwardB", //访问自己的中转方法
dataType : json