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.
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
相关文章
- java-GUI编程之布局类型介绍
- 2021 大数据应用开发Java 1+x初级实操题答案汇总–含2篇
- java指定长度数组长度_Java声明数组时不能指定其长度[通俗易懂]
- java数组排序去重_JAVA数组去重排序
- java中文乱码_Java中文乱码问题的解决方案[通俗易懂]
- MySQL字段类型如何转为java_Java JDBC中,MySQL字段类型到JAVA类型的转换
- java jersey使用总结_Java Jersey2使用总结
- java 读取字符串文件_Java读取文件为字符串
- java销毁定时器_Java 定时器退出解决方案
- Java截取字符串方法_java通过split截取字符串
- Java异或什么意思_0与0异或
- java+sm4+加密算法_SM4加密算法实现Java和C#相互加密解密
- Java疫苗预约小程序线上疫苗预约系统
- 关于 SAP UI5 接口 sap.ui.core.IAsyncContentCreation 的问题讨论
- 【Android FFMPEG 开发】FFMPEG ANativeWindow 原生绘制 ( Java 层获取 Surface | 传递画布到本地 | 创建 ANativeWindow )
- Java获取几天后的日期详解编程语言
- 银联支付Java开发详解编程语言
- 更新LINUX下的Java版本(linux更新java)
- 策略解析Redis Java过期策略(redisjava过期)
- 设置Redis实现Java中过期设置的技术实现(redisjava过期)
- Java如何启动MySQL?(java启动mysql)
- Deploying Java on Linux: A Simple Guide for Beginners.(linux上部署java)
- Linux系统中下载Java的方法(linux下java下载)
- Java运行在Linux系统上免费下载(linux java下载)
- Linux下编译Java文件,迎来新体验(linux编译java文件)
- Novice:学习Java 7 在Linux上的简单入门(java 7 linux)
- 秘籍学习实现纯Java版Redis(纯java版redis)
- Redis实现Java语言下的遍历处理(redis遍历java)
- Oracle与SAP金蝶谁更具竞争力(oracle sap金蝶)
- 浅析Java中Map与HashMap,Hashtable,HashSet的区别