最近在做一个项目,前端资源与服务端单独部署。遇到一个跨域问题,常见的跨域问题可以通过jsonp方式解决。下面介绍另一种解决方式:
服务端环境:spring + dubbo + tomcat
第一步:在WEB-INF目录下添加一个crossdomain.xml文件,内容如下:
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
表示web服务器允许任何domain的请求。
第二步:
在web.xml中添加一个新的过滤器Filter–crossDomainFilter。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Archetype CreatedWeb Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-main.xml</param-value>
</context-param>
<context-param>
<param-name>timeoutMinutes</param-name>
<param-value>120</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>crossDomainFilter</filter-name>
<filter-class>com.*.resource.web.utils.CrossDomainFilter</filter-class>
<init-param>
<param-name>file</param-name>
<param-value>/WEB-INF/web-config.properties</param-value>
</init-param>
</filter>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter-mapping>
<filter-name>crossDomainFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
crossDomainFilter中增加crossDomain方法:
package com.*.resource.web.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
*
* @author
* @date
*/
public class CrossDomainFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(CrossDomainFilter.class);
private Properties pp = new Properties();
private FilterConfig config;
private String allowDomain = "http://allow.com";
@Override
public void destroy() {
pp = null;
this.config = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 得到请求的uri和url
String reqUri = req.getRequestURI();
String reqUrl = req.getRequestURL().toString();
log.info(" reqUri:{} ,reqUrl:{} ", reqUri, reqUrl);
// 跨域处理
this.crossDomain(req, resp, reqUrl);
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig config) throws ServletException {
}
/**
* 处理跨域问题
*/
private void crossDomain(HttpServletRequest request, HttpServletResponse response, String url) {
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Credentials", "true");
log.info("REFERER:{}", request.getHeader("REFERER"));
String referer = request.getHeader("REFERER");
String reqRefererDomain = "";
if (referer != null && referer.length() > referer.indexOf(".com") + 4) {
reqRefererDomain = referer.substring(0, referer.indexOf(".com") + 4);
log.info("reqRefererDomain:{}", reqRefererDomain);
if (reqRefererDomain.equals(allowDomain)) {
response.setHeader("Access-Control-Allow-Origin", allowDomain );
}
}
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.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");
}
}
解决跨域的关键:
response.setHeader("Access-Control-Allow-Origin", allowDomain );