首页 > 解决方案 > Spring boot 2:为每种语言映射 addResourceHandler 返回 404

问题描述

我正在尝试设置以根据 URL 中的语言参数提供静态内容,我得到404了,以下代码中的映射有什么问题?

在此处输入图像描述

private PathResourceResolver getResolver() {
        return new PathResourceResolver() {
            @Override
            protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
                logger.info("REQ PATH :: " + requestPath + "   " + locations);
                return super.resolveResourceInternal(request, requestPath, locations, chain); //To change body of generated methods, choose Tools | Templates.
            }
        };
    }

和静态文件夹结构:

在此处输入图像描述

404以下是我尝试访问 URL 时显示的完整日志https://localhost:8443/fr

在此处输入图像描述

标签: springspring-bootspring-mvc

解决方案


我能够解决这个问题,如果其他人遇到类似的问题,下面的解决方案对我有用。

addResourceLocations路径必须以/否则该StringUtils applyRelativePath方法将删除提供的路径的最后一部分,在我的情况下en|fr|de..

    /**
     * Apply the given relative path to the given Java resource path,
     * assuming standard Java folder separation (i.e. "/" separators).
     * @param path the path to start from (usually a full file path)
     * @param relativePath the relative path to apply
     * (relative to the full file path above)
     * @return the full file path that results from applying the relative path
     */
    public static String applyRelativePath(String path, String relativePath) {
        int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
        if (separatorIndex != -1) {
            String newPath = path.substring(0, separatorIndex);
            if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
                newPath += FOLDER_SEPARATOR;
            }
            return newPath + relativePath;
        }
        else {
            return relativePath;
        }
    }

推荐阅读