Spring, REST, Ajax and CORS

Assuming you’re working on a project based on JavaScript for the client side and who makes ajax requests to a server through rest web services, you may encounter some troubles especially if both sides are on a separate domain.

Indeed, for security reasons, ajax requests from one domain A to a different domain B are not authorized.

Fortunately, the W3C introduced what is known as CORS (Cross Origin Resource Sharing) which offers the possibility for a server to have a better control of cross domain requests.

To do that, the server must add HTTP headers to the response, indicating to the client side which are the allowed origins.

Moreover, if you use custom headers, you browser will not be able to read them for security matters, so you must specify which headers to expose. So, if in your JavaScript code you can’t retrieve your custom http header value, you should read what comes next

List of headers:


Access-Control-Allow-Origin: <origin> | *

The origin parameter specifies a URI that may access the resource.  The browser must enforce this.  For requests without credentials, the server may specify “*” as a wildcard, thereby allowing any origin to access the resource.


Access-Control-Expose-Headers: X-My-Header

This header lets a server whitelist headers that browsers are allowed to access. It is very usefull when you add custom headers, because by adding them to the ” Access-Control-Expose-Headers” header you can be sure that your browser will be able to read them.


Access-Control-Max-Age: <delta-seconds>

This header indicates how long the results of a preflight request can be cached.


Access-Control-Allow-Methods: <method>[, <method>]*

Specifies the method or methods allowed when accessing the resource.  This is used in response to a preflight request.  The conditions under which a request is preflighted are discussed above.


Access-Control-Allow-Headers: <field-name>[, <field-name>]*

Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.

Now let’s see how to add this headers with Spring

First we need to create a class implementing the Filter interface:

package hello;
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;

public class CORSFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
                HttpServletRequest request= (HttpServletRequest) req;

                  response.setHeader("Access-Control-Allow-Origin", "*");
                  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                  response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
                  response.setHeader("Access-Control-Expose-Headers", "x-requested-with"); chain.doFilter(req, res);

Now, we just have to add our filter to the servlet context:

public class ServletConfigurer implements ServletContextInitializer {
    public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
       servletContext.addFilter("corsFilter", new CORSFilter());

And that’s all folks, you’re now able to make cross domain requests and use custom http headers!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Leave a Reply

− six = 3

Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: