JavaEE从服务器端解决Ajax跨域问题

1、Ajax跨域简介

  1、指的是浏览器不能执行其他网站的脚本。是浏览器施加的安全限制。js本身不跨域,使用form表单和iframe直接请求,是不会跨域的;

  2、只要两个url的协议、域名、端口其中有一个不同,从其中一个url中使用ajax请求另一个url,则属于Ajax跨域;

  3、ajax请求接口,只是不能进入回调函数,接口还是可以正常请求的。

二、从服务器解决Ajax跨域问题

  1、只需要添加对应的响应头,通知浏览器即可,可以使用filter统一添加响应头,例如:

允许ip为192.168.182.1,可以使用ajax跨域进入回调函数(具体规则和实现可以按项目需求)

package com.moy.whymoy.test.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * [Project]:whymoy  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/14  <br/>
 * [Description]:  <br/>
 * 允许指定ip使用Ajax跨域调用
 *
 * @author YeXiangYang
 */
@WebFilter(value = "/*", initParams = {@WebInitParam(name = "origin", value = "192.168.182.1")})
public class CORSFilter implements Filter {

    private static String ALLOW_ORIGIN = "";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ALLOW_ORIGIN = filterConfig.getInitParameter("origin");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (ALLOW_ORIGIN.indexOf(servletRequest.getRemoteHost()) >= 0) {
            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,Authorization");
            response.setHeader("Access-Control-Allow-Credentials", "true");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

 

yexiangyang

moyyexy@gmail.com


 

posted @ 2018-03-14 21:51  墨阳  阅读(246)  评论(0编辑  收藏  举报