CORS Handling Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in Java as in every other language.
- ✓The JDK does ship an HTTP server, com.sun.net.httpserver, and it has no notion of CORS, so the portable seam is the Servlet API: jakarta.servlet.Filter, HttpServletResponse setHeader and addHeader, and @WebFilter, all honoured by Tomcat, Jetty and Spring Boot alike.
- ✓Two things get checked in review: that the filter is ordered early enough to run ahead of authentication, and that it terminates the preflight itself rather than calling chain.doFilter.
- ✓The Java trap: A preflight is anonymous by specification: the browser strips cookies, the Authorization header and every custom header from the OPTIONS probe.
- ✓The filter executes on the request thread before the container has done anything expensive, and contains on a two-element Set.of is a hash probe with no iterator allocation.
What CORS Handling actually is
CORS Handling in Java: what you actually reach for
Java implementation
package dev.example.web;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
@WebFilter(urlPatterns = "/*")
public class CorsFilter implements Filter {
private static final Set<String> ALLOWED = Set.of("https://app.example.dev", "https://ops.example.dev");
private static final String EXPOSED = "X-Request-Id, X-Rate-Limit-Remaining";
@Override
public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) rq;
HttpServletResponse res = (HttpServletResponse) rs;
res.addHeader("Vary", "Origin");
String origin = req.getHeader("Origin");
boolean allowed = origin != null && ALLOWED.contains(origin);
if (allowed) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Expose-Headers", EXPOSED);
}
if ("OPTIONS".equals(req.getMethod()) && req.getHeader("Access-Control-Request-Method") != null) {
res.addHeader("Vary", "Access-Control-Request-Headers");
if (allowed) {
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Max-Age", "600");
}
// A preflight carries no cookie and no Authorization header by specification, so it
// must terminate here, ahead of any filter that would 401 an anonymous request.
res.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
chain.doFilter(req, res);
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for CORS Handling?
The JDK does ship an HTTP server, com.sun.net.httpserver, and it has no notion of CORS, so the portable seam is the Servlet API: jakarta.servlet.Filter, HttpServletResponse setHeader and addHeader, and @WebFilter, all honoured by Tomcat, Jetty and Spring Boot alike. Spring Web layers on org.springframework.web.cors.CorsConfiguration with UrlBasedCorsConfigurationSource and CorsFilter, plus the @CrossOrigin annotation for per-controller policies. The Servlet specification defines no standard CORS filter, which is why each container documents one of its own.
What is the most common Java mistake when implementing CORS Handling?
A preflight is anonymous by specification: the browser strips cookies, the Authorization header and every custom header from the OPTIONS probe. Put any security filter ahead of the CORS filter and it sees an unauthenticated request to a protected path, answers 401 or a 302 to a login page, and attaches no CORS headers, so the browser reports a CORS error for an endpoint whose actual defect is filter ordering. Spring Security's chain runs before DispatcherServlet, which is why @CrossOrigin on the controller cannot influence the preflight. Spring also rejects allowedOrigins of * with allowCredentials true, throwing at configuration time.
How does CORS Handling actually perform in Java?
The filter executes on the request thread before the container has done anything expensive, and contains on a two-element Set.of is a hash probe with no iterator allocation. What costs more than it looks is the string handling: container header structures store byte chunks and copy the values you hand them, so building Allow-Headers with concatenation per request produces garbage that a young-generation collector then has to sweep. Spring's CorsConfiguration.checkOrigin walks the configured list, so hundreds of origins is a linear scan on every response, not a hash lookup. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.