Search code examples
springspring-mvccorsspring-restcontroller

Add Access-Control-Allow-Origin to Web Service


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?


Solution

  • 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