Ajax跨域问题在SpringMVC中的解决方案总结

原帖地址:http://pingguohe.net/2016/03/21/ajax-solution-spring.html

又学到了一招小技巧:关于解决跨域问题的后台解决方式,记录一下

原贴的后续讲述没有仔细研究,只是看了帖子后初步的自己定义了一个拦截器,并配置好xml的配置,很简单的操作就实现了功能。

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 CORSFilter 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 {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setHeader("Access-Control-Allow-Origin","*");
		httpResponse.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE");
		httpResponse.setHeader("Access-Control-Max-Age","3600");
		httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
		httpResponse.setHeader("","");
		httpResponse.setHeader("","");
        chain.doFilter(request, httpResponse);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
}

然后参数的引用,原来是通过jsonp实现跨域的,只支持get方法,所以参数只能从request对象中获取,改为cors跨域后,支持post方法,原来的传参就接收不到参数了,修改成通过注解@RequestBody就可以正常获取。

猜你喜欢

转载自blog.csdn.net/ZNG_XP/article/details/53160177

相关文章