springboot跨域問題解決方案
這篇文章主要介紹了springboot跨域問題解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
springboot中的跨域問題,如果不注意的話,容易造成錯誤,本次springboot版本為2.13
前端錯誤信息:
Access to XMLHttpRequest at 'http://localhost:8080/user/loginOn' from origin 'http://localhost:8082' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
第一種:是在每個Controller里,加上注解:@CrossOrigin
import javax.validation.Valid;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController{
也可以在方法上加上,比如這樣,這樣針對具體的方法
@CrossOrigin
@ApiOperation(value = "用戶登錄",notes = "")
@PostMapping("/loginOn")
public ResponseMessage loginOn(@RequestBody @Valid UserReq userReq){
每一個Controller這樣寫也是很麻煩。
第二種:是實現(xiàn)WebMvcConfigurer接口,在接口中進行跨域支持
以前可以繼承WebMvcConfigurerAdapter,springboot2.x版本已經(jīng)將其@Deprecated
我們直接實現(xiàn)接口:
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 跨域支持
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600 * 24);
}
但使用這種方法,我今天遇到一個坑,我準備在攔截器里面對用戶的請求進行攔截
@Component
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object loginUser = request.getSession().getAttribute("token");
if(loginUser == null){
//自定義的異常類,這里拋出異常,交給全局異常捕捉類處理
throw new ServiceException("沒有權限,請先登錄!");
}else{
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
全局異常捕捉類:
@RestControllerAdvice
public class GlobleExceptionHandler {
@ExceptionHandler(value = ServiceException.class)
public ResponseMessage caughtException(ServiceException e){
return new ResponseMessage(e.getMsg());
}
}
ResponseMessage 是自定義的統(tǒng)一的響應信息類:
ResponseMessage
@Data
public class ResponseMessage {
private Integer Code;
private String msg;
private Integer count;
private Object data;
public ResponseMessage(Object data) {
this.data = data;
}
public ResponseMessage(String msg) {
this.msg = msg;
}
public ResponseMessage(Integer code, String msg) {
Code = code;
this.msg = msg;
}
public ResponseMessage(Integer code, String msg, Integer count) {
Code = code;
this.msg = msg;
this.count = count;
}
public ResponseMessage(Integer code, String msg, Integer count, Object data) {
Code = code;
this.msg = msg;
this.count = count;
this.data = data;
}
public static ResponseMessage success(String msg){
return new ResponseMessage(200,msg);
}
public static ResponseMessage fail(Integer code,String msg){
return new ResponseMessage(code,msg);
}
}
通過這樣的處理發(fā)現(xiàn),前端一直報跨域異常問題,這時候有了第三種方法
第三種:使用CorsFilter過濾器:
寫一個MyCorsConfig 配置類
@Configuration
public class MyCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//設置過濾器的順序
bean.setOrder(0);
return new CorsFilter(source);
}
}
最終解決本次demo的跨域問題。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
java抓取網(wǎng)頁數(shù)據(jù)獲取網(wǎng)頁中所有的鏈接實例分享
java抓取網(wǎng)頁數(shù)據(jù)獲取網(wǎng)頁中所有的鏈接實例分享,使用方法,只要實例化HtmlParser時傳入網(wǎng)頁地址就可以了2013-12-12
FutureTask為何單個任務僅執(zhí)行一次原理解析
這篇文章主要為大家介紹了FutureTask為何單個任務僅執(zhí)行一次原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
Mybatis基于xml配置實現(xiàn)單表的增刪改查功能
這篇文章主要介紹了Mybatis基于xml配置實現(xiàn)單表的增刪改查,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
Spring?Data?Elasticsearch?5.0.x修改數(shù)據(jù)后無法立即刷新解決方法示例
這篇文章主要為大家介紹了Spring?Data?Elasticsearch?5.0.x修改數(shù)據(jù)后無法立即刷新解決方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
SpringBoot入坑筆記之spring-boot-starter-web 配置文件的使用
本篇向小伙伴介紹springboot配置文件的配置,已經(jīng)全局配置參數(shù)如何使用的。需要的朋友跟隨腳本之家小編一起學習吧2018-01-01

