Expand my Community achievements bar.

SOLVED

Disabling CORS on a servlet without disabling CORS site-wide

Avatar

Level 1

I want to create a servlet that I can use to pass data to an in-browser javascript app. The issue I'm having is I can't find a way to disable CORS for the specific servlet - only for the entire site, which isn't ideal. Is there a way to achieve this?

1 Accepted Solution

Avatar

Correct answer by
Level 2

If the dispatcher is in the picture

1. Either set conditional apache header as per your request " e.g if your servlet URL is /wknd/marketting/

SetEnvIf Request_URI "/wknd/amrketting/" cors
Header Set Access-Control-Allow-Origin "YOUR_DOMAIN" env=cors

Or

2. Use rewrite rule by enabling mod_rewrite module

RewriteRule ^/wkndmarketting/$ - [ENV=cors:true]
Header set "Access-Control-Allow-Origin" "*" env=cors

 

Or

3. add header in servlet response

response.addHeader("Access-Control-Allow-Origin", "either specific domain or allow all by using * ");

 

Regards

View solution in original post

2 Replies

Avatar

Community Advisor

Did you try just appending the headers as part of your Servlet Response? Something like this:

 

response.addHeader("Access-Control-Allow-Origin", "*")

 

Another alternative could be to add headers through Apache, you will filter the incoming request to match your servlet path and then append the headers right there: https://ubiq.co/tech-blog/set-apache-header-conditionally/  



Esteban Bustamante

Avatar

Correct answer by
Level 2

If the dispatcher is in the picture

1. Either set conditional apache header as per your request " e.g if your servlet URL is /wknd/marketting/

SetEnvIf Request_URI "/wknd/amrketting/" cors
Header Set Access-Control-Allow-Origin "YOUR_DOMAIN" env=cors

Or

2. Use rewrite rule by enabling mod_rewrite module

RewriteRule ^/wkndmarketting/$ - [ENV=cors:true]
Header set "Access-Control-Allow-Origin" "*" env=cors

 

Or

3. add header in servlet response

response.addHeader("Access-Control-Allow-Origin", "either specific domain or allow all by using * ");

 

Regards