SAP ABAP和Java跨域请求问题的解决方案

简介: 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



image.pngMETHOD 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.image.pngAnd 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.



image.pngThe 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:


image.pngThe response is available in JavaScript code:

image.pngChange the user id to any other one and the request will fail again:image.png

Cross Domain Request in Java

The similar logic as in ABAP.

Create a dynamic web project in Java with a servlet named “HelloWorldServlet”:

image.pngCopy 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:image.pngAnd perform positive test via an allowed user id specified in request:image.pngRequest is successfully handled and returned to browser:image.pngClient 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”


image.png

image.png

Once installed, just switch on CORS via checkbox:image.png

This extension will automatically add a new field in request header to do the magic:image.pngNow the response is available with the help of this extension, even the requested user id is not in allowed list:image.pngworkaround 2: disable same origin policy via Chrome start command argument –disable-web-security

Create a new shortcut and add the argument –disable-web-security


image.png


image.pngrequest detail:

image.pngThis time the request is still successfully handled – you will see a warning “Stability and security will suffer.” in Chrome.

image.png

相关文章
|
4月前
|
JavaScript 安全 Java
Java - 探究前后分离带来的跨域问题
Java - 探究前后分离带来的跨域问题
30 1
|
7月前
|
存储 Java 数据库
如何在 SAP BTP Java 应用里使用 SQLite 数据库
如何在 SAP BTP Java 应用里使用 SQLite 数据库
72 0
|
7月前
|
Java 数据库 Spring
使用 SAP BTP 创建一个 Spring Boot Java 应用
使用 SAP BTP 创建一个 Spring Boot Java 应用
109 0
|
5月前
|
缓存 前端开发 Java
13:SpringBoot跨域解决方案-Java Spring
13:SpringBoot跨域解决方案-Java Spring
85 0
|
7月前
|
Java Windows 容器
SAP Java Connector 的配置指南
SAP Java Connector 的配置指南
88 0
|
8月前
|
Java 数据库 数据库管理
一个实际的例子学习 SAP BTP Java 应用的 @Before 注解使用方式
一个实际的例子学习 SAP BTP Java 应用的 @Before 注解使用方式
88 0
|
3月前
|
Java
【Java专题_03】spring-boot跨域问题如何解决
【Java专题_03】spring-boot跨域问题如何解决
|
7月前
|
存储 Java BI
如何使用 Java 程序通过 SAP Java Connector 调用 ABAP 系统的函数试读版
如何使用 Java 程序通过 SAP Java Connector 调用 ABAP 系统的函数试读版
52 0
|
7月前
|
负载均衡 网络协议 Java
SAP Java Connector 错误 - JCO_ERROR_COMMUNICATION
SAP Java Connector 错误 - JCO_ERROR_COMMUNICATION
116 0
|
4月前
|
JavaScript 前端开发 Java
Java其他: 解释一下跨域资源共享(CORS)。
Java其他: 解释一下跨域资源共享(CORS)。
47 0