美文网首页
SpringMVC 进行ajax跨域请求访问

SpringMVC 进行ajax跨域请求访问

作者: 山水风情 | 来源:发表于2017-06-02 16:57 被阅读0次

    关于 springmvc 3.x 版本对ajax跨域请求访问

    ajax 请求后,浏览器出现跨域的问题
    那么在当前环境中运行的js代码,出于安全考虑,正常情况下不能访问www.xxx.com域名下的资源。

    XMLHttpRequest cannot load http://localhost:8080/project/page/t.do. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.
    

    单个方法中访问可以直接单独进行配置

    response.setHeader("Access-Control-Allow-Origin", "*"); // * :为访问服务器地址,写了 * 表示所有的服务都允许
    

    <ol>
    <li> 通过 实现Filter接口实现全局ajax跨域请求 </li>

    
    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.apache.log4j.Logger;
    
    
    public class WebContextFilter implements Filter{
        
        private static Logger logger = Logger.getLogger(WebContextFilter.class);
        
        /**
         * 
         */
        public WebContextFilter() {
            logger.info("-------初始化ajax请求跨域------");
        }
    
        /* (non-Javadoc)
         * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
         */
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            // TODO Auto-generated method stub
        }
    
        /* (non-Javadoc)
         * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
         */
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            
            HttpServletResponse httpResponse = (HttpServletResponse) response;  
            httpResponse.setHeader("Access-Control-Allow-Origin","*");  
            httpResponse.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE");  
            httpResponse.setHeader("Access-Control-Max-Age","3600");  
            httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");  
            chain.doFilter(request, httpResponse);  
        }
    
        /* (non-Javadoc)
         * @see javax.servlet.Filter#destroy()
         */
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
        }
    }
    
     配置web.xml 文件
    <!-- ajax跨域解决 -->
        <filter>
            <filter-name>webContextFilter</filter-name>
            <filter-class>com.test.interceptor.WebContextFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>webContextFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
     
    

    <li>通过 继承 OncePerRequestFilter 实现ajax跨域请求</li>

    import java.io.IOException;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.Logger;
    import org.springframework.web.filter.OncePerRequestFilter;
     
    public class CrossFilter extends OncePerRequestFilter {
    
        private static Logger logger = Logger.getLogger(CrossFilter.class);
        
        /**
         * 
         */
        public CrossFilter() {
            logger.info("--------------------ajax跨域初始化------------------------");
        }
        
        
        /* (non-Javadoc)
         * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
         */
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                HttpServletResponse response, FilterChain filterChain)
                        throws ServletException, IOException { 
            if (request.getHeader("Access-Control-Request-Method") != null 
                    && "OPTIONS".equals(request.getMethod())) {  // 如果跨域失败 将 if 注释掉去
                // CORS "pre-flight" request
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                response.addHeader("Access-Control-Allow-Headers", "Content-Type");
                response.addHeader("Access-Control-Max-Age", "1800");//30 min
            }
            filterChain.doFilter(request, response);
        }
    
    }
    
    配置web.xml 文件
    
    <!-- ajax跨域解决 -->
        <filter>
            <filter-name>webContextFilter</filter-name>
            <filter-class>com.test.interceptor.CrossFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>webContextFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    

    <ol>
    好了 这个时候可以进行ajax请求了

    跨域访问.png

    相关文章

      网友评论

          本文标题:SpringMVC 进行ajax跨域请求访问

          本文链接:https://www.haomeiwen.com/subject/ueuufxtx.html