Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...