[SpringBoot] cross domain, filter and swaggerUI configuration

Posted by mrgrammar on Tue, 15 Oct 2019 21:45:23 +0200

1. springboot WebAppConfig configuration

 * Created with IntelliJ IDEA.
 * @author: zhangenke @Date: 2018/8/16 on 2:25 p.m.
 * @description: Let springBoot know that there is this interceptor
public class WebAppConfig extends WebMvcConfigurationSupport {
  // The following rewriting interfaces are commonly used by WebMvcConfigurerAdapter
  // Solve cross domain problems**/
  //    public void addCorsMappings(CorsRegistry registry) ;
  // Add interceptor**/
  //    void addInterceptors(InterceptorRegistry registry);
  // Configuration of view resolver here**/
  // View jump controller**/
  //    void addViewControllers(ViewControllerRegistry registry);
  //    void configureViewResolvers(ViewResolverRegistry registry);
  // Some options for configuring content adjudication**/
  //    void configureContentNegotiation(ContentNegotiationConfigurer configurer);
  // View jump controller**/
  //    void addViewControllers(ViewControllerRegistry registry);
  // Static resource processing**/
  //    void addResourceHandlers(ResourceHandlerRegistry registry);
  // Default static resource processor**/
  //    void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
  // private final ProcureInterceptor procureInterceptor;
  // @Autowired
  // public WebAppConfig(ProcureInterceptor procureInterceptor) {
  //    this.procureInterceptor = procureInterceptor;
  // }
  private final TokenUtils tokenUtils;
  private final TokenDao tokenDaoImpl;
  public WebAppConfig(TokenUtils tokenUtils, TokenDao tokenDaoImpl) {
    this.tokenUtils = tokenUtils;
    this.tokenDaoImpl = tokenDaoImpl;
  public ProcureInterceptor getProcureInterceptor() {
    return new ProcureInterceptor(tokenUtils, tokenDaoImpl);
  public void addInterceptors(InterceptorRegistry registry) {
    // Multiple interceptors form an interceptor chain
    // addPathPatterns to add interception rules
    // excludePathPatterns user exclusion
    log.info("tokenUtils:{}", tokenUtils);
    log.info("tokenDaoImpl:{}", tokenDaoImpl);
    log.info("WebAppConfig Interceptor injection succeeded:**********************************************");
    // log.info("procureInterceptor:{}", procureInterceptor);
    // registry.addInterceptor(new ProcureInterceptor(tokenUtils,
    // tokenDaoImpl)).addPathPatterns("/**")
    // Intercept requests from the link / user / *;
    // super.addInterceptors(registry);
    // registry.addInterceptor(getInterfaceAuthCheckInterceptor()
    // This way, no matter what.
    // registry.addInterceptor(new InterfaceAuthCheckInterceptor())
    // In this case, the custom interceptor cannot inject other content, such as redis or other service s. If you want to inject, you must use the above method.
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
   * @param [configurer]
   * @return void
   * @author chaosgod 2018/10/17 11:34 a.m.
   * @description : Configure access to static files
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    FastJsonConfig config = new FastJsonConfig();
    // SerializerFeature.WriteNullListAsEmpty: output [] instead of null when the List type field is null
    // SerializerFeature.WriteMapNullValue: show empty fields
    // SerializerFeature.WriteNullStringAsEmpty: output '' instead of null when string type field is null
    // Serializerfeature.writenullboolean asfalse: output false and null when Boolean type field is null
    // SerializerFeature.PrettyFormat: Beautify json output, otherwise it will be output as the whole line
  // @Override
  // protected void addCorsMappings(CorsRegistry registry) {
  //    registry.addMapping("/**");
  //    super.addCorsMappings(registry);
  // }

2. ProcureInterceptor configuration

 * @author zhangenke
public class ProcureInterceptor implements HandlerInterceptor {
    private static final String VALUE = "false";
    private static final String OPTIONS = "OPTIONS";
    private final SessionService sessionServiceImpl;
    public ProcureInterceptor(SessionService sessionServiceImpl) {
        this.sessionServiceImpl = sessionServiceImpl;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String[] noFilters = new String[]{"login", "errorSession", "swagger", "images", "v2"};
        String uri = request.getRequestURI();
        boolean beFilter = true;
        log.info("Request address uri:{}", uri);
        log.info("Request method:{}", request.getMethod());
        // Pre request
        if (OPTIONS.equals(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, " +
                    "Content-Type, Accept,sessionId");
            return true;
        // Configure cross domain
        response.setHeader("Access-Control-Allow-Origin", "*");
        String requestId = request.getHeader("X-REQUEST-ID");
        String userAgent = request.getHeader("User-Agent");
        if (requestId != null) {
            MDC.put("requestUUID", requestId);
        if (userAgent != null) {
            MDC.put("User-Agent", userAgent);
        log.info("variable:{}", JSON.toJSONString(request.getParameterMap()));
        String sessionId = request.getHeader("sessionId");
        log.info("Headers-sessionId: {}", sessionId);
        for (String s : noFilters) {
            if (uri.contains(s)) {
                beFilter = false;
        String origin = request.getHeader("Origin");
        log.info("Request received Origin For:{}", origin);
        // todo
        return true;
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) {
        // TODO Auto-generated method stub

As shown in the figure above, this configuration is enough.

2018-10-23 optimization, which can be tested by swagger UI and static files

2019-01-22 optimization, local test can be passed at will. When Linux is online, there will be cross domain occasionally, but after repackaging, it can be passed again.

At present, no solution to this problem has been found.

(it may be related to Linux. After killing the process, if Enter goes online again until the prompt that the process is killed appears, it can pass.)
Author: Uncle evil spirit
Source: CSDN
Original: https://blog.csdn.net/qq_/article/details/83058281
Copyright notice: This is the original article of the blogger. Please attach the link of the blog!

Topics: SpringBoot JSON Linux IntelliJ IDEA