2015-02-23 173 views
0

我有这样的服务,我在我的本地机器上公布:配置http请求spring mvc和angular js?

http://joediego.dtdns.net:3000/jcsistemas/rest/cliente/all 

如果我打afromentioned URL终点,我可以让我的JSON提要响应。但是当我使用另一个主机名,如http://localhost:8081,服务与以下消息响应:

XMLHttpRequest can not load http: // localhost: 8081/jcsistemas/rest/customer/all. In the 'Access-Control-Allow-Origin "header is present on the requested resource. Origin 'http: // localhost: 9000' is not allowed Therefore access. 

这里是我试过至今克服了同源策略的问题:

import java.io.IOException; 

import javax.servlet.Filter; 
import javax.servlet.FilterChain; 
import javax.servlet.FilterConfig; 
import javax.servlet.ServletException; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
import javax.servlet.http.HttpServletResponse; 

import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.stereotype.Component; 
//filter 
@Component 
public class SimpleCORSFilter implements Filter { 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
     HttpServletResponse response = (HttpServletResponse) res; 
     response.setHeader("Access-Control-Allow-Origin", "*"); 
     response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 
     response.setHeader("Access-Control-Max-Age", "3600"); 
     response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 
     chain.doFilter(req, res); 
    } 

    public void init(FilterConfig filterConfig) {} 
    public void destroy() {} 
} 

@Configuration 
@EnableWebMvc 
@ComponentScan("my..package...... ") 
public class WebAppConfig extends WebMvcConfigurerAdapter { 

    //configureContentNegotiation 
    @Override 
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { 
     configurer.favorPathExtension(true). 
       ignoreAcceptHeader(true). 
       useJaf(false). 
       defaultContentType(MediaType.APPLICATION_JSON). 
       mediaType("html", MediaType.TEXT_HTML). 
       mediaType("xml", MediaType.APPLICATION_XML); 
    } 
} 

AngualarJS模块配置:

angular.module('my_module').config(['$routeProvider','$httpProvider',function($routeProvider,$httpProvider) { 
    //how configure headers here??  
    }]); 
}()); 

回答

0

我设法解决我的问题,通过删除@Component SimpleCorsFilter并添加getServletFilters()方法在WebApplicationInitializer子类中。对于那些使用基于Java的应用程序配置的人员,请在此处下载组件声明:

public MyWebApplicationInitializer implements WebApplicationInitializer 
{ 
    @ Override 
    protected Filter[] getServletFilters() 
    { 
     return new Filter[] {new MyFilter()}; // MyFilter refers to the filter needed class 
    } 
}