解决“跨域问题”的几种方法

(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

 

转载于:https://www.cnblogs.com/xuehuashanghe/p/9687066.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/249458.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Conda 安装本地包

有的conda或pipy源太慢&#xff0c;conda install xxx或者pip install xxx下载会中断连接导致压缩包下载不全&#xff0c;本地的安装包没法完全安装, 遇到这个问题时&#xff0c;我们可以用p2p工具-迅雷等先下载指定包再用conda或pip安装 pip 安装本地包pip install D:\XXX.w…

DESUtils 加解密时 Given final block not properly padded bug小记

事情的经过是这个样子的。。。。。。 先说说问题是怎么出现的。根据客户需求&#xff0c;需要完成一个一键登录的功能&#xff0c;于是我的项目中就诞生了DesUtil&#xff0c;但是经过上百次用户测试&#xff0c;发现有一个用户登录就一直报错&#xff01;难道又遇到神坑啦&am…

Apache

https://www.iteye.com/blog/yaodaqing-1596570

仿 腾讯新闻快讯 --无缝滚动

//无缝滚动function AutoScroll(obj) {var autoScrollTimernull,timernull;timersetTimeout(function(){move();},3000);function move(){clearTime(autoScrollTimer);var liLen $(obj).find(li).length;if(liLen 1){//此处处理只有一条数据时 跳动效果$(obj).find("ul:f…

spring3.2 @Scheduled注解 定时任务

1.首先加入 下载spring3.2 &#xff0c;http://projects.spring.io/spring-framework/ 2.加入jar包&#xff0c;在applicationContext.xml加入声明-xmlns加入[java xmlns:task"http://www.springframework.org/schema/task" -xsi加入[java] http://www.springframe…

搜索(题目)

A.POJ_1321考查DFS的一个循环中递归调用 1 #include<iostream>2 #include<cstring>3 4 using namespace std;5 char a[10][10]; //记录棋盘位置6 int book[10]; //记录一列是否已经放过棋子7 int n, k; // k 为 需要放入的棋子数8 int t…

rest_framework中的url注册器,分页器,响应器

url注册器&#xff1a; 对于authors表&#xff0c;有两个url显得麻烦&#xff1a; rest_framework将我们的url进行了处理&#xff1a; 这样写了之后&#xff0c;就可以像原来一样访问author表了。 故意写错路径&#xff0c;看看它为我们做了哪些配置&#xff1a; 在有关author的…

Alluxio学习

介绍 Alluxio&#xff08;之前名为Tachyon&#xff09;是世界上第一个以内存为中心的虚拟的分布式存储系统。它统一了数据访问的方式&#xff0c;为上层计算框架和底层存储系统构建了桥梁。应用只需要连接Alluxio即可访问存储在底层任意存储系统中的数据。此外&#xff0c;Allu…

freemarker常见语法大全

FreeMarker的插值有如下两种类型:1,通用插值${expr};2,数字格式化插值:#{expr}或#{expr;format} ${book.name?if_exists } //用于判断如果存在,就输出这个值 ${book.name?default(‘xxx’)}//默认值xxx ${book.name!"xxx"}//默认值xxx ${book.date?string(yyy…

网页排版与布局

一 网站的层次结构 制作便于浏览页面的一个大敌就是视觉干扰,它包含两类: a,混乱页面主次不清,所有东西都引人注目 b,背景干扰 1.把页面分割成清晰明确的不同区域很重要,因为可以使用户迅速判断出哪些区域应重点看,哪些可以放心地忽略. 2.创建清晰直观的页面层次结构;越重要越要…

Bash的循环结构(for和while)

在bash有三中类型的循环结构表达方法&#xff1a;for&#xff0c;while&#xff0c;until。这里介绍常用的两种&#xff1a;for和while。 for bash的for循环表达式和python的for循环表达式风格很像&#xff1a; for var in $(ls) doecho "$var"done 取值列表有很多种…

MVVM模式下实现拖拽

MVVM模式下实现拖拽 原文:MVVM模式下实现拖拽在文章开始之前先看一看效果图 我们可以拖拽一个"游戏"给ListBox,并且ListBox也能接受拖拽过来的数据&#xff0c; 但是我们不能拖拽一个"游戏类型"给它。 所以当拖拽开始发生的时候我们必须添加一些限制条件&a…

nodejs变量

https://www.cnblogs.com/vipyoumay/p/5597992.html

jenkins+Docker持续化部署(笔记)

参考资料&#xff1a;https://www.cnblogs.com/leolztang/p/6934694.html &#xff08;Jenkins&#xff08;Docker容器内&#xff09;使用宿主机的docker命令&#xff09; https://container-solutions.com/running-docker-in-jenkins-in-docker/ &#xff08;Running Docker i…

正则表达式之括号

正则表达式&#xff08;三&#xff09; 括号 分组 量词可以作用字符或者字符组后面作为限定出现次数&#xff0c;如果是限制多个字符出现次数或者限制一个表达式出现次数&#xff0c;需要使用括号()将多个字符或者表达式括起来&#xff0c;这样便称为分组。例如(ab)表示“ab”字…

免安装Mysql在Mac中的神坑之Access denied for user 'root'@'localhost' (using password: YES)

眼看马上夜深人静了&#xff0c;研究了一天的问题也尘埃落定了。 废话不多说 直接来干货&#xff01; 大家都知道免安装版本的Mysql, 在Mac中安装完成&#xff08;如何安装详见Mac OS X 下 TAR.GZ 方式安装 MySQL&#xff09;之后&#xff0c;在登录时会遇到没有访问权限的问题…

nodejs函数

https://www.cnblogs.com/yourstars/p/6121262.html

[HNOI2009]梦幻布丁

题目描述 N个布丁摆成一行,进行M次操作.每次将某个颜色的布丁全部变成另一种颜色的,然后再询问当前一共有多少段颜色.例如颜色分别为1,2,2,1的四个布丁一共有3段颜色. 第一行给出N,M表示布丁的个数和好友的操作次数. 第二行N个数A1,A2...An表示第i个布丁的颜色从第三行起有M行,…

用jquery实现html5的placeholder功能

版权声明&#xff1a;本文为博主原创文章。未经博主同意不得转载。 https://blog.csdn.net/QianShouYuZhiBo/article/details/28913501 html5的placeholder功能在表单中经经常使用到。它主要用来提示用户输入信息&#xff0c;当用户点击该输入框之后&#xff0c;提示文字会自己…

mac环境下node.js和phonegap/cordova创建ios和android应用

mac环境下node.js和phonegap/cordova创建ios和android应用 一介布衣 2015-01-12 nodejs 6888 分享到&#xff1a;QQ空间新浪微博腾讯微博人人网微信引用百度百科的一段描述:PhoneGap是一个用基于HTML&#xff0c;CSS和JavaScript的&#xff0c;创建移动跨平台移动应用程序的…