Mastering CORS in Java: 5 Ways to Enable Cross-Origin Requests
This article explains why browsers enforce same‑origin policies, defines cross‑origin requests, outlines the restrictions on non‑same‑origin resources, and presents five practical Java backend solutions—including a global CorsFilter, WebMvcConfigurer, @CrossOrigin annotation, manual response headers, and a custom filter—complete with code examples.
Why CORS Issues Occur
Browsers enforce the Same‑Origin Policy to protect security; it blocks JavaScript on one origin from interacting with resources on another origin unless explicitly allowed.
What Is Cross‑Origin
A request is cross‑origin when its protocol, domain, or port differs from the current page.
Non‑Same‑Origin Restrictions
Cannot read cookies, LocalStorage, IndexedDB of other origins.
Cannot access the DOM of other origins.
Cannot send AJAX requests to other origins.
Java Backend Implementations for CORS
Several approaches are available:
Return a new CorsFilter bean (global configuration).
Override WebMvcConfigurer (global configuration).
Use the @CrossOrigin annotation (local configuration).
Manually set response headers via HttpServletResponse (local configuration).
Create a custom filter to add CORS headers (local configuration).
1. Global CorsFilter
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.addExposedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}2. Override WebMvcConfigurer
@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
@RestController
@CrossOrigin(origins = "*")
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello world";
}
}Or apply @CrossOrigin on a specific method.
@RequestMapping("/hello")
@CrossOrigin(origins = "*")
public String hello() {
return "hello world";
}4. Manual Response Headers
@RequestMapping("/index")
public String index(HttpServletResponse response) {
response.addHeader("Access-Allow-Control-Origin", "*");
return "index";
}5. Custom Filter Implementation
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() {}
}Configure this filter in web.xml to activate it.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
