Spring boot Ajax 跨域问题

之前做的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  @RequestMapping annotation and a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the annotation attributes:  origins methods allowedHeaders , exposedHeaders allowCredentials  or  maxAge . In this example, we only allow http://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跨域成功!


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值