Search This Blog

Friday, June 8, 2012

Enable CORS support in REST services with Spring 3.1

We are working on a web project, which has 2 components, UI and web services.  These 2 components are deployed to 2 different servers.  UI uses jQuery to make ajax call  to back end restful web services. Back end web services use Spring 3.1 MVC framework.  We are facing the XSS (cross site scripting) issue since modern browsers don't allow XSS.

The back end rest web services support HTTP methods GET, POST, PUT and DELETE.  The first problem we solved was how to call HTTP method GET from UI using jQuery.  Since I used JSONP before, it is a natural solution to me to use JSONP again.  My coworker already blog the solution here:

However,  JSONP only supports GET, and you can't set http headers with JSONP request.  I also realized that JSONP is kind of out-of-dated too.  So how to support other methods like PUT, POST? 

CORS, Cross-Origin Resource Sharing, defines a mechanism to enable client-side cross-origin requests.  CORS are widely supported by modern browsers like FireFox, Chrome, Safari, and IE.

The UI code is fairly simple:
<script type="text/javascript" src="jquery.js"></script>
<script type="application/javascript">      
(function($) {
    var url = 'http://localhost:8080/employee/id';
        type: 'put',
        url: url,
        async: true,
    contentType: 'application/json',
        data: '{"id": 1, "name": "John Doe"}',
        success: function(response) {
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status + " Message = " + xhr.statusText);
    <!-- we will add our HTML content here -->
If you just run the above javascript and call the backend, you may notice that the PUT request is changed to OPTIONS.  The browser sends an OPTIONS request to the server, and the server needs to send response with correct headers.  So in order to return the correct response, a filter is created (thanks to the link
package com.zhentao;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter {

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
        filterChain.doFilter(request, response);
 The web.xml needs adding the following too:

However, this isn't enough yet.  The original post didn't address it.  You still need to change your rest web services to return Accept-Controll-Allow-Origin header since HTTP is stateless.  Here is what I did with Spring Rest api:
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.PUT, consumes = {"application/json"})
    public ResponseEntity<Employee> create(@Valid @RequestBody Employee employee, @PathVariable String id) 
            employee.setId(id);//some logic here
            HttpHeaders headers = new HttpHeaders();
            headers.add("Access-Control-Allow-Origin", "*");
            ResponseEntity<Employee> entity = new ResponseEntity<Employee>(headers, HttpStatus.CREATED);
            return entity;
Update: it seems my post caused some confusion, and I created another post and fully working examples for CORS. See here.


  1. This comment has been removed by the author.

  2. hey, don't know if you'd see this, but I am having trouble to get sending as json type working as your example. Also the CORSfilter is never hit. Could you give any more tip on how the CORSfilter works?

    1. See the url pattern for CORS filter. It is /*. So, for every request, the cors filter is called (which checks if the request is of type OPTIONS and adds appropriate headers). The filter then returns the response to the browser.The browser can now make the actual POST/PUT call to the server and this time you wont get cross domain error because the filter added the required headers to the response previously

  3. Why do you say I have to change my REST API code if I define the new headers using the Filter? The filter already adds the COSR headers to the response. If the filter doesn't do it what is it doing there? Just wondering... because I've seen several posts about this subject and yours is the only one that requires changing code. However I haven't tested any of those solutions (just researching, for now).

  4. filter is adding headers for OPTION request (requests with method option), but not for POST and GET.
    However you can add to filter handling of GET, POST and also as well

  5. Great tips.

    Just a remark. The Cors doesnt' works without add in the filter :

    response.addHeader("Access-Control-Allow-Headers", "Content-Type, x-http-method-override");

    Without the header x-http-method-override, the GET resquest wasn't sent after the OPTION request.

  6. You could always change it to

    response.addHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

  7. Nice post, we took a slightly different approach rather than creating an implementation as above. Thought it would be worth a mention:

  8. Thank you for this post, I learned a lot about CORS + Spring here. Although I used the suggestion by Jim Gough above. :)

  9. Same issue I have faced,but front end is EXT.js in my situation.
    I have achieved this issue by adding
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type"); in header.

    Thx This concept is really useful.

  10. I am facing same problem, I am using spring javaconfig anotations, AbstractAnnotationConfigDispatcherServletInitializer instead of web.xml.

    Could anyone provide me reinvent code.

  11. The fact that the company I'm working with has forced me to use a blog post from 6 years ago and hasn't been bumped in 3 years makes me sad.

    Thank you for make this available.