攔截器參考: https://www.jianshu.com/p/e52444f0a121
跨域參考: https://www.cnblogs.com/yuansc/p/9076604.html
創建一個Config
來注冊攔截器,代碼如下:
MyMvcConfig -----這個意義是 讓配置的一些接口,不需要走攔截器的邏輯
package com.config;
import com.controle.lanjie.LoginHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//所有的WebMvcConfigurerAdapter組件都會一起起作用
@Bean //將組件注冊在容器中
public WebMvcConfigurer webMvcConfigurerAdapter(){
return new WebMvcConfigurer(){
//注冊攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//靜態資源; *.css,*.js
//SpringBoot已經做好了靜態資源映射
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**");
// .excludePathPatterns("/index.html","/","/user/login","/static/**","/webjars/**");
// /** 表示攔截所有路徑下的所有請求
// registry.addInterceptor(new LoginHandlerInterceptor())
// .addPathPatterns("/person.html","/Person.html",
// "/questionnaire.html","/Questionnaire.html",
// "/result.html","/Result.html");
}
};
}
}
創建一個攔截器
LoginHandlerInterceptor
package com.controle.lanjie;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
//目標方法執行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//--------------------------------------------------------添加請求頭,允許跨域----方法一
setHeader(name, value):如果Header中沒有定義則添加,如果已定義則用新的value覆蓋原用value值。
addHeader(name, value):如果Header中沒有定義則添加,如果已定義則保持原有value不改變。
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Headers", "*");
//Access-Control-Allow-Methods: 真實請求允許的方法
//Access-Control-Allow-Headers: 服務器允許使用的字段
//Access-Control-Allow-Credentials: 是否允許用戶發送、處理 cookie
//Access-Control-Max-Age: 預檢請求的有效期,單位為秒。有效期內,不會重復發送預檢請求
//獲取請求參數
Object user5 = request.getQueryString();
System.out.println(user5);
//獲取請求頭參數
Object user6 = request.getHeader("currentUser");
System.out.println(user6);
//獲取請求方式
Object user7 = request.getMethod();
System.out.println(user7);
//獲取請求路徑
Object user8 = request.getRequestURI();
System.out.println(user8);
//重定向訪問路徑
response.sendRedirect("/bbb2");
// 添加請求頭
response.addHeader("location","http://baidu.com");
// if (user == null) {
// //未登錄,返回登錄頁面
// System.out.println("第一攔截了,請求前");
//// response.sendRedirect("/LoginError.html");
// return false;
// }else {
// //放行
return true;
// }
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("第二攔截了,請求中");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println("第三攔截了,請求后");
}
}
允許前端跨域方法二 ----添加全局配置類
package com.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 跨域支持
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.allowedHeaders("*")
.maxAge(3600 * 24);
}
}
還可以通過添加 Filter 的方式,配置 CORS 規則,並手動指定對哪些接口有效。---這個我沒試過,上面2種親測ok
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:9000");
config.addAllowedOrigin("null");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config); // CORS 配置對所有接口都有效
FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
三更草堂是向下面那樣寫的 親測成功
bilibili.com/video/BV1U44y1W77D
package com.qingge.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 當前跨域請求最大有效時長。這里默認1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 設置訪問源地址
corsConfiguration.addAllowedHeader("*"); // 2 設置訪問源請求頭
corsConfiguration.addAllowedMethod("*"); // 3 設置訪問源請求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 對接口配置跨域設置
return new CorsFilter(source);
}
}
增加跨域配置解決的方法見 https://www.cnblogs.com/kaibindirver/p/16189077.html