java中的跨域问题
参考网址:
1.springboot项目中,提供了跨域的注解
@CrossOrigin注解的方法,只能作用在一个Controller层
直接在Controller类或方法前加上@CrossOrigin注解即可允许所有ip跨域访问
加在Controller类上表示该Controller的所有方法都支持跨域
加在Controller中的方法上表示仅该方法支持跨域
2.ssm中跨域的解决方案
我是用的是第四种方案,这样耦合性比较低,易于修改
添加一个过滤器的配置类
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;
public class CrossingFilter implements Filter {
private boolean isCross = false;
@Override
public void destroy() {
isCross = false;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (isCross) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
System.out.println("拦截请求: " + httpServletRequest.getServletPath());
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
// httpServletResponse.setHeader("Access-Control-Allow-Methods", "*"); // 表示所有请求都有效
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "0");
httpServletResponse.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,userId,token");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("XDomainRequestAllowed", "1");
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String isCrossStr = filterConfig.getInitParameter("IsCross");
isCross = isCrossStr.equals("true") ? true : false;
System.out.println("跨域开启状态:" + isCrossStr);
}
}
代码直接粘贴复制即可
在web.xml文件中注册CrossingFilter过滤器
<!-- 配置跨域过滤器 -->
<filter>
<filter-name>CrossingFilter</filter-name>
<filter-class>com.pmsapi.filter.CrossingFilter</filter-class>
<init-param>
<param-name>IsCross</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CrossingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
说明:
filter-class是CrossingFilter的全类名,这边需要修改一下
其余直接粘贴复制,亲测有效