跨域問題,源於瀏覽器的安全策略
同源策略
,它會限制一個域的文檔或是腳本與另一個域的資源交互。如我們一個域的加載的JavaScript腳本調用另一個域的接口,則出於同源策略的影響,它會阻止進行交互。
怎么算跨域
- 當 兩個url 協議、域名、端口三者之間任意一項不同即為跨域。
怎么解決跨域
HTML5中定義的一種解決資源跨域的策略Access-Control-Allow-Origin
,通過服務器返回帶這個的標識Response header
,用來解決資源的跨域權限問題。
Access-Control-Allow-Origin: * //標識任何資源都可以使用
JFinal里面設置
- 設置一個全局攔截器
import javax.servlet.http.HttpServletResponse;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
public class CrossInterceptor implements Interceptor {
@Override
public void intercept(Invocation inv) {
// TODO Auto-generated method stub
if(inv.isActionInvocation()){
Controller c = inv.getController();
HttpServletResponse response = c.getResponse();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
}
inv.invoke();
}
}
Config文件添加攔截器
public void configInterceptor(Interceptors me) {
me.add(new CrossInterceptor());
}