前端ajax访问后端:(主要关注url路径)
<script type="text/javascript">
$(function(){
$.ajax({
cache: false,
async: false,
type: "GET",
dataType: "json",
//data: {method: "validateAjaxname", username: username},
url: "http://localhost:8080/getdata",
success: function(data) {
var html;
for( var i = 0; i < data.length; i++ ) {
html += "<tr>";
html += "<td>" + data[i].name + "</td>"
html += "<td>" + data[i].url + "</td>"
html += "<td>" + data[i].type + "</td>"
html += "</tr>";
}
$("#J_TbData").html(html);
}
});
});
</script>
前端页面访问不到后端数据,跨域问题报错如下:
解决办法:
https://www.cnblogs.com/zishu/p/10727230.html
过滤器
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CrosFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
//*号表示对所有请求都允许跨域访问
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "*");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
@SpringBootApplication
@MapperScan("com.mybatisplus.springboot")
public class MybatisPlusSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusSpringbootApplication.class, args);
}
/**
* 配置跨域访问的过滤器
* @return
*/
@Bean
public FilterRegistrationBean registerFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.addUrlPatterns("/*");
bean.setFilter(new CrosFilter());
return bean;
}
}