【问题标题】:Java/Spring-Boot Webapp not Serving Assets from Public Resources DirectoryJava/Spring-Boot Webapp 不提供公共资源目录中的资产
【发布时间】:2017-07-05 17:24:05
【问题描述】:

我正在开发一个由 Spring-Boot 提供服务的 AngularJS 应用程序。我正在升级我们的构建管道以包含 Webpack。 Webpack 将所有源代码捆绑到 /src/main/resources/static 目录中,我被告知应该由 Spring-Boot 自动提供该目录。然而,当我尝试通过导航到http://localhost:8080 来测试这一点时,index.html 页面正在被提供,但各种 JS 包没有。下面是一些相关的配置文件:

webpack.config.js

/*global process, module, __dirname*/

const path = require('path');
const proxyMiddleware = require('proxy-middleware');
const url = require('url');
const webpack = require('webpack');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');

const PATHS = {
    app: path.join(__dirname, './src/main/webapp'),
    dist: path.join(__dirname, './src/main/resources/static'),
    test: path.join(__dirname, './src/test/webapp')
};

const isDevelopment = process.env.NODE_ENV === 'develop';
const isE2E = process.env.NODE_ENV === 'e2e';
const isTest = process.env.NODE_ENV === 'test';
const isProd = process.env.NODE_ENV === 'production';

// Webpack Loaders
const fontRule = {
    test: /\.(eot|svg|ttf|woff|woff2)$/,
    loader: 'file-loader',
    options: {
        name: '[name].[sha1:hash:base64:32].[ext]'
    }
};

const htmlRule = {
    test: /\.html$/,
    loader: 'html-loader',
    query: {
        minimize: isProd
    }
};

const imageRule = {
    test: /\.png$/i,
    loader: 'url-loader',
    options: {
        limit: 8192,
        mimetype: 'image/png'
    }
};

const javasscriptPreRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    enforce: 'pre',
    loader: 'eslint-loader'
};

const javascriptRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'babel-loader'
};

const sassRule = {
    test : /\.scss$/,
    use: ExtractTextPlugin.extract({
        use: [ 'css-loader', 'resolve-url-loader', 'sass-loader?sourceMap' ]
    })
};

const entry = {
    app: (() => {
        let app = [ path.join(PATHS.app, 'app.js') ];

        if (isProd || isE2E) {
            app.push(path.join(PATHS.app, 'app.prod.js'));
        } else {
            app.push(path.join(PATHS.app, 'app.mock.js'));
        }

        return app;
    })()
};

const output = {
    path: PATHS.dist,
    filename: isProd ? '[name].[chunkhash].js' : '[name].js'
};

const plugins = (() => {
    let plugins = [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks(module) {
                return module.context
                    && module.context.indexOf('node_modules') !== -1;
            }
        }),

        new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' }),

        new ExtractTextPlugin(isProd ? 'styles.[contenthash].css' : 'styles.css'),

        new HtmlWebpackPlugin({ template: path.join(PATHS.app, 'index.html') }),

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
        })
    ];

    if (isProd) {
        plugins = plugins.concat([
            new webpack.optimize.UglifyJsPlugin({
                beautify: false,
                comments: false,
                compress: {
                    warnings: false
                }
            }),

            new webpack.optimize.OccurrenceOrderPlugin(),

            new OptimizeCssAssetsWebpackPlugin({
                cssProcessorOptions: {
                    discardComments: { removeAll: true }
                }
            })
        ]);
    } else {
        const server = (() => {
            let server = {
                baseDir: PATHS.dist
            };

            // Internal testing server configurations...

            return server;
        })();

        plugins.push(
            new BrowserSyncPlugin({
                host: 'localhost',
                port: 3000,
                server
            })
        )
    }

    return plugins;
})();

function proxy(target) {
    let options = url.parse(target);
    options.route = '/api';

    return proxyMiddleware(options);
}

module.exports = {
    entry,
    output,
    plugins,
    module: {
        rules: [ fontRule, htmlRule, imageRule, javasscriptPreRule, javascriptRule, sassRule ]
    }
};

WebSecurityConfig.java

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements InitializingBean {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // Internal security configurations
                .and()
                .authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                    .anyRequest().permitAll();
    }

}

这里是存储在/src/target/classes/static中的静态文件:

这是打开浏览器时没有显示 JS 文件的证据:

【问题讨论】:

  • 发布target/classes/static的目录输出。这是一个巨大的 Webpack 配置转储,但它并没有清楚地表明文件保存在正确的位置(或在正确的时间,在 Maven 中是 generate-resources 阶段)。
  • 我已经用target/classes/static的截图更新了我原来的帖子。
  • 好的,看起来这些就在那里。你的网络选项卡怎么样——你得到 404 了吗?还有什么?
  • 只获取 HTML 文件,遗憾的是没有其他资源。
  • 这不是答案。它没有说明其他资源是否没有被请求(您没有包含script 标签),或者是否存在其他问题(带有确切的错误消息)。跨度>

标签: java angularjs spring spring-mvc


【解决方案1】:

我发现了我遇到的问题。 Spring-Boot 仍然默认使用src/main/webapp 来提供前端代码。虽然该目录中有一个index.html 文件,但它不包含Webpack 生成的JavaScript 包的<script> 标签; Webpack 负责自动添加这些标签。我不得不更改加载捆绑文件的目录。

为此,我编辑了src/main/resources/application.properties 文件,并添加了以下行:

spring.resources.static-locations=classpath:/static/

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 2016-07-08
    • 1970-01-01
    • 2014-04-04
    • 2020-12-02
    相关资源
    最近更新 更多