Implementing CORS Cross‑Origin Requests in a Java Spring Backend

This article explains the browser same‑origin policy, defines cross‑origin requests, outlines the restrictions they impose, and presents five practical ways—global filter, WebMvcConfigurer, @CrossOrigin annotation, manual response headers, and a custom filter—to enable CORS in a Java Spring MVC backend with complete code examples.

Architect
Architect
Architect
Implementing CORS Cross‑Origin Requests in a Java Spring Backend

The browser enforces a Same‑Origin Policy that blocks JavaScript on one origin from interacting with resources from another origin; an origin is defined by the combination of protocol, host, and port.

When any of these three components differ, the request is considered cross‑origin, and the browser restricts reading cookies, LocalStorage, IndexedDB, accessing the DOM, and sending AJAX requests to the foreign site.

To allow cross‑origin communication in a Java Spring backend, you can choose among several approaches:

Global CORS filter bean – define a @Configuration class that creates a CorsFilter bean with permissive settings and registers it for all paths.

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        // 1. configure CORS
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.addExposedHeader("*");
        // 2. map to URL pattern
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 3. return filter
        return new CorsFilter(source);
    }
}

Override WebMvcConfigurer – implement the interface and add CORS mappings in addCorsMappings.

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

Use the @CrossOrigin annotation (local CORS) – place it on a controller class or individual handler methods.

@RestController
@CrossOrigin(origins = "*")
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "hello world";
    }
}

Or on a method: <code>@RequestMapping("/hello") @CrossOrigin(origins = "*") public String hello() { return "hello world"; }</code>

Manually set response headers – add Access-Control-Allow-Origin (and other CORS headers) to the HttpServletResponse inside a handler.

@RequestMapping("/index")
public String index(HttpServletResponse response) {
    response.addHeader("Access-Allow-Control-Origin", "*");
    return "index";
}

Custom filter implementation – create a servlet filter that sets the required CORS headers for every request and register it in web.xml.

package com.mesnac.aop;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class MyCorsFilter 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,content-type");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}
<!-- CORS filter registration in web.xml -->
<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.mesnac.aop.MyCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

All these solutions ultimately modify the HTTP response headers so that browsers accept cross‑origin requests, and they require Spring MVC 4.2+ (Spring Boot 1.3+) for the first three methods.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaCORSWeb Security
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.