解决Java后端跨越问题拦截器WebMvcConfigurer

存笔记,方便以后Copy

前后端都需要解决跨域问题的方式有很多,Java解决的方式主要是添加注解的方式和采用添加拦截器的方法。

WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,提供很多自定义的拦截器,例如跨域设置、类型转化器等等

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 CorsConfig implements WebMvcConfigurer {
     
    @Override
    public void addCorsMappings(CorsRegistry registry) {
     
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

如果整合到Shiro+Jwt组合的安全拦截验证框架中,还需要再JwtFilter中加入,重写preHandle方法

@Component
public class JwtFilter extends AuthenticatingFilter {
     

    @Autowired
    JwtUtils jwtUtils;
	...... 
	.....
	....其他方法,例如AuthenticationToken,onAccessDenied....
	...
	..
	.
   
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
     
        //跨域处理
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求,这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
     
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }
}


你可能感兴趣的:(JAVA,java,后端,apache)