今天我们来学习SpringBoot框架前后端分离配置,这个主要就是配置跨域。
前后端分离简单讲就是
前端只编写页面
后端编写Controller
http://localhost:7099/selectByExample
终于学到正题了,java是一个后端语言,现在前端框架这么发达,java就干点后端的事就行了,学什么jsp,写什么前端。
我这里接口还是使用之前写好的接口,代码如下:
@RequestMapping("selectByExample")
@ResponseBody
public List<User> selectByExample()
{
// 输出日志信息
logger.info("selectByExample,info:");
logger.trace("selectByExample,trace:");
logger.debug("selectByExample,debug:");
logger.warn("selectByExample,warn:");
logger.error("selectByExample,error:");
List<User> list = userDao.selectByExample(null);
return list;
}
随意找一个地方写一个index.html文件
代码如下:
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>CAMELLIA</h2>
<h3 id="h3"></h3>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$.ajax({
url:"http://localhost:7099/selectByExample",
type:"get",
success:function(response){
console.log(response)
$("#h3").html(response);
}
});
});
</script>
我们来访问index.html,结果如下图所示:
控制台报错跨域:
Access to XMLHttpRequest at 'http://localhost:7099/selectByExample' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
那接下来,我们需要在SpringBoot中配置跨域。那我们该怎么做呢?
在javaconfig中配置,文件位置如下图所示:
代码如下所示:
package com.example.demo.demos.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class CrosConfig extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(false).maxAge(3600);
super.addCorsMappings(registry);
}
}
跨域这就配置完成了。
我们再来访问index.html,结果如下图所示:
跨域问题解决了。
至此,SpringBoot的跨域配置完成。
有好的建议,请在下方输入你的评论。