servlet跨域請求
一,先建立一filter類去實現Servlet的Filter介面,實現三個方法
package com.wisezone.filter;
import java.io.IOException;
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.HttpServletResponse;
public class WebFliter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse resp=(HttpServletResponse) response;
resp.setHeader("Access-Control-Allow-Headers", "*");
//允許所有的方法訪問 如post , get方法
resp.setHeader("Access-Control-Allow-Method", "*");
//允許所有的域
resp.setHeader("Access-Control-Allow-Origin","*");
//放行
chain.doFilter(request, resp);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
二,在web.xml中配置如下
<!-- 跨域 -->
<filter>
<filter-name>webFliter</filter-name>
<filter-class>com.wisezone.filter.WebFliter</filter-class>
</filter>
<filter-mapping>
<filter-name>webFliter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>