• ajax跨域问题及解决


    overview

    ajax是一种创建交互式网页应用的网页开发技术,是一种用于创建快速动态网页的技术,通过在后台与服务器进行少量数据交换。而ajax的跨域问题则是请求了其他项目的接口地址,当协议、子域名、主域名、端口号中任意一个不一样的时候,都算不同的域。不同域之间的相互请求,就叫跨域

    基于安全的考虑,ajax只能访问本地的资源,而不能跨域访问,常出现跨域访问的几种情况:

    实现:

    处理ajax跨域的问题主要从ajax本身和服务器端去考虑,这里主要介绍服务器端应该怎样去解决,ajax本身的话可以考虑JSONP技术。

    为了不出现跨域的问题,我们应该在服务器端往响应头里添加Access-Control-Allow-Origin

    response.addHeader("Access-Control-Allow-Origin", "*");

    而在实际的项目当中的话,我们应该考虑配置一个拦截器

    <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**" />
                <bean class="com.whcd.app.interceptor.CCInterceptor"/>
            </mvc:interceptor>
    </mvc:interceptors>

    然后再写一个类去继承HandlerInterceptorAdapter ,

    package com.whcd.app.interceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    public class CCInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
                throws Exception {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
                throws Exception {
    
        }
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
            // TODO Auto-generated method stub
            response.addHeader("Access-Control-Allow-Origin", "*");
            return true;
    
        }
    
    }





  • 相关阅读:
    【leetcode】496. Next Greater Element I
    工具网站
    [err]Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in <module> from pip._internal import main ImportError: No module named 'pip._internal'
    []TLD code run
    【动手学深度学习】
    【论文阅读】Wing Loss for Robust Facial Landmark Localisation with Convolutional Neural Networks
    【linux基础】ubuntu系统NVIDIA驱动安装
    【linux基础】linux不能进入系统
    【leetcode】492. Construct the Rectangle
    【leetcode】485. Max Consecutive Ones
  • 原文地址:https://www.cnblogs.com/asen0713/p/6481401.html
Copyright © 2020-2023  润新知