Spring boot Ajax 跨域问题

来源:互联网 发布:js 数字转二进制 编辑:程序博客网 时间:2024/06/03 07:53
之前做的api大多都是移动端在用,接口的调用也不会出现什么问题
但是web端调用会出现ajax跨域的请求出错的问题,之前只有个把个接口,所以用jsonp处理的(此处就不解释什么事jsonp了),这次的项目web端调用的比较多,所以就找一些其它的方法解决
首先在网上找了这么一段代码
  1. import java.io.IOException;
  2. import javax.servlet.Filter;
  3. import javax.servlet.FilterChain;
  4. import javax.servlet.FilterConfig;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.ServletRequest;
  7. import javax.servlet.ServletResponse;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.springframework.stereotype.Component;
  10. @Component
  11. public class SimpleCORSFilter implements Filter {
  12. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  13. HttpServletResponse response = (HttpServletResponse) res;
  14. response.setHeader("Access-Control-Allow-Origin", "*");
  15. response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
  16. response.setHeader("Access-Control-Max-Age", "3600");
  17. response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
  18. chain.doFilter(req, res);
  19. }
  20. public void init(FilterConfig filterConfig) {}
  21. public void destroy() {}
  22. }
这个是用的annotation加载一个过滤器,配上这个之后在请求进来的时候日志会打印过滤器加载进来了,但是测了一下,只有get请求才能跨域,而post请求还是被拒绝的。
那这个方法就不可取,换一个方法继续试,突然在网上看见了这么一个东西


  1. @CrossOrigin(origins = "http://localhost:9000")
  2. @RequestMapping("/greeting")
  3. public @ResponseBody Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
  4. System.out.println("==== in greeting ====");
  5. return new Greeting(counter.incrementAndGet(), String.format(template, name));
  6. }

This @CrossOrigin annotation enables cross-origin requests only for this specific method. By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMappingannotation and a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the annotation attributes: originsmethodsallowedHeaders,exposedHeadersallowCredentials or maxAge. In this example, we only allowhttp://localhost:8080 to send cross-origin requests.

我这一下子就开心了,以前从没关注过的 @CrossOrigin Annotation瞬间就让我看见了解决的希望。
它不是把ajax请求拒绝了么,查了一下资料,如果不写默认是不允许跨域了。那现在好我直接在 @RestController 的前面加一个Annotation
  1. @CrossOrigin(origins = "*")
  2. @RequestMapping("/test)
  3. @RestController
  4. @Api(tags = "test", description = "testoperation")
  5. public class UserController {
  6. }
这下Controller就把ajax跨域的请求放进来了,测试了一下,ajax跨域成功!


0 0
原创粉丝点击