-
-
Save kdonald/2232095 to your computer and use it in GitHub Desktop.
package org.springframework.web.servlet.support; | |
import java.io.IOException; | |
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 { | |
@Override | |
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())); { | |
// 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-Max-Age", "1728000"); | |
} | |
filterChain.doFilter(request, response); | |
} | |
} | |
// example web.xml configuration | |
/* | |
<filter> | |
<filter-name>cors</filter-name> | |
<filter-class>org.springframework.web.servlet.support.CorsFilter</filter-class> | |
</filter> | |
<filter-mapping> | |
<filter-name>cors</filter-name> | |
<url-pattern>/*</url-pattern> | |
</filter-mapping> | |
*/ |
JIRA # for tracking Spring support: https://jira.springsource.org/browse/SPR-9278
You need to remove the semi-colon on line 18. Otherwise the if statement seems to magically always be called.
you're extending OncePerRequestFilter, but where is it?
@beneloper "import org.springframework.web.filter.OncePerRequestFilter;"
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod()));
from the above code, why did you put semi-colon at the end of the if statement? That semi-colon confused me a lot.
and why did you surrounded other codes with {}?
{
// 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-Max-Age", "1728000");
}
like this...
it looks like that codes in the {} belong to the if statement...
So much confusing code because of the "semi-colon" after the if statement's condition...
Did you do that for any purpose? or just a mistake? I still don't understand..
I think the ; after the if is a typo just as Coris instead of Cors in the name.
Simply adding this class doesn't solve the problem.
Adding a link for posterity to a supporting link from your twitter post.
Promising full-featured support: https://bitbucket.org/jsumners/corsfilter