SAP ABAP和Java跨域请求问题的解决方案-阿里云开发者社区

开发者社区> 开发者小助手-bz4> 正文

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

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.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

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
JavaWeb 乱码问题终极解决方案!
JavaWeb 乱码问题终极解决方案! 经常有读者在公众号上问 JavaWeb 乱码的问题,昨天又有一个小伙伴问及此事,其实这个问题很简单,但是想要说清楚却并不容易,因为每个人乱码的原因都不一样,给每位小伙伴都把乱码的原因讲一遍也挺费时间的,因此,松哥今天决定写一篇文章,和大伙好好捋捋 JavaWeb 中的乱码问题。
1416 0
Java 邮件(问题解决)
Java 邮件(问题) A secure connection is requiered(such as ssl). 问题详情: javax.mail.
1279 0
怎么设置阿里云服务器安全组?阿里云安全组规则详细解说
阿里云服务器安全组设置规则分享,阿里云服务器安全组如何放行端口设置教程
8419 0
阿里云推出全球应用加速解决方案,快速提升跨域应用访问体验
近日,阿里云全球加速产品推出全球应用加速等多个新特性,融合云安全DDoS高防与WAF的安全防护能力,结合云解析智能DNS与GTM全局流量调度,保障企业全球应用部署的高质量、高安全、高可靠。另外邀请到在线互联网教育机构—豌豆思维,进一步分享了他们使用全球加速的经验。
567 0
关于my.getAuthUserInfo报错:error4,无权跨域调用 的解决方案
使用my.getAuthUserInfo之前,是需要先使用my.getAuthCode的,两个API可以嵌套使用: my.getAuthCode({ scopes: 'auth_user', success: (res) => { my.
1661 0
iframe跨域解决方案
    公司某个功能用的是iframe,由于跨域的原因,我们不能直接设置父级页面iframe的高度,所以用了一个中间页home来完成父级页面iframe的高度设置,这种中间页其实很多时候不好用,因为涉及到页面跳转和刷新,每次都得刷一下页面,而消息发送成功页的一个定位到顶部的功能,就是由于页面刷了一次导致体验不好,除了体验,这种中间页跳转的做法也很蹩脚和繁琐。
987 0
Vue:处理Axios多次请求问题数据显示问题
Vue:处理Axios多次请求问题数据显示问题
17 0
2315
文章
0
问答
来源圈子
更多
+ 订阅
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载