Java服务端设置CORS跨越请求,Ajax跨越请求服务器设置

  • 所谓ajax跨域就是从百度的网站ajax访问360的网站
  • 一般需要服务端设置代码即可
  • 代码:

    • web.xml
    • 
      <filter>
          <filter-name>CrossOriginControlfilter-name>
          <filter-class>com.clk.filter.CrossOriginControlfilter-class>
          <init-param>
              <param-name>IsCrossparam-name>
              <param-value>trueparam-value>
          init-param>
      filter>
      <filter-mapping>
          <filter-name>CrossOriginControlfilter-name>
          <url-pattern>/*url-pattern>
      filter-mapping>
    • java代码

    • public class CrossOriginControl implements Filter {
          private boolean isCross = false;
      
          public CrossOriginControl() {
          }
      
          public void init(FilterConfig filterConfig) throws ServletException {
              String isCrossStr = filterConfig.getInitParameter("IsCross");
              this.isCross = isCrossStr.equals("true");
          }
      
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              if (this.isCross) {
                  HttpServletResponse httpServletResponse = (HttpServletResponse)response;
                  httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
                  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);
          }
      
          public void destroy() {
          }
      } 

你可能感兴趣的:(ajax跨域)