java后端通过Filter过滤器解决跨域问题

/

2019-7-30

此方案只需服务端的代码修改

因为现在要前后端分离开发,那必不可免的会出现跨域问题,以下是自己实际测试过的有效代码:

步骤:

一、在 web.xml文件中添加

  1. <!-- 2019-07-30 解决跨域问题 -->
  2. <filter>
  3. <filter-name>crossFilter</filter-name>
  4. <filter-class>com.sx.test.controller.CorsFilter</filter-class>
  5. </filter>
  6. <filter-mapping>
  7. <filter-name>crossFilter</filter-name>
  8. <url-pattern>/*</url-pattern>
  9. </filter-mapping>

二、在自己的项目中创建 CorsFilter.java文件

  1. package com.sx.test.controller;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.core.annotation.Order;
  4. import javax.servlet.Filter;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import javax.servlet.annotation.WebFilter;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.IOException;
  13. @WebFilter(filterName = "CORSFilter", urlPatterns = {"/*"})
  14. @Order(value = 1)
  15. @Configuration
  16. public class CorsFilter implements Filter {
  17. @Override
  18. public void init(FilterConfig filterConfig) throws ServletException {
  19. }
  20. @Override
  21. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {
  22. System.out.println("Filter 过滤器 执行 了");
  23. HttpServletRequest request = (HttpServletRequest) servletRequest;
  24. HttpServletResponse response = (HttpServletResponse) servletResponse;
  25. // 响应标头指定 指定可以访问资源的URI路径
  26. response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
  27. //响应标头指定响应访问所述资源到时允许的一种或多种方法
  28. response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
  29. //设置 缓存可以生存的最大秒数
  30. response.setHeader("Access-Control-Max-Age", "3600");
  31. //设置 受支持请求标头
  32. response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
  33. // 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
  34. response.setHeader("Access-Control-Allow-Credentials","true");
  35. filterChain.doFilter(servletRequest, servletResponse);
  36. }
  37. @Override
  38. public void destroy() {
  39. }
  40. }

注:

上面代码中的注解作用:
@WebFilter 用于将一个类声明为过滤器,该注解将会在部署时被容器处理,容器将根据具体的 属性配置将相应的类部署为过滤器。@WebFilter常用属性:
@Order 注解主要用来控制配置类的加载顺序,其value为正整数,值越小优先度越高
@Configuration 从Spring3.0,@Configuration用于定义配置类

对于setHeader() 响应头相关的API 详解:

点我

Reproduced please indicate the author and the source, and error a link to this page.
text link: /origin1.html

不要让懒惰占据你的大脑,不让要妥协拖跨你的人生。青春就是一张票,能不能赶上时代的快车,你的步伐掌握在你的脚下,good luck3

Say something...

Website
Username
Email
2019/7/29上线