Add Access-Control-Allow-Origin to Web Service

2019-02-21 04:46发布

问题:

I have a webservice like:

@Controller
@RequestMapping("/")
public class ApplicationController {

    @RequestMapping(value="/Changes", method = RequestMethod.GET)
    public String inspect(ModelMap model) {
         model.addAttribute("msg", "example");

         return "index";
    }
}

in the link: "localhost:8081/ChangesPDF/Changes?..."

I'm trying to get the response of this webservice through Alfresco that is in the link: "localhost:8080/share". I have different ports now (when I have same ports, this works good), so, with different ports I get the error in Alfresco:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/ChangesPDF/Changes?... (Reason: Header CORS 'Access-Control-Allow-Origin' missing).

How can I add this header?

回答1:

You should add a filter that sets the "Access-Control-Allow-Origin" to accepts domain "localhost:8081" (* for all).

Most probably you will find your answer here cores-filter-not-working

More explanation:

Create a filter class first

public class CorsFilter implements Filter {

    private static final Logger log = Logger.getAnonymousLogger();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // can be moved to properties
        String[] allowDomain = {"localhost:8080","localhost:8081"};              


        String originHeader = request.getHeader("host");

        for(String domian : allowDomain){

            if(originHeader.endsWith(domian))

            response.setHeader("Access-Control-Allow-Origin", originHeader);
            break;
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {}
}

Add mapping to your web.xml class

<filter>
    <filter-name>cors</filter-name>
    <filter-class>full name of your filter class here</filter-class>
</filter>

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

you should correclty define the URL pattren in web.xml config according to your requirnment



回答2:

If you are using Spring 4.2+, you can use the @CrossOrigin annotation :

@Controller
@RequestMapping("/")
public class ApplicationController {

    @CrossOrigin
    @RequestMapping(value="/Changes", method = RequestMethod.GET)
    public String inspect(ModelMap model) {
         model.addAttribute("msg", "example");

         return "index";
    }
}

Otherwise, you'll need to register a CORS filter in your Spring application. Something like this.



回答3:

I think your code may need to use Spring's @CrossOrigin annotation, e.g.:

import org.springframework.web.bind.annotation.CrossOrigin;

....

@Controller
@RequestMapping("/")
public class ApplicationController {

    @CrossOrigin
    @RequestMapping(value="/Changes", method = RequestMethod.GET)
    public String inspect(ModelMap model) {
        model.addAttribute("msg", "example");

        return "index";
    }
}

This will allow all origins, which may or may not be enough for your needs.

For reference, I found the above described in this article, and mentioned in the Spring blog here.

Hope this helps!