1.由于浏览器的同源策略,前后端分离的时候会出现跨域的问题。
java 的解决方案是:
手写一个corsFilter 实现 Filter . 然后在 doFilter 方法中定义:
笔者用的springboot ,其他架构可能配置方式有所不同
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "CorsFilter")
public class CorsFilter implements Filter {
private static Logger log = Logger.getLogger(CorsFilter.class);
@Value("${curvar}")
private String curvar;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("添加自定义注解 {}" +curvar);
System.out.print("添加自定义注解" + curvar);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
//跨域
response.setHeader("Access-Control-Allow-Origin", "*");
//跨域 Header
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
前端的调用不受影响:
--------------------------------------- JS代码开始-------------------------------------------------------------------
$("#btnButton").click(function () {
var userName=$('#userName').val();
var password=$('#password').val();
var age=$('#age').val();
var email=$('#email').val();
var userbean={userName:userName,password:password,age:age,email:email};
console.log(userbean);
//Ajax调用处理
$.ajax({
type: "POST",
contentType : "application/json ; charset=utf-8",
url:"http://127.0.0.1:8080/user/addUser",
data:JSON.stringify(userbean),
dataType: "json",
async: false,
success:function(data){
alert("..");
}
});
});
--------------------------------------- JS代码结束-------------------------------------------------------------------
唯一要注意的是 data需要 转成 json
data:JSON.stringify(userbean);