How to add Access-Control-Allow-Origin to jetty server

本秂侑毒 提交于 2019-12-28 02:13:07

问题


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.


回答1:


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

  1. Grab yourself a copy of jetty-servlets.jar.

  2. Put the jetty-servlets.jar in your WEB-INF/lib

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



回答2:


The workaround for this CORS problem is to use an extension in chrome/chromium browser. here is the link for the extension.

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog

No need to add any headers in the server side code(which will obviously work but may not be a good idea).



来源:https://stackoverflow.com/questions/16037558/how-to-add-access-control-allow-origin-to-jetty-server

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