2、跨区没配置之前请求访问会报错
请求方式:
当前域地址:http://192.168.1.78:9080/testGit/
(index):1 Failed toload http://192.168.1.78:8800/bronzecoll/share/shareNews?id=1: No'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://192.168.1.78:9080' is therefore not allowed access.
请求服务端地址:http://192.168.1.78:8800/bronzecoll/share/shareNews?id=1
服务端配置:
Controller头部配置注解:@CrossOrigin(origins = "*", maxAge = 3600)//跨越请求配置
3、配置后请求访问
1、新建一个Filter类: Filter是一个过滤器。对你设定的请求地址进行拦截,然后设置。
package com.jgonet.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 HeaderFilter implements Filter
{
public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse response = (HttpServletResponse) resp; response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");
chain.doFilter(request, resp);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
2、在web.xml中配置:加入下面的代码。com.jgonet.filter.HeaderFilter是我类HeaderFilter的路径,你自己记得改下,放在哪个路径下就该成哪个。
HeaderFilter
com.jgonet.filter.HeaderFilter
HeaderFilter
/*
3、 ajax调用 :这里url中192.169.2.80是我电脑的ip地址,8080是我电脑的tomcat的端口号,procePlatform项目名,employee/login.do接口路径。
消息框