服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Springmvc ajax跨域请求处理方法实例详解

Springmvc ajax跨域请求处理方法实例详解

2021-01-19 10:48Java之家 Java教程

这篇文章主要介绍了Springmvc ajax跨域请求处理方法实例详解,需要的朋友可以参考下

上次给一个网站写网站  前后端分离 最后跪在ajax跨域上面了  自己在网上找了个方法  亲试可用  记录一下

写一个类  继承HandlerInterceptorAdapter

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class CommonInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Allow-Credentials", "true"); // 是否允许浏览器携带用户身份信息(cookie)
return true;
}
}

然后在xml里面配置一下路径

?
1
2
3
4
5
6
7
<mvc:interceptors>
<!--过滤所有请求,处理跨域请求问题 -->
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.util.CommonInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

 这样就可以了  不过有篇博客说针对简单跨域没问题。但是针对post+json请求却失败,提示跨域失败。所以下面记录一下他的解决方式

建立一个类  继承 OncePerRequestFilter

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class CrossFilter extends OncePerRequestFilter {
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
      // CORS "pre-flight" request
      response.addHeader("Access-Control-Allow-Origin", "*");
      response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
      response.addHeader("Access-Control-Allow-Headers", "Content-Type");
      response.addHeader("Access-Control-Max-Age", "1800");//30 min
    }
    filterChain.doFilter(request, response);
  }
}

web.xml里面设置一下

?
1
2
3
4
5
6
7
8
<filter>
  <filter-name>cors</filter-name>
  <filter-class>cn.***.filter.CrossFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

然后就可以了  上述方式为spring3.0版本  如果是4.0版本可以用下面方式(无测)

xml里面配置

?
1
2
3
<mvc:cors>
  <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET,POST,OPTIONS"/>
</mvc:cors>

PS:使用SpringMVC解决Ajax跨域问题

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.mengyao.system.filter;
 import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
/**
 * CORSFilter 解决跨域问题
 * @author mengyao
 *
 */
@Component
public class InitCORSFilter extends OncePerRequestFilter {
  private Logger logger = LoggerFactory.getLogger(InitCORSFilter.class);
  public InitCORSFilter() {
    logger.info("==== 初始化系统允许跨域请求 ====");
  }
  /**
   * 解决跨域:Access-Control-Allow-Origin,值为*表示服务器端允许任意Domain访问请求
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
      response.addHeader("Access-Control-Allow-Origin", "*");
      response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
      response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");
      response.addHeader("Access-Control-Max-Age", "1800");//30 min
    }
    filterChain.doFilter(request, response);
  }
}

好了,代码到此结束!

总结

以上所述是小编给大家介绍的Springmvc ajax跨域请求处理方法实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

延伸 · 阅读

精彩推荐