Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
To enable CORS support in Spring MVC 4 - Access-Control-Allow-Origin

To enable CORS support in Spring MVC 4 - Access-Control-Allow-Origin



import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

 * Enabling CORS support  - Access-Control-Allow-Origin
 * @author
 * <code>
 	<!-- Add this to your web.xml to enable "CORS" -->
 * </code>
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 {
		response.addHeader("Access-Control-Allow-Origin", "*");
		if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
			LOG.trace("Sending Header....");
			// CORS "pre-flight" request
			response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//			response.addHeader("Access-Control-Allow-Headers", "Authorization");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
			response.addHeader("Access-Control-Max-Age", "1");
		filterChain.doFilter(request, response);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.