Monthly Archives: May 2016

SpringMVC Restful Service

When I tried to use SpringMVC to design a restful web service, it showed this error message: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.


After a long journey of the debug, I found that in SpringMVC, we should setup “Access-Control-Allow-Origin” to “*” in reponseHeader.

In order to do this, first in web.xml, we should set a filter:



Then, we define a CorsFilter:

public class CorsFilter extends OncePerRequestFilter {
    private static final Log LOG = LogFactory.getLog(CorsFilter.class);

    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        System.out.println("in filter");
        response.addHeader("Access-Control-Allow-Origin", "*");
        if (request.getHeader("Access-Control-Request-Method") != null
                && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
                    "GET, POST, PUT, DELETE");
                    "X-Requested-With,Origin,Content-Type, Accept");
        filterChain.doFilter(request, response);


In the controller, we not only add@RequestMapping tag, but also @ResponseBody tag to write to HTTP body:

public class RestfulController {

   public @ResponseBody List getStudentList() {
      List<String> list = new LinkedList<String>();
      return list;


In applicationContext.xml, add corsFilter bean:

<bean id="corsFilter" class="restful.filter.CorsFilter" />

Check my code on github: SpringMVCRestful