Java请求Cross跨域配置及Nginx反向代理配置

1.CrossJava跨域配置

首先给出Java的跨域请求cross配置(简单控制版)

import java.io.IOException;
import java.util.Enumeration;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Cross-Origin Resource Sharing跨源资源共享 过滤器 允许前台页面通过ajax或者angualr直接访问
 *
 */
@Component
@Slf4j
public class CorsFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CorsFilter.class);
    
    @Value("${page.home}")
    private String pageHome;
    
    @Override
    public void init(FilterConfig filterConfig)
        throws ServletException {
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)res;
        HttpServletRequest request = (HttpServletRequest) req;
        Enumeration<String> headerNames = ((HttpServletRequest) req).getHeaderNames();
        while (headerNames.hasMoreElements()){
            String s = headerNames.nextElement();
            log.info("请求key:{},请求值:{}",s,((HttpServletRequest) req).getHeader(s));
        }

        // 允许的访问域,允许全部则为*,允许部分则配置详细的http地址,端口后不能有/
        response.setHeader("Access-Control-Allow-Origin", "*");
        
        // 访问授权有效期 为一周,单位为秒
        response.setHeader("Access-Control-Max-Age", "604800");
        
        // 默认只允许GET、POST请求,需要将PUT和DELETE也加入此列
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,PUT,DELETE");
        
        // 允许自定义 header accessToken
        response.setHeader("Access-Control-Allow-Headers",
            "Authorization,Origin, Accept, Content-Type, X-HTTP-Method, X-HTTP-METHOD-OVERRIDE,XRequestedWith,X-Requested-With,xhr,custom-enterpriseId,x-clientappversion, x-wxopenid, x-devicetype,accessToken");
        
        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        chain.doFilter(req, res);
        
        LOGGER.info("do filter");
    }
    
    @Override
    public void destroy() {
    }
    
}

 

跨域域名限制版  pagehome用逗号隔开

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Cross-Origin Resource Sharing跨源资源共享 过滤器 允许前台页面通过ajax或者angualr直接访问
 *
 */
@Component
public class CorsFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CorsFilter.class);
    
    public static final String HOST_SPLIT_LINE = ",";
    
    public static final String ALLOW_HEADER_SPLIT_LINE = "\\|";
    
    
    @Value("${page.home}")
    private String pageHome;
    
    @Override
    public void init(FilterConfig filterConfig)
        throws ServletException {
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)res;
        HttpServletRequest request = (HttpServletRequest)req;
        List<String> domains = Arrays.asList(pageHome.split(HOST_SPLIT_LINE));
        // 获取发起当前请求的域名
        String originHead = request.getHeader("Origin");
        int index = index(domains, originHead);
        if (index >= 0) {
            String matchHeader = domains.get(index);
            if (matchHeader.split(ALLOW_HEADER_SPLIT_LINE).length > 1) {
                String [] headerConfig = matchHeader.split(ALLOW_HEADER_SPLIT_LINE);
                // 允许的访问域,允许全部则为*,允许部分则配置详细的http地址,端口后不能有/
                response.setHeader("Access-Control-Allow-Origin", headerConfig[1]);
            } else {
                response.setHeader("Access-Control-Allow-Origin", originHead);
            }
            
        } else {
            response.setHeader("Access-Control-Allow-Origin", domains.get(0));
        }
        
        // 访问授权有效期 为一周,单位为秒
        response.setHeader("Access-Control-Max-Age", "604800");
        
        // 默认只允许GET、POST请求,需要将PUT和DELETE也加入此列
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,PUT,DELETE");
        
        // 允许自定义 header accessToken
        response.setHeader("Access-Control-Allow-Headers",
            "Authorization,Origin, Accept, Content-Type, X-HTTP-Method, X-HTTP-METHOD-OVERRIDE,XRequestedWith,X-Requested-With,xhr,custom-enterpriseId,x-clientappversion, x-wxopenid, x-devicetype,accessToken");
        
        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        chain.doFilter(req, res);
        
        LOGGER.debug("do filter");
    }
    
    @Override
    public void destroy() {
    }
    
    
    /**
     * 计算Header所在索引位置
     * @param domains 域名列表
     * @param originHeader 当前页面域名
     * @return
     * @return int  返回类型 
     * @author caiwenhao
     * @date 2020年6月30日 上午11:53:31
     */
    private int index(List<String> domains, String curDomain) {
        String domain = null; 
        for (int i = 0; i < domains.size(); i++) {
            domain = domains.get(i);
            String strs [] = domain.split(ALLOW_HEADER_SPLIT_LINE);
            if ((null != strs) && (strs[0].equals(curDomain))) {
                return i;
            }
            
            if (domain.equals(curDomain)) {
                return i;
            }
        }
        
        return -1;
    }
}

  

1.1 几个注意点

  • .response.setHeader("Access-Control-Allow-Origin", "*");   *可换成具体的域名做精确控制,使用*代表的跨域范围很大

  • .Access-Control-Allow-Headers的参数注意自行检查,如果需要自定义header中的验证token字段必须加上accessToken,否则跨域会失败

 

2.Nginx反向代理配置

2.1.首先按正常安装安装nginx

2.2.进入/etc/nginx 配置目录,自行安装的进入自己的配置目录

2.3 nginx.cong默认导入conf.d下的所有文件

所以我们可将项目的配置放在conf.d下也可自行配置目录

首先我们给出web端的资源映射路径,以及其他gzip配置  不需要的可去除

server 
{
	#开启和关闭gzip模式
        gzip on;
        
        #gizp压缩起点,文件大于1k才进行压缩
        gzip_min_length 1k;
        
        # gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间
        gzip_comp_level 6;
        
        # 进行压缩的文件类型。
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/xml text/javascript application/json image/png image/gif image/jpeg;
        
        #nginx对于静态文件的处理模块,开启后会寻找以.gz结尾的文件,直接返回,不会占用cpu进行压缩,如果找不到则不进行压缩
        # gzip_static on|off
        
        # 是否在http header中添加Vary: Accept-Encoding,建议开启
        gzip_vary on;

        # 设置压缩所需要的缓冲区大小,以4k为单位,如果文件为7k则申请2*4k的缓冲区 
        gzip_buffers 4 16k;

        # 设置gzip压缩针对的HTTP协议版本
        # gzip_http_version 1.1;
	listen       80;
	server_name  manager.XXX.com;
	location / {
         # web打包资源路径 root /service/app/XXX/frontEnd/mgmt; try_files $uri $uri/ /index.html?q=$uri&$args; index index.html index.htm; } }

 其次我们给出后端appService的接口映射配置,一般将域名也就是ip的80端口映射到我们项目的ip及项目端口(比如我的项目就是部署在本地的4000端口  )

/ 路径一般配置项目需要的资源路径,如无也可直接配置反向代理

server 
{
	listen       80;
	server_name  api.XXXX.com;

	location / {
		root  /service/app/hunger_server/master;
		try_files $uri $uri/ /index.html?q=$uri&$args;
		index  index.html index.htm;
	}

	location /hunger {
	   proxy_pass  http://127.0.0.1:4000;
	   client_max_body_size 100m;
	   proxy_buffer_size  512k;
	   proxy_buffers   32 32k;
	   proxy_busy_buffers_size 512k;

	   proxy_set_header  Host        $host;
	   proxy_set_header  X-Real-IP   $remote_addr;
	   proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
	   proxy_set_header  Accept-Encoding "";
   	}
		
   
}

  

 

posted @ 2020-08-10 10:00  胡小华  阅读(600)  评论(0编辑  收藏  举报