springboot跨域問(wèn)題解決方案
這篇文章主要介紹了springboot跨域問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
springboot中的跨域問(wèn)題,如果不注意的話,容易造成錯(cuò)誤,本次springboot版本為2.13
前端錯(cuò)誤信息:
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.
第一種:是在每個(gè)Controller里,加上注解:@CrossOrigin
import javax.validation.Valid;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController{
也可以在方法上加上,比如這樣,這樣針對(duì)具體的方法
@CrossOrigin
@ApiOperation(value = "用戶登錄",notes = "")
@PostMapping("/loginOn")
public ResponseMessage loginOn(@RequestBody @Valid UserReq userReq){
每一個(gè)Controller這樣寫也是很麻煩。
第二種:是實(shí)現(xiàn)WebMvcConfigurer接口,在接口中進(jìn)行跨域支持
以前可以繼承WebMvcConfigurerAdapter,springboot2.x版本已經(jīng)將其@Deprecated
我們直接實(shí)現(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);
}
但使用這種方法,我今天遇到一個(gè)坑,我準(zhǔn)備在攔截器里面對(duì)用戶的請(qǐng)求進(jìn)行攔截
@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("沒(méi)有權(quán)限,請(qǐng)先登錄!");
}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)一的響應(yī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);
}
}
通過(guò)這樣的處理發(fā)現(xiàn),前端一直報(bào)跨域異常問(wèn)題,這時(shí)候有了第三種方法
第三種:使用CorsFilter過(guò)濾器:
寫一個(gè)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));
//設(shè)置過(guò)濾器的順序
bean.setOrder(0);
return new CorsFilter(source);
}
}
最終解決本次demo的跨域問(wèn)題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
通過(guò)java字節(jié)碼分析學(xué)習(xí)對(duì)象初始化順序
今天用了jmock對(duì)進(jìn)行單元測(cè)試編碼,發(fā)現(xiàn)一個(gè)比較奇怪的語(yǔ)法,static使用方法,見下面例子2013-11-11
淺談resultMap的用法及關(guān)聯(lián)結(jié)果集映射
這篇文章主要介紹了resultMap的用法及關(guān)聯(lián)結(jié)果集映射操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java FileDescriptor總結(jié)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
FileDescriptor 是“文件描述符”??梢员挥脕?lái)表示開放文件、開放套接字等。接下來(lái)通過(guò)本文給大家分享Java FileDescriptor總結(jié),感興趣的朋友一起學(xué)習(xí)吧2017-05-05
使用Java和Selenium實(shí)現(xiàn)滑塊驗(yàn)證的自動(dòng)化登錄功能
在現(xiàn)代Web應(yīng)用中,滑塊驗(yàn)證碼被廣泛用于防止自動(dòng)化腳本的濫用,滑塊驗(yàn)證通常要求用戶通過(guò)拖動(dòng)滑塊來(lái)完成驗(yàn)證,然而,在某些場(chǎng)景下,如自動(dòng)化測(cè)試或批量登錄,我們需要通過(guò)編程手段解決滑塊驗(yàn)證問(wèn)題,本文將詳細(xì)介紹如何使用Java和Selenium實(shí)現(xiàn)滑塊驗(yàn)證的自動(dòng)化登錄2025-01-01
java ThreadLocal線程局部變量常用方法使用場(chǎng)景示例詳解
這篇文章主要介紹了為大家java ThreadLocal線程局部變量常用方法使用場(chǎng)景示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
struts2攔截器_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
如何使用struts2攔截器,或者自定義攔截器。下面通過(guò)實(shí)例代碼給大家分享struts2攔截器的相關(guān)知識(shí),感興趣的朋友參考下吧2017-09-09

