【问题标题】:How can I add request parameters to a static HTML page using Spring Boot?如何使用 Spring Boot 将请求参数添加到静态 HTML 页面?
【发布时间】:2018-05-16 00:58:38
【问题描述】:

我想要做的是添加到我的静态 HTML 页面的 URL 以具有请求参数。随后,页面应该使用它们并使用请求参数中的值调用我的 Java api(在同一模块中)以动态构建 HTML 表。我试图通过ResourceHandlerRegistry 像这样添加到 URL:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("status.html")
                .addResourceLocations("classpath:/META-INF/resources/");
}

并将方法更改为具有请求参数:

registry.addResourceHandler("status.html?testparam=")
                    .addResourceLocations("classpath:/META-INF/resources/");

但是当我尝试这样做时会出现 404 错误。

我们的目标是让页面是动态的,以便根据他们添加的请求参数的值为某人创建它。我知道参数可以用javascript解析,只是把它们放到页面上。

在我看来,这不需要更改 java 代码,但如果可能的话,我不确定执行此操作的最佳方法。

【问题讨论】:

    标签: java html spring


    【解决方案1】:

    为此,您无需定义单独的资源处理程序。只需将您的 status.html 文件保存在任何默认静态资源位置即可

    classpath:/META-INF/resources/
    classpath:/resources/
    classpath:/static/
    classpath:/public/
    

    您可以使用 application.properties 文件中的 spring.resources.static-locations 属性修改/添加/删除这些默认位置。您可以添加位置。甚至像这样的文件系统中的 jar 之外的位置

    spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/path/to/static/directory
    

    并以

    的身份正常访问您的页面
    http://host:port/status.html?testparam=value
    

    或者您可以使用您在问题中提到的资源处理程序添加静态位置。

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("abc")
                    .addResourceLocations("file:/path/to/static/directory");
    }
    

    这里的所有静态资源都将通过您的网址的前缀“abc”访问

    http://host:port/abc/status.html?testparam=value
    

    现在在您的 status.html 中,您可以访问 url 参数并以您想要的方式使用它们。参考javascript中访问url参数的简单方法-https://css-tricks.com/snippets/javascript/get-url-variables/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2019-02-14
      • 2015-10-30
      • 2012-04-14
      • 1970-01-01
      • 2016-09-22
      • 2015-07-09
      相关资源
      最近更新 更多