javaweb项目前后端分离后,解决跨域问题

一、在后台使用拦截器doFilter方法解决跨域

  1、在web.xml中添加拦截器



	Online Filter
	com.sunsheen.meteobp.web.filter.OnlineFilter


	Online Filter
	/*

2、解决跨域核心代码

// 解决跨域问题
((HttpServletResponse) resp).setHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse) resp).setContentType("application/json;charset=UTF-8");
((HttpServletResponse) resp).setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
((HttpServletResponse) resp).setHeader("Access-Control-Max-Age", "3600");
((HttpServletResponse) resp).setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
((HttpServletResponse) resp).setHeader("Access-Control-Allow-Credentials", "true"); //如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true;
((HttpServletResponse) resp).setHeader("XDomainRequestAllowed","1");

   

  3、doFilter类源码示例

package com.sunsheen.meteobp.web.filter;

import java.io.IOException;
import java.util.Date;

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 com.sunsheen.jfids.dsi.sysman.security.login.SysUser;
import com.sunsheen.jfids.system.config.Configs;
import com.sunsheen.jfids.system.security.login.Session;
import com.sunsheen.meteobp.common.redis.RedisUtils;

public class OnlineFilter implements Filter {

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		// 解决跨域问题
		((HttpServletResponse) resp).setHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) resp).setContentType("application/json;charset=UTF-8");
        ((HttpServletResponse) resp).setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        ((HttpServletResponse) resp).setHeader("Access-Control-Max-Age", "3600");
        ((HttpServletResponse) resp).setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
        ((HttpServletResponse) resp).setHeader("Access-Control-Allow-Credentials", "true"); //如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true;
        ((HttpServletResponse) resp).setHeader("XDomainRequestAllowed","1");

		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}

 

你可能感兴趣的:(java)