解决spring mvc跨域的问题

java开发网站是很繁琐的事情,特别是写前端,每次运行都需要进行编译,所以需要配置跨域访问:

服务端

首先要创建一个CrossDomainFilter类,类继承了Servlet Filter接口,如下代码:

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by alan.luo on 2017/9/5.
 */
public class CrossDomainFilter extends Compact implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            // 跨域
            String origin = httpRequest.getHeader("Origin");
            if (origin == null) {
                httpResponse.addHeader("Access-Control-Allow-Origin", "http://localhost/");

            } else {
                httpResponse.addHeader("Access-Control-Allow-Origin", origin);
            }
            httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, Content-Type, Accept,X-Cookie");
            httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
            if ( httpRequest.getMethod().equals("OPTIONS") ) {
                httpResponse.setStatus(HttpServletResponse.SC_OK);
                return;
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {
    }
}

类方法主要是配置response的响应信息,告诉客户端,可以传递什么及使用什么方法过来。

接下来就是配置xml文件,打开web.xml文件,在过滤代码中加入以下代码:

<!-- 允许跨域 -->
<filter>
    <filter-name>CrossDomainFilter</filter-name>
    <filter-class>com.test.com.CrossDomainFilter</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CrossDomainFilter</filter-name>
    <url-pattern>/*</url-pattern><!-- 配置允许跨域访问的的url-pattern -->
</filter-mapping>

到这里服务器就已经配置完毕了。

客户端

客户端直接使用ajax发起请求就可以:

  /**
   * 发起ajax请求
   * @param url 请求地址
   * @param data 请求参数(object)对象
   * @param fnScuss 成功回调的函数
   * @param fnError 失败回调的函数
   * @returns {{get: get, post: post}}
   */
  ajax: function (url, data, fnScuss, fnError) {
      
      var _cacheKey = app.md5(url+JSON.stringify(data));
      var _cache = null;
      var _isCanCache = app.isCanCache(url);
      url = this.constant.DOMAIN + url;

      var http = function (method,header) {
          if (method == null){
              method = "POST";
          }
          if(header == null){
              header = new Object();
          }
     
          $.ajax({
              url: url,
              data: data,
              dataType: "json",
              type: method,
              headers: header,
      beforeSend: function(xhr) {
         xhr.withCredentials = true;
      },
      crossDomain:true,
              success: function (e) {

                  if (typeof fnScuss == "function") {
                      //储存缓存
                      if (e.code == "1" && _isCanCache == true){
                          //app.cache.set(_cacheKey,e)
                      }
                      fnScuss(e);
                  }
              },
              error: function (e) {
                  if (typeof fnError == "function") {
                      fnError(e);
                  }
              }

          })
      };

      return {
          get: function () {
              //缓存判断
              if (_isCanCache == true){
                  _cache = app.cache.get(_cacheKey)
                  if (_cache != null && typeof fnScuss == "function"){
                      fnScuss(_cache);
                      return true;
                  }
              }

              http("GET");
          },
          post: function (isJson) {
              //缓存判断
              if (_isCanCache == true){
                  _cache = app.cache.get(_cacheKey)
                  if (_cache != null && typeof fnScuss == "function"){
                      fnScuss(_cache);
                      return true;
                  }
              }
              var header = new Object();
              if (isJson == true){
                  header['Content-Type'] = "application/json";
              }
              http("POST",header);
          },
          delete:function () {
              http("DELETE");
          },
          put:function () {
              http("PUT");
          }
      }

  },

 

app.event("#getToken", "click", function () {
    app.ajax("/project/api/getToken", {type:"1"}, function (e) {
        app.log(e);
        if (e.code == 1) {
            
        }
    }).post();
});

Leave a Comment