当前位置: 主页 > JAVA语言

java如何解决跨域问题-前端怎么解决跨域问题

发布时间:2023-04-17 10:11   浏览次数:次   作者:佚名

一、全部接口解决跨域问题

要想解决测试人员的跨域问题,在请求访问前解决跨域问题

java 解决跨域访问_java如何解决跨域问题_前端怎么解决跨域问题


public class SimpleCORSFilter implements Filter{  
    @Override  
    public void destroy() {  
    }  
    @Override  
    public void doFilter(ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
            HttpServletResponse response = (HttpServletResponse) res;  
            response.setHeader("Access-Control-Allow-Origin", "*");  
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
            response.setHeader("Access-Control-Max-Age", "3600");  
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");  
            chain.doFilter(req, res);  
    }  
    @Override  
    public void init(FilterConfig arg0) throws ServletException {  
    }  
} 

java 解决跨域访问_java如何解决跨域问题_前端怎么解决跨域问题

@Component
public class CORSInterceptor extends HandlerInterceptorAdapter {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //添加跨域CORS
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
      response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
      return true;
  }
}

java如何解决跨域问题_前端怎么解决跨域问题_java 解决跨域访问

单个接口解决跨越问题

java如何解决跨域问题_java 解决跨域访问_前端怎么解决跨域问题

在接口的代码中添加下面这端代码

java如何解决跨域问题_前端怎么解决跨域问题_java 解决跨域访问

 response.addHeader("Access-Control-Allow-Origin", "*");
          response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
          response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
          response.addHeader("Access-Control-Max-Age", "1800");//30 min

改变接口方法解决跨越问题

简单的说,就是把post方法的接口java如何解决跨域问题,变成get方法,也可以有效的解决跨域的问题。但是这种方法不建议用java如何解决跨域问题,毕竟它改变了方法的性质。