zoukankan      html  css  js  c++  java
  • 解决跨域问题的方式

    方式1.利用spring中的一个注解@CrossOrigin(推荐)

    将该注解加到controller上,如下:

    @Controller
    @CrossOrigin
    @Scope("prototype")
    @RequestMapping(value="/test")
    public class HelloWorldController {
    @RequestMapping(value="/users/{userName}", method=RequestMethod.GET)
    public @ResponseBody User findUser(@PathVariable("userName") String userName) {
    User user = new User();
    user.setUserName(userName);
    user.setSex("男");
    System.out.println(123456789);
    return user;
    }
    }

    方式2.加过滤器filter

    首先添加一个过滤器类类似下面:

    package com.ygz.filter;//所在的包
    
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    
    public class CorsFilter implements Filter {
    
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            HttpServletResponse httpServletResponse = (HttpServletResponse) arg1;
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            arg2.doFilter(arg0, httpServletResponse);
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
            // TODO Auto-generated method stub
    
        }
    
    }  

    然后在web.xml中添加filter过滤器如下即可:

        <filter>
            <filter-name>corsFilter</filter-name>
            <filter-class>spring.mvc.filter.CorsFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>corsFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
  • 相关阅读:
    Android应用签名
    Win7环境下TreeSaver编译环境的搭配
    TreeSaver 使用教程整理——Step 4: Using a Title Figure
    使用jquery获取父元素或父节点的方法
    IIS 错误代码分析手册
    敏捷开发 规范
    Asp.net中时间格式化的几种方法
    在Oracle中使用Guid
    jquery 当前时间
    JQuery一种取同级值的方式 比如你在GridView中如下
  • 原文地址:https://www.cnblogs.com/hzdzkjdxygz/p/8870330.html
Copyright © 2011-2022 走看看