zoukankan      html  css  js  c++  java
  • java解决前后台跨域问题

    这篇文章主要介绍了使用Cors实现JavaWeb跨域请求问题的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

    之前用jsonp 解决跨域问题,现在用CORS实现跨域请求解决java 跨域问题:

    主要代码如下

    package com.hy.fliter;

    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;

    import org.apache.commons.httpclient.HttpStatus;

    /**

    * Created by WangShuai on 2016/7/30.

    */

    public class CorsFilter implements Filter {

    @Override

    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletResponse response = (HttpServletResponse) servletResponse;

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    // 指定允许其他域名访问

    response.setHeader("Access-Control-Allow-Origin", "*");

    // 响应类型

    response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");

    // 响应头设置

    response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");

    if ("OPTIONS".equals(request.getMethod())){

    response.setStatus(HttpStatus.SC_NO_CONTENT);

    }

    filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override

    public void destroy() { }

    }

    web.xml 代码如下配置

    <filter>

    <filter-name>cors</filter-name>

    <filter-class>com.hy.fliter.CorsFilter</filter-class>

    </filter>

    <filter-mapping>

    <filter-name>cors</filter-name>

    <url-pattern>/*</url-pattern>

    </filter-mapping>

  • 相关阅读:
    介绍Shiro Annotation及Shiro标签的用法
    SpringMVC+Apache Shiro+JPA(hibernate)案例教学(四)基于Shiro验证用户权限,且给用户授权
    SpringMVC+Apache Shiro+JPA(hibernate)案例教学(一)整合配置
    Spring MVC之@RequestMapping 详解
    vimrc
    sk_buff深度解析
    ieee80211ax简介
    新基地
    dos格式迭代转为unix
    ath10k MAC地址
  • 原文地址:https://www.cnblogs.com/lc93/p/7879127.html
Copyright © 2011-2022 走看看