5 Proven Ways to Enable CORS in Java Backend Applications

This guide explains the browser's same‑origin policy, defines cross‑origin requests, outlines the restrictions on non‑same‑origin resources, and presents five Java‑backend techniques—including a global CorsFilter bean, WebMvcConfigurer, @CrossOrigin annotation, manual response headers, and a custom filter—to enable CORS.

Programmer DD
Programmer DD
Programmer DD
5 Proven Ways to Enable CORS in Java Backend Applications

Why CORS Issues Occur

The browser enforces the Same‑Origin Policy, a core security rule that blocks a script from one origin from interacting with resources from another origin. An origin is defined by the combination of protocol, host, and port.

What Is Cross‑Origin

A request is considered cross‑origin when its protocol, domain, or port differs from those of the current page.

Non‑Same‑Origin Restrictions

Cannot read cookies, LocalStorage, or IndexedDB of a non‑same‑origin page.

Cannot access the DOM of a non‑same‑origin page.

Cannot send AJAX requests to a non‑same‑origin address.

Java Backend Implementations of CORS

There are five common ways to enable CORS in a Spring‑based Java backend.

Return a new CorsFilter bean (global configuration).

Implement WebMvcConfigurer and override addCorsMappings (global configuration).

Use the @CrossOrigin annotation (local configuration on controller or method).

Manually set response headers via HttpServletResponse (local configuration).

Create a custom filter that adds the necessary CORS headers (global or local).

1. Return a New CorsFilter (Global)

Define a configuration class that creates a CorsFilter bean and registers a mapping for all paths.

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        // 1. Add CORS configuration
        CorsConfiguration config = new CorsConfiguration();
        // Allow any origin
        config.addAllowedOrigin("*");
        // Allow credentials (cookies)
        config.setAllowCredentials(true);
        // Allow any HTTP method
        config.addAllowedMethod("*");
        // Allow any header
        config.addAllowedHeader("*");
        // Expose any header
        config.addExposedHeader("*");
        // 2. Register the configuration for all paths
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 3. Return the filter
        return new CorsFilter(source);
    }
}

2. Override WebMvcConfigurer (Global)

Implement WebMvcConfigurer and configure CORS mappings.

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

3. Use @CrossOrigin Annotation (Local)

Apply @CrossOrigin on a controller class or method to enable CORS for specific endpoints.

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

Or on a method:

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

4. Manually Set Response Headers (Local)

Use HttpServletResponse to add the required CORS headers.

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

5. Custom Filter Implementation (Global or Local)

Create a filter that sets CORS headers for every request.

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 {
    @Override
    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);
    }
    @Override public void init(FilterConfig filterConfig) {}
    @Override public void destroy() {}
}

Configure the filter in web.xml to apply it to all URLs.

<!-- CORS filter START -->
<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>
<!-- CORS filter END -->
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.

JavaBackend DevelopmentSpring BootCORSCross-OriginWeb Security
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

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.