java中的跨域问题

java中的跨域问题

参考网址:

参照csdn博客

1.springboot项目中,提供了跨域的注解

@CrossOrigin注解的方法,只能作用在一个Controller层

直接在Controller类或方法前加上@CrossOrigin注解即可允许所有ip跨域访问

加在Controller类上表示该Controller的所有方法都支持跨域

加在Controller中的方法上表示仅该方法支持跨域

2.ssm中跨域的解决方案

参照csdn博客

我是用的是第四种方案,这样耦合性比较低,易于修改

添加一个过滤器的配置类

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的全类名,这边需要修改一下

其余直接粘贴复制,亲测有效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值