Spring MVC拦截器和跨域请求
Spring MVC 拦截器用于在控制器处理请求之前或之后执行某些操作。跨域请求问题通常涉及到浏览器的同源策略,阻止来自不同源的Web页面请求访问其他源的资源。
- 创建一个Spring MVC拦截器:
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 在请求处理之前进行调用(如:权限校验、日志记录)
return true; // 如果返回false,则停止流程,api不会被调用
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// 请求处理之后进行调用,但是在视图被渲染之前(如:数据封装、处理模板)
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 在整个请求结束之后调用,也就是在DispatcherServlet渲染了视图执行
}
}
- 注册拦截器:
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomInterceptor())
.addPathPatterns("/**") // 拦截所有请求路径
.excludePathPatterns("/login", "/error"); // 排除登录和错误处理路径
}
}
- 处理跨域请求:
import org.springframework.context.annotation.Bean;
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 {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域的路径
.allowedOrigins("http://domain2.com") // 允许哪些域进行跨域请求
评论已关闭