就在刚刚,朋友问我跨域怎么解决,正好前段时间刚做过,那我就来分享一下吧。
Httpfilter类代码:
package com.Verification.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
public class Httpfilter implements Filter {
@Override
public void destroy() {
// TODO 自动生成的方法存根
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 指定允许其他域名访问
response.setHeader("Access-Control-Allow-Origin", "*");
// 响应类型
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");
// 响应头设置
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");
if ("OPTIONS".equals(request.getMethod())){
response.setStatus(HttpStatus.SC_NO_CONTENT);
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO 自动生成的方法存根
}
}
然后:
xml添加:
<filter>
<filter-name>httpfilter</filter-name>
<filter-class>com.Verification.filter.Httpfilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
最后按ctrl然后鼠标点击xml里的com.Verification.filter.Httpfilter能进入这个页面就算成功。
有其他问题加我QQ:2751499750
希望能帮助你!