Created
March 29, 2012 01:12
-
-
Save kdonald/2232095 to your computer and use it in GitHub Desktop.
Basic Cross Origin Resource Sharing (CORS) support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
*/ |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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..