How to add Access-Control-Allow-Origin to jetty server
30,122
Setup the org.eclipse.jetty.servlets.CrossOriginFilter
in your web app.
Old question/answer on the topic: https://stackoverflow.com/a/8454168/775715
See Jetty Documentation Hub on CrossOriginFilter Use:
Quick Start
Grab yourself a copy of jetty-servlets.jar.
Put the
jetty-servlets.jar
in yourWEB-INF/lib
Add the following to your
WEB-INF/web.xml
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
<init-param>
<param-name>allowedOrigins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>allowedMethods</param-name>
<param-value>GET,POST,HEAD</param-value>
</init-param>
<init-param>
<param-name>allowedHeaders</param-name>
<param-value>X-Requested-With,Content-Type,Accept,Origin</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Author by
Imesh Chandrasiri
Enthusiastic Javascript developer who learn new things everyday. The power of JS have amazed me alot. :)
Updated on July 09, 2022Comments
-
Imesh Chandrasiri almost 2 years
I've got a jetty server to run my web services. Recently I developed a program to consume the web service and ran into Access-Control-Allow-Origin issue.
How can I add the Access-Control-Allow-Origin: * to a jetty embedded server.
below is the webappcontext code.
public WebAppContext buildWebAppContext(){ webAppContext = new WebAppContext(); webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml"); webAppContext.setResourceBase("."); webAppContext.setContextPath("/posApplication"); webAppContext.setAttribute("webContext", webAppContext); return webAppContext; }
Thank you.
-
black666 over 9 yearsNote that wildcards like "*" are not allowed for headers. I had to explicitly provide a list of the headers for it to work. See killer7's answer in the question you've linked.
-
Joakim Erdfelt over 9 yearsWhen this was answered, back in Apr 2013, it was correct. Things have changed since then.
-
Lorenzo Sciuto about 8 years@JoakimErdfelt can you please link me to a correct solution? this one is not working for me
-
Dominic over 5 yearsThanks, do I need to rename it to java-servlets.jar? Does it get automatically picked up? Only with that name rather than jetty-servlets-9.4.9.v20180320?
-
Joakim Erdfelt over 5 years@Dominic that's a good candidate for a new question as it depends on your setup (using newer
jetty-home-<ver>.tar.gz
? or olderjetty-distribution-<ver>.tar.gz
? or standalone? or jetty-runner? or jetty-maven-plugin? or embedded-jetty?) -
mbokil over 4 yearsAnother workaround is to just launch Chrome without CORS rules. Quit Chrome completely. Then open a terminal and execute: open -a Google\ Chrome --args --disable-web-security --user-data-dir