Handling CORS in SpringBoot: Concepts and Implementation Methods
This article explains the concept of Cross-Origin Resource Sharing (CORS), its role in browser security, and provides three practical ways to handle CORS in SpringBoot applications—including using the @CrossOrigin annotation, a dedicated configuration class, and a custom filter—complete with code examples.
Cross‑origin requests are blocked by browsers due to the Same‑Origin Policy, which requires the protocol, domain, and port to match. When a request is sent from a different origin, the browser intercepts the response even though the server may have processed it correctly.
CORS (Cross‑Origin Resource Sharing) is a W3C standard that allows browsers to make cross‑origin XMLHttpRequest calls when the server includes specific response headers, most importantly Access-Control-Allow-Origin . If the browser determines that the request’s Origin is permitted, it will allow the response to be accessed.
Typical CORS response headers include:
Access-Control-Allow-Origin: http://www.xxx.com
Access-Control-Max-Age: 86400
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Credentials: true
1. Using the @CrossOrigin annotation (SpringBoot / Spring MVC)
Apply @CrossOrigin directly on a controller class or method. This is the simplest approach but requires adding the annotation to every controller that needs CORS support.
@RestController
@CrossOrigin
@RequestMapping("/situation")
public class SituationController extends PublicUtilController {
@Autowired
private SituationService situationService;
// log日志信息
private static Logger LOGGER = Logger.getLogger(SituationController.class);
}If many controllers share the same CORS configuration, place the annotation on a common base controller and let all others extend it:
@CrossOrigin
public class PublicUtilController {
/**
* 公共分页参数整理接口
*/
public PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {
PageInfoUtil pageInfoUtil = new PageInfoUtil();
try {
pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
} catch (NumberFormatException e) {
}
return pageInfoUtil;
}
}The annotation works with SpringBoot 2.x and Spring MVC 4.2+ (or later). For older versions you can also modify Tomcat’s web.xml configuration.
2. Configuring CORS with a dedicated configuration class
Create a class that implements WebMvcConfigurer (or extends the deprecated WebMvcConfigurerAdapter ) and override addCorsMappings :
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods(ORIGINS)
.maxAge(3600);
}
}3. Using a custom filter to set CORS headers
Define a filter that adds the required headers to every response and handles pre‑flight OPTIONS requests:
@Component
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
@Override public void destroy() {}
@Override public void init(FilterConfig filterConfig) throws ServletException {}
}All three methods achieve the same goal: allowing cross‑origin requests while keeping the server side logic unchanged.
Conclusion
The article has presented the essential theory behind CORS and three practical implementations for SpringBoot projects, giving developers ready‑to‑use code snippets to solve cross‑origin issues efficiently.
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.