Implementing CORS Cross-Origin Requests in Java Backend
This article explains the origin of CORS issues caused by the browser's Same‑Origin Policy, describes what constitutes a cross‑origin request, outlines the restrictions of non‑same‑origin resources, and provides five Java‑based solutions—including a global CorsFilter bean, WebMvcConfigurer override, @CrossOrigin annotation, manual response‑header setting, and a custom filter—to enable cross‑origin access.
Cross‑origin problems arise because browsers enforce the Same‑Origin Policy, which blocks JavaScript from interacting with resources that have a different protocol, host, or port.
What is cross‑origin
A request is considered cross‑origin when its protocol, domain, or port differs from the current page.
Restrictions of non‑same‑origin resources
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 approaches to enable CORS
Several methods can be used in Spring MVC/Spring Boot to add the required response headers.
1. Return a new CorsFilter (global)
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1. Add CORS configuration
CorsConfiguration config = new CorsConfiguration();
//Allowed origins
config.addAllowedOrigin("*");
//Allow credentials
config.setAllowCredentials(true);
//Allowed methods
config.addAllowedMethod("*");
//Allowed headers
config.addAllowedHeader("*");
//Exposed headers
config.addExposedHeader("*");
//2. Register mapping
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
//3. Return the filter
return new CorsFilter(corsConfigurationSource);
}
}2. Override WebMvcConfigurer (global)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("*")
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}3. Use @CrossOrigin annotation (local)
Apply the annotation on a controller class or method to allow cross‑origin access.
@RestController
@CrossOrigin(origins = "*")
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello world";
}
}Or on a specific method:
@RequestMapping("/hello")
@CrossOrigin(origins = "*")
public String hello() {
return "hello world";
}4. Manually set response headers (local)
@RequestMapping("/index")
public String index(HttpServletResponse response) {
response.addHeader("Access-Allow-Control-Origin", "*");
return "index";
}5. Custom filter implementation (local)
package com.mesnac.aop;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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() {}
}Configure this filter in web.xml to make it effective.
Note: The @CrossOrigin annotation and the configuration classes require Spring MVC 4.2+ (Spring Boot 1.3+). Global configurations affect all endpoints, while local annotations or manual header settings provide finer‑grained control. All approaches ultimately modify the response headers to satisfy the browser's CORS requirements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
