1.第一种方式:创建一个CorsConfig类用于解决跨域问题
由于springboot项目没有web.xml这个配置文件,所有我们使用servlet3.0支持注解配置,用于代替xml文件,所以一定要在这个类上加上注解:@WebFilter(urlPatterns = "/*",filterName = "CorsConfig")
package com.ck.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(urlPatterns = "/*",filterName = "CorsConfig")
public class CorsConfig implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
System.out.println("request.getMethod():" + request.getMethod());
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
然后在springboot启动类上加@ServletComponentScan开启扫描servlet注解,这样springboot项目就能识别到这个过滤器,面向全局的
2.第二种方式:使用@CrossOrigin注解
这个注解是局部的,加在controller层类上或者具体方法上
只支持整个类的跨域访问
@RestController
@CrossOrigin
public class TestController {
……
……
}
只支持某个方法跨域访问
@RequestMapping("/index")
@CrossOrigin
public String testMethod(...){
……
……
}
——————————跳转JSR303——数据校验&统一响应数据格式————————————