之前做的api大多都是移动端在用,接口的调用也不会出现什么问题
但是web端调用会出现ajax跨域的请求出错的问题,之前只有个把个接口,所以用jsonp处理的(此处就不解释什么事jsonp了),这次的项目web端调用的比较多,所以就找一些其它的方法解决
首先在网上找了这么一段代码
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;
import org.springframework.stereotype.Component;
@Component
public class SimpleCORSFilter implements Filter {
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);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
这个是用的annotation加载一个过滤器,配上这个之后在请求进来的时候日志会打印过滤器加载进来了,但是测了一下,只有get请求才能跨域,而post请求还是被拒绝的。
那这个方法就不可取,换一个方法继续试
,突然在网上看见了这么一个东西
@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping("/greeting")
public @ResponseBody Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
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
@CrossOrigin(origins = "*")
@RequestMapping("/test)
@RestController
@Api(tags = "test", description = "testoperation")
public class UserController {
}
这下Controller就把ajax跨域的请求放进来了,测试了一下,ajax跨域成功!