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.

SpringRestfulErrMsg

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:

<filter>
   <filter-name>cors</filter-name>
   <filter-class>restful.filter.CorsFilter</filter-class>
</filter>

<filter-mapping>
   <filter-name>cors</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

Then, we define a CorsFilter:

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

    @Override
    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
            response.addHeader("Access-Control-Allow-Methods",
                    "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers",
                    "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:

@Controller
public class RestfulController {

   @RequestMapping("getList")
   public @ResponseBody List getStudentList() {
      List<String> list = new LinkedList<String>();
      list.add("1");
      list.add("2");
      list.add("3");
      return list;
   }

}

In applicationContext.xml, add corsFilter bean:

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

Check my code on github: SpringMVCRestful