1.过滤器代码如下:
package com.mvc.imp;
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;
/**
* 跨域过滤器
* @author suyunlong
*
*/
public class CorsFilter implements Filter
{
private String allowOrigin;
private String allowMethods;
private String allowCredentials;
private String allowHeaders;
private String exposeHeaders;
public void init(FilterConfig filterConfig) throws ServletException
{
allowOrigin=filterConfig.getInitParameter("allowOrigin");
allowMethods=filterConfig.getInitParameter("allowMethods");
allowCredentials=filterConfig.getInitParameter("allowCredentials");
allowHeaders=filterConfig.getInitParameter("allowHeaders");
exposeHeaders=filterConfig.getInitParameter("exposeHeaders");
}
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)
throws IOException,ServletException
{
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)res;
if(!allowOrigin.equals(""))
{
List<String> allowOriginList=Arrays.asList(allowOrigin.split(","));
if(allowOriginList!=null)
{
String currentOrigin=request.getHeader("Origin");
if(allowOriginList.contains(currentOrigin))
{
response.setHeader("Access-Control-Allow-Origin",currentOrigin);
}
}
}
if(!allowMethods.equals(""))
{
response.setHeader("Access-Control-Allow-Methods",allowMethods);
}
if(!allowCredentials.equals(""))
{
response.setHeader("Access-Control-Allow-Credentials",allowCredentials);
}
if(!allowHeaders.equals(""))
{
response.setHeader("Access-Control-Allow-Headers",allowHeaders);
}
if(!exposeHeaders.equals(""))
{
response.setHeader("Access-Control-Expose-Headers",exposeHeaders);
}
chain.doFilter(req,res);
}
public void destroy()
{
}
}
2.web.xml配置如下:
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.mvc.imp.CorsFilter</filter-class>
<init-param>
<param-name>allowOrigin</param-name>
<param-value>http://localhost:8080,http://127.0.0.1:8080</param-value>
</init-param>
<init-param>
<param-name>allowMethods</param-name>
<param-value>GET,POST,PUT,DELETE,OPTIONS</param-value>
</init-param>
<init-param>
<param-name>allowCredentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>allowHeaders</param-name>
<param-value>Content-Type</param-value>
</init-param>
<init-param>
<param-name>exposeHeaders</param-name>
<param-value>Content-Type</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>