使用Spring 3.0.4启用Cors

时间:2019-03-26 17:37:19

标签: java spring http spring-mvc cors

我正在使用Java Spring 3.0.4(由于某些要求而无法升级),并且需要启用Cors,以便前端与后端进行对话。

我的后端是一个运行在http://localhost:4200/home

上的有角度的应用程序

我没有运气就尝试过以下方法:

public static final String CREDENTIALS_NAME = "Access-Control-Allow-Credentials";
public static final String ORIGIN_NAME = "Access-Control-Allow-Origin";
public static final String METHODS_NAME = "Access-Control-Allow-Methods";
public static final String HEADERS_NAME = "Access-Control-Allow-Headers";
public static final String MAX_AGE_NAME = "Access-Control-Max-Age";

@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value="/data", method=RequestMethod.GET)
public void serverSide(Model model,  HttpServletRequest request, HttpServletResponse response) throws IOException{

    response.setContentType("application/json");
    response.setHeader("Cache-Control", "no-store");

    response.setHeader(CREDENTIALS_NAME, "true");
    response.setHeader(ORIGIN_NAME, "http://localhost:4200");
    response.setHeader(METHODS_NAME, "GET, OPTIONS, POST, PUT, DELETE");
    response.setHeader(HEADERS_NAME, "Origin, X-Requested-With, Content-Type, Accept");
    response.setHeader(MAX_AGE_NAME, "3600");

    PrintWriter out = response.getWriter();

    out.print("TEST!!");
}       

3 个答案:

答案 0 :(得分:1)

您可以扩展Filter界面。

public class CORSFilter implements Filter {

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

  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse httpResponse = (HttpServletResponse) response;
      httpResponse.addHeader("Access-Control-Allow-Origin", "*");
      httpResponse.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS");
      httpResponse.setHeader("Access-Control-Allow-Headers", "X-Requested-With, X-Auth-Token");       chain.doFilter(request, response);
  }

  @Override
  public void destroy() {

  }
}

然后您需要在web.xml

中注册过滤器
<filter>
    <filter-name>cors</filter-name>
    <filter-class>com.yourpackage.CORSFilter</filter-class>
</filter>

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

答案 1 :(得分:0)

您可以通过创建拦截器来启用CORS。请按照以下步骤操作:

  1. 通过扩展 HandlerInterceptorAdapter

    创建拦截器
    public class CorsInterceptor extends HandlerInterceptorAdapter {
    
        public static final String CREDENTIALS_NAME = "Access-Control-Allow-Credentials";
        public static final String ORIGIN_NAME = "Access-Control-Allow-Origin";
        public static final String METHODS_NAME = "Access-Control-Allow-Methods";
        public static final String HEADERS_NAME = "Access-Control-Allow-Headers";
        public static final String MAX_AGE_NAME = "Access-Control-Max-Age";
    
       @Override
       public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
          Object handler) throws Exception {
          response.setHeader(CREDENTIALS_NAME, "true");
          response.setHeader(ORIGIN_NAME, "http://localhost:4200");
          response.setHeader(METHODS_NAME, "GET, OPTIONS, POST, PUT, DELETE");
          response.setHeader(HEADERS_NAME, "Origin, X-Requested-With, Content-Type, 
            Accept");
          response.setHeader(MAX_AGE_NAME, "3600");
          return true;
      }
    
    }
    
  2. 在您的网络配置中注册上面创建的拦截器。

    public class WebConfig extends WebMvcConfigurerAdapter {
    
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor());
      }
     // continue if any ..
    }
    
  3. 以上对于GET请求工作正常,但对于任何其他修改请求(POST,DELETE,PUT),浏览器将发送SpringMVC忽略的预检OPTIONS请求。因此,您必须调度“选项”请求。您可以在 web.xml 上添加dispatchOptionRequest,如下所示:

    <servlet>
        <servlet-name>servletName</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
         <param-name>dispatchOptionsRequest</param-name>
         <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

希望这会有所帮助! 谢谢。

答案 2 :(得分:0)

有了WebMVC,这是可能的并且对我有用。 尝试一下,但是如果您使用Spring Security,我可能需要更新答案

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfiguration implements WebMvcConfigurer {

private static final String HTTP_LOCALHOST_4200 = "http://localhost:4200";
private static final String GET = "GET";
private static final String POST = "POST";
private static final String PUT = "PUT";
private static final String DELETE = "DELETE";
private static final String HEAD = "HEAD";

@Override
public void addCorsMappings(CorsRegistry registry) {

    registry.addMapping("/**")
            .allowedOrigins(
                    HTTP_LOCALHOST_4200).allowedMethods(GET, POST, PUT, DELETE, 
  HEAD).allowCredentials(true);
 }
 }