简体   繁体   English

使用Spring 3.0.4启用Cors

[英]Enable Cors using Spring 3.0.4

I'm using Java Spring 3.0.4 (can't upgrade due to some requirements) and I need to enable Cors in order for my front-end to talk to my back-end. 我正在使用Java Spring 3.0.4(由于某些要求而无法升级),并且需要启用Cors,以便前端与后端进行通信。

My back-end is an angular application running on: http://localhost:4200/home 我的后端是一个运行在以下位置的有角度的应用程序: http:// localhost:4200 / home

I have tried the following with no luck: 我没有运气就尝试了以下方法:

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!!");
}       

You can extends Filter interface. 您可以扩展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() {

  }
}

And then you need to register filter in web.xml 然后您需要在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>

You can enable CORS by creating an Interceptor. 您可以通过创建拦截器来启用CORS。 Please follow below steps: 请按照以下步骤操作:

  1. Create a Interceptor by Extending HandlerInterceptorAdapter 通过扩展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. Register the above created interceptor on your web configuration. 在您的Web配置上注册上面创建的拦截器。

     public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CorsInterceptor()); } // continue if any .. } 
  3. Above works fine for GET requests but for any other modification request (POST, DELETE, PUT), browser will send preflight OPTIONS request which SpringMVC ignores. 上面的方法对于GET请求很好用,但是对于任何其他修改请求(POST,DELETE,PUT),浏览器将发送SpringMVC忽略的预检OPTIONS请求。 So, you have to dispatch Options request. 因此,您必须调度“选项”请求。 You can add dispatchOptionRequest on web.xml as follows: 您可以在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> 

Hope this helps! 希望这可以帮助! Thanks. 谢谢。

With WebMVC it is possible and works for me. 有了WebMVC,就可以为我工作。 Try this , but if you use spring security i might need to update the answer 试试这个,但是如果您使用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);
 }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM