enabling CORS in TOMCAT 7 servlets for post request

我与影子孤独终老i 提交于 2020-01-03 02:24:27

问题


I'm using tomcat 7 to run my servlets on my Dynamic web project in java (eclipse ee). I've added to my web.xml file the following paragraph (from https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter/Introduction):

<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>"

I am trying to use the post request from chrome using the following angular js code:

app.controller("LoginControler", function($scope,$rootScope,$http) {
  $scope.submit = function () {
       $rootScope.ret = "clicked";
      var data = {
                CompanyName: $scope.CompanyName,
                UserName: $scope.UserName,
                Password: $scope.Password,

        };
        $http.post(URL, data).success(function(data, status) {
            $rootScope.ret = data;
        })
  }
});

and I keep getting the following error code: "XMLHttpRequest cannot load http://localhost:8080/Project-FrontEnd/ServletUsers. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403."

I tried all solutions that I could find but no help...please can any body solve my problem?


回答1:


You need to add the "Access-Control-Allow-Origin" value for the CorsFilter. Now Tomcat says that from your origin you cannot access here. Add this to the CorsFilter configuration:

<filter>
   <filter-name>CorsFilter</filter-name>
   <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
   //add below config
   <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>

</filter>

<filter-mapping>
   <filter-name>CorsFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

So with this configuration you can determine from which domains requests are allowed. Instead of * you can add comma separated domains that can access your resources.




回答2:


hi friends only updating tomcat from version 7 to version 8.5 solved the problem with the original solution.



来源:https://stackoverflow.com/questions/42091246/enabling-cors-in-tomcat-7-servlets-for-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!