SAP ABAP和Java跨域请求问题的解决方案
There is an excellent blog Cross-domain communications with ABAP and JSONP written by Alessandro Spadoni. And in this blog, I just record down my own study experience about how to achieve cross domain request in ABAP and Java.
Cross Domain Request in ABAP
Create a new ICF node in tcode SICF, implement the following source code in its handler class.4
METHOD if_http_extension~handle_request.
DATA: lv_text TYPE string value 'hello world'.
server->response->append_cdata(
data = lv_text
length = strlen( lv_text ) ).
ENDMETHOD.
Access the url in browser, and it works as expected.
And now try to access the url by AJAX in jQuery:
function getPostByAJAX(requestURL){
var html = $.ajax({
url: requestURL,
async: false}).responseText;
debugger;
return html;
}
You will get the following error message in browser: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.
The request fails to finish due to same origin policy.
One remedy is to use Cross-Origin Resource Sharing.
Add a few more codes in the ICF handler class:
METHOD if_http_extension~handle_request.
DATA: lv_text TYPE string VALUE 'hello world'.
CONSTANTS: cv_white_id TYPE string VALUE 'i042416'.
DATA(lv_origin) = server->request->get_header_field( 'origin' ).
DATA(lv_userid) = server->request->get_form_field( 'userId' ).
IF lv_userid = cv_white_id.
server->response->set_header_field(
EXPORTING
name = 'Access-Control-Allow-Origin'
value = lv_origin ).
ENDIF.
server->response->append_cdata(
data = lv_text
length = strlen( lv_text ) ).
ENDMETHOD.
And when requesting the resource again but this time with a hard coded user id which acts a a simulation of white list, the request can be successfully processed this time thanks to CORS:
The response is available in JavaScript code:
Change the user id to any other one and the request will fail again:
Cross Domain Request in Java
The similar logic as in ABAP. Create a dynamic web project in Java with a servlet named “HelloWorldServlet”:
Copy the following implementation source code into the Servlet:
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> allowedUserId = Arrays.asList(getServletContext().getInitParameter("userIds").trim().split(","));
String clientOrigin = request.getHeader("origin");
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
String userId = request.getParameter("userId");
if( userId != null)
userId = userId.trim();
if( allowedUserId.contains(userId)){
response.setHeader("Access-Control-Allow-Origin", clientOrigin);
}
if( ipAddress.equals("0:0:0:0:0:0:0:1"))
response.getWriter().println("local one");
else
response.getWriter().println("Hello World!");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
The web.xml in folder WEB-INF, which the allowed user ids are listed in node .
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>JerryTest</display-name>
<welcome-file-list>
<welcome-file>Hello</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>userIds</param-name>
<param-value>i042416,i042417,i042418</param-value>
</context-param>
<servlet>
<description></description>
<display-name>HelloWorldServlet</display-name>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>helloworld.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- http://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern -->
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>
Now access the servlet with user id which is not included in the list, and the request fails:
And perform positive test via an allowed user id specified in request:
Request is successfully handled and returned to browser:
Client side workaround
Sometimes for development purpose we would like to bypass the limitation of same origin policy, and here below are two approaches I used in my daily work.
workaround 1: use Chrome extension “Allow-Control-Allow-Origin”
Once installed, just switch on CORS via checkbox:
This extension will automatically add a new field in request header to do the magic:
Now the response is available with the help of this extension, even the requested user id is not in allowed list:
workaround 2: disable same origin policy via Chrome start command argument –disable-web-security
Create a new shortcut and add the argument –disable-web-security
request detail:
This time the request is still successfully handled – you will see a warning “Stability and security will suffer.” in Chrome.
- 以太坊·将自定义数据写入到区块链中
- 使用TensorFlow实现股票价格预测深度学习模型
- 06-移动端开发教程-fullpage框架
- 07-移动端开发教程-移动端视口
- 10-移动端开发教程-移动端事件
- 08-移动端开发教程-移动端适配方案
- 09-移动端开发教程-Sass入门
- 开发者的如何优雅的使用OSX
- Solidity 智能合约开发语言·数据类型
- 以太坊·Rinkeby 测试网络
- TensorFlow强化学习入门(0)——Q-Learning的查找表实现和神经网络实现
- 【云端架构】网站运维之CDN链接鉴权示例入门(PHP)
- 以太坊·单机多实例演示
- TensorFlow强化学习入门(1)——双臂赌博机
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- 学习一下Python3的协程
- Android网络收集和ping封装库
- Kubernetes之helm部署使用
- 想掌握 Binder 机制?驱动核心源码详解和Binder超系统学习资源,想学不会都难!
- leetcode链表之回文链表
- Docsify 安装
- Docsify 初始化文件夹
- ELK 日志系统集成 Skywalking 调用链 ID
- ChartCenter ——为您的K8s之旅保驾护航v
- leetcode链表之删除链表的节点
- iOS打包的那一些事情
- 腾讯云服务器(CentOS 7、Tencent Linux)手动搭建LNMP环境(linux+Nginx+Mariadb+PHP)
- iOS技术面试题及答案
- 虽然现在有可以去码的软件了,可视频是如何自动跟踪打码的?
- 2020-09-12:手撕代码:最小公倍数,复杂度多少?