Mình có 1 đoạn code Spring, nhưng mình không hiểu ý nghĩa của đoạn code này. Bạn nào giải thích giùm mình với(Theo từng dòng thì càng tốt):
@Component
// We want to put this in front of SpringSessionFilter
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-auth-token");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
if(!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Pre-fight");
response.setHeader("Access-Control-Allowed-Methods", "POST, GET, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, x-auth-token, " +
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
response.setStatus(HttpServletResponse.SC_OK);
}
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
Và đây là giải thích cho đoạn code trên:
So when Angular 2 send an http post ajax call, it will first send a pre-flight and method type is not “POST” but “OPTIONS”. If this preflight has a valid response, then it will start to send the real http post. This is to prevent cross site attack. At backend, spring doesn’t have a out-of-box handling for this. So we need to check whether the http method is a preflight or not. If it is, we will just respond with valid headers and info. If not, we’ll just proceed the filter chain.