跨域支持
接下来是最关键的时候了,之前我们已经实现了一个普通的REST服务,如何支持跨域就在此一举了:)我们只需要增加一个Filter
,在HTTP响应中增加一些头信息,我们通过SimpleCORSFilter
来实现。
SimpleCORSFilter.java
package com.tianmaying.crossorigin;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
原文地址:https://www.cnblogs.com/chenhonggao/p/9164831.html
时间: 2024-11-10 16:04:35