Enable Cors using Spring 3.0.4

余生颓废 提交于 2021-02-19 04:23:04

问题


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.

My back-end is an angular application running on: 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!!");
}       

回答1:


You can extends Filter interface.

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

<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>



回答2:


You can enable CORS by creating an Interceptor. Please follow below steps:

  1. Create a Interceptor by Extending 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.

    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. So, you have to dispatch Options request. You can add dispatchOptionRequest on web.xml as follows:

    <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.




回答3:


With WebMVC it is possible and works for me. Try this , but if you use spring security i might need to update the answer

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


来源:https://stackoverflow.com/questions/55363203/enable-cors-using-spring-3-0-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!