纯html跨域访问java接口

来源:互联网 发布:安智市场软件 编辑:程序博客网 时间:2024/06/05 02:05

跨域是什么?

跨域的意思就是html访问地址和接口地址在不同的域中,只要满足域名、协议、端口中有一个不同就代表跨域了。

为什么不能跨域?

因为安全问题,比如用户访问了银行网站,这时用户信息都在浏览器的cookie中,然后他又心血来潮访问了一些羞羞哒的网站,该网站就可以拿到cookie,里面存在各种隐私信息,如果银行的网站支持跨域,那么一些心怀不轨的人就可以用户信息进行一些不好的操作了。

但是有些时候需求需要跨域,但是现在的http请求头默认禁止跨域访问,那么就需要进行一些配置

方法一(接口配置filter过滤):

    <!--json跨域配置-->    <filter>        <filter-name>cors</filter-name>        <filter-class>com.base.filter.SimpleCORSFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>cors</filter-name>        <url-pattern>*.do</url-pattern>    </filter-mapping>

对应java类

/****<p>功能描述:跨域资源共享过滤器</p>*<ul>*<li>@param </li>*<li>@return </li>*<li>@throws </li>*<li>@author jackson</li>*<li>@date 17-9-28 上午11:19</li>*</ul>*/public class SimpleCORSFilter implements Filter {    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {        HttpServletResponse response = (HttpServletResponse) res;        response.setHeader("Access-Control-Allow-Origin", "*");        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");        response.setHeader("Access-Control-Max-Age", "3600");        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");        chain.doFilter(req, res);    }    public void init(FilterConfig filterConfig) {}    public void destroy() {}}